如何使用 Intent 选择 Google 文档文件(保存在 Google 驱动器上)?

How to enable picking Google Docs files (kept on Google Drive) with Intent?

我想在我的 Android 应用程序中选择 Google 保存在 Google 驱动器上的文档文件,然后从中读取一些数据(但它不在这个范围内)问题的范围)。所以一开始我只想单击该文件并获得一些回调。我关注 this recommendations on Google Drive Android API Deprecation and migration to Google Drive Rest API.

我设法与 Google Drive 文件列表进行对话,但我无法选择 Google Docs 文件(我可以看到它们,但无法点击它们)。同时我可以选择其他类型的文件——例如 PDF、PNG,如果我设置它们的 MIME 类型。

现在我使用这段代码:

val pickerIntent = Intent(Intent.ACTION_OPEN_DOCUMENT)
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
pickerIntent.type = "*/*"
val mimeTypes = arrayOf(
     "application/pdf", // works
     "image/png", //works
     // none of MIME below works
     "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
     "application/vnd.google-apps.document",
     "application/vnd.google-apps.file"
)
pickerIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)

official sample中他们用MIME "text/plain"作为例子,所以对我没有帮助。

我尝试了几种我能找到的 MIME 类型(例如 here and here),但它们都没有解决问题。

为此应该使用什么 MIME 类型?或者问题不在 MIME 类型中?

我在 this official documentation's article 中找到了问题的根源。

问题是 Google Doc 文件 - 与 "real" PDF|PNG 文件不同,它们是所谓的 "virtual" 文件,因为它们没有二进制表示。

我的问题的明确答案是文档中的下一条注释:

Note: Because an app cannot directly open a virtual file by using the openInputStream() method, don't use the CATEGORY_OPENABLE category when creating the intent that contains the ACTION_OPEN_DOCUMENT or ACTION_OPEN_DOCUMENT_TREE action

所以在我删除下一行后问题就解决了:

pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)

此外,我可以承认,Google Doc 的选择器过滤器与下一个 MIME 配合得很好:

"application/vnd.google-apps.document"