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

Android无需Google Drive API集成获取Drive文档选择器Intent问题

Android: getPickChooserIntent works for images from Google Drive but fails for PDFs (no Drive API allowed)

I'm developing an Android app that uses getPickChooserIntent to select files from Google Drive. This function works fine for images but fails to handle documents like PDFs. Note: I don't want to integrate the Google Drive API.

Relevant Code

getPickChooserIntent method:

public static Intent getPickChooserIntent( @NonNull Context context, CharSequence title, boolean includeDocuments, boolean includeCamera) { 
    List<Intent> allIntents = new ArrayList<>(); 
    PackageManager packageManager = context.getPackageManager(); 

    // collect all camera intents if Camera permission is available 
    if (!isExplicitCameraPermissionRequired(context) && includeCamera) { 
        allIntents.addAll(getCameraIntents(context, packageManager)); 
    } 

    List<Intent> galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_GET_CONTENT, includeDocuments); 
    if (galleryIntents.size() == 0) { 
        // if no intents found for get-content try pick intent action (Huawei P9). 
        galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_PICK, includeDocuments); 
    } 
    allIntents.addAll(galleryIntents); 

    Intent target; 
    if (allIntents.isEmpty()) { 
        target = new Intent(); 
    } else { 
        target = allIntents.get(allIntents.size() - 1); 
        allIntents.remove(allIntents.size() - 1); 
    } 

    // Create a chooser from the main intent 
    Intent chooserIntent = Intent.createChooser(target, title); 
    // Add all other intents 
    chooserIntent.putExtra( Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()])); 
    return chooserIntent; 
}

getPickImageResultUri method (works for images):

public static Uri getPickImageResultUri(@NonNull Context context, @Nullable Intent data) { 
    boolean isCamera = true; 
    if (data != null && data.getData() != null) { 
        String action = data.getAction(); 
        isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE); 
    } 
    return isCamera || data.getData() == null ? getCaptureImageOutputUri(context) : data.getData(); 
}

The Issue

When selecting images, I get a URI like content://com.google.android.apps.docs.storage.legacy/enc%3D8HXM7NIDpCn_Ax78iaO3nB9azNXlIu4AOk2poROCD8xP19KU%0A which loads fine into an ImageView. However, when selecting PDFs or other documents, this setup doesn't work correctly.

Is there a way to fix this without integrating the Google Drive API?


Solution

Let's work through this step by step—no Google Drive API required to get this working:

1. Fix the Intent MIME Type Filter

The root issue here is likely that your getGalleryIntents method is restricting selections to image-only MIME types, even when includeDocuments is enabled. To support PDFs and other documents, update the method to accept broader file types:

private static List<Intent> getGalleryIntents(PackageManager packageManager, String action, boolean includeDocuments) {
    List<Intent> intents = new ArrayList<>();
    Intent baseIntent = new Intent(action);
    
    if (includeDocuments) {
        // Accept all file types, or specify specific ones like "application/pdf", "text/plain" if needed
        baseIntent.setType("*/*");
    } else {
        // Keep image-only filter for non-document cases
        baseIntent.setType("image/*");
    }
    
    List<ResolveInfo> resInfo = packageManager.queryIntentActivities(baseIntent, 0);
    for (ResolveInfo info : resInfo) {
        Intent intent = new Intent(baseIntent);
        intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
        intents.add(intent);
    }
    return intents;
}

2. Replace Image-Specific URI Handling with Generic Logic

Your getPickImageResultUri method is built exclusively for images and includes camera-focused logic that breaks document selection. Create a generic version for all file types:

public static Uri getPickFileResultUri(@NonNull Context context, @Nullable Intent data) {
    // Fall back to camera output only if data is null (relevant only for image capture)
    if (data == null || data.getData() == null) {
        return getCaptureImageOutputUri(context);
    }
    // For documents, return the direct URI from the intent
    return data.getData();
}

3. Correctly Read Document Content

Images can load directly into an ImageView, but documents like PDFs need to be read via ContentResolver (since Google Drive uses content URIs, not raw file paths). Here's how to handle the input stream:

// Example: Process a selected PDF file
Uri fileUri = getPickFileResultUri(context, data);
ContentResolver resolver = getContentResolver();

try (InputStream inputStream = resolver.openInputStream(fileUri)) {
    // Use the input stream to save to a temp file, pass to a PDF viewer, etc.
    File tempFile = new File(getCacheDir(), "temp_document.pdf");
    try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    }
    // Now you can use tempFile to open the document with a viewer or process it further
} catch (IOException e) {
    e.printStackTrace();
    // Show an error message to the user, e.g., Toast.makeText(context, "Failed to read file", Toast.LENGTH_SHORT).show();
}

4. Optional: Use ACTION_OPEN_DOCUMENT for Better Document Support

For more reliable long-term access to documents, consider adding Intent.ACTION_OPEN_DOCUMENT alongside your existing ACTION_GET_CONTENT intent. This action is specifically designed for document selection and can improve compatibility with apps like Google Drive.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:47:30