Android中如何通过文件名获取开发者Google Drive特定文件ID?
Hey there! Let's break down your two questions step by step, since they cover different use cases (personal Drive vs. a developer/service account Drive on Android).
1. How to Find a Google Drive File ID by Filename (Personal User Account)
Web UI Method (No Code Needed)
- Open your Google Drive in a web browser and locate the target file.
- Either right-click the file and select "Get link", or open the file directly.
- In the resulting URL, look for the string between
d/and/view(or/edit). That’s your file ID!Example URL:
https://drive.google.com/file/d/123abcXYZ789/view?usp=sharing→ File ID is123abcXYZ789
Using the Google Drive API (Programmatic Approach)
If you need to automate this, use the Drive API's files.list endpoint with a filename filter:
- Enable the Drive API in your Google Cloud Project and set up OAuth 2.0 authentication (for personal accounts).
- Use the
qparameter to filter files:name='YourExactFileName'(case-sensitive by default; usecontainsinstead of=for partial matches). - Request only the
idandnamefields to keep responses lightweight.
Here’s a quick Python example:
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # Load OAuth 2.0 credentials (from a token.json file) creds = Credentials.from_authorized_user_file('token.json', ['https://www.googleapis.com/auth/drive.readonly']) # Build the Drive service drive_service = build('drive', 'v3', credentials=creds) # Search for the file by name results = drive_service.files().list( q="name='MyTargetFile.pdf'", fields="files(id, name)" ).execute() items = results.get('files', []) if not items: print('No files found.') else: print('Matching files:') for item in items: print(f'{item["name"]} ({item["id"]})')
2. Get File ID by Filename from a Developer/Service Account Drive on Android
Absolutely achievable! This uses a Google Service Account (a dedicated account for your app, separate from user accounts) to access its own isolated Drive storage. Here’s how to set it up:
Prerequisites
- Create a Service Account in your Google Cloud Project and download its JSON key file.
- Enable the Drive API for your project.
- Ensure target files are stored in the Service Account’s Drive, or shared with the Service Account’s email address.
Android Implementation Steps
- Add required dependencies to your app’s module-level
build.gradle:
dependencies { implementation 'com.google.api-client:google-api-client-android:1.34.1' implementation 'com.google.apis:google-api-services-drive:v3-rev20220606-2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' }
- Load Service Account credentials and authenticate:
Store the JSON key file inres/raw/and load it to get a valid credential:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import java.io.InputStream; import java.util.Collections; // Inside your Activity/ViewModel private Drive getDriveService() throws Exception { InputStream inputStream = getResources().openRawResource(R.raw.service_account_key); GoogleCredential credential = GoogleCredential.fromStream(inputStream) .createScoped(Collections.singleton(DriveScopes.DRIVE_READONLY)); return new Drive.Builder( new NetHttpTransport(), GsonFactory.getDefaultInstance(), credential) .setApplicationName("YourAppName") .build(); }
- Fetch the File ID by Filename
Use thefiles.listmethod with a filename filter (run network operations off the main thread):
import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import android.util.Log; private void fetchFileIdByFilename(String targetFilename) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { try { Drive driveService = getDriveService(); FileList result = driveService.files().list() .setQ("name='" + targetFilename + "'") .setFields("files(id, name)") .execute(); // Return first matching file ID (handle duplicates if needed) for (File file : result.getFiles()) { return file.getId(); } return null; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String fileId) { if (fileId != null) { Log.d("DriveService", "Found file ID: " + fileId); // Use the ID in your app logic } else { Log.d("DriveService", "No matching file found"); } } }.execute(); }
Key Notes
- Service Accounts have their own isolated Drive—personal Drive files won’t be accessible unless shared with the Service Account’s email.
- For modern Android, replace
AsyncTaskwith Coroutines or WorkManager for better lifecycle compliance. - Add extra filters (like
mimeTypeormodifiedTime) if multiple files share the same filename.
内容的提问来源于stack exchange,提问作者user3658352
相关产品推荐
相关产品推荐

