You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 is 123abcXYZ789

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:

  1. Enable the Drive API in your Google Cloud Project and set up OAuth 2.0 authentication (for personal accounts).
  2. Use the q parameter to filter files: name='YourExactFileName' (case-sensitive by default; use contains instead of = for partial matches).
  3. Request only the id and name fields 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

  1. 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'
}
  1. Load Service Account credentials and authenticate:
    Store the JSON key file in res/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();
}
  1. Fetch the File ID by Filename
    Use the files.list method 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 AsyncTask with Coroutines or WorkManager for better lifecycle compliance.
  • Add extra filters (like mimeType or modifiedTime) if multiple files share the same filename.

内容的提问来源于stack exchange,提问作者user3658352

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:21