首页 > 解决方案 > 通过 Intent 共享 Google 文件类型

问题描述

我正在尝试共享 Google 文件类型(例如:application/vnd.google-apps.document、application/vnd.google-apps.form、application/vnd.google-apps.presentation、application/vnd.google-apps。电子表格)与意图。

我的代码:

private void shareFile(String uri) {
    ContentResolver contentResolve = getContentResolver();
    String mimeType = contentResolve.getType(Uri.parse(uri));
    Intent intentShareFile = new Intent(Intent.ACTION_SEND);
    intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intentShareFile.putExtra(Intent.EXTRA_STREAM,
            Uri.parse(uri));
    intentShareFile.setType(mimeType);
    intentShareFile.putExtra(Intent.EXTRA_TEXT, "Hey, check out this file!");

    startActivity(Intent.createChooser(intentShareFile, "Share File"));
}

但是当我单击一个应用程序来共享该文件时,它没有响应,也没有做任何事情。即使我尝试将其上传到 Google Drive 上,它也会说上传不成功。当我共享 pdf 或 docx 文件时,共享文件工作正常。

显然,我们无法通过 Intent 共享 Google 文件类型。我们必须将具有 Google 文件类型的文件转换为 Microsoft 文件类型(application/vnd.openxmlformats-officedocument.wordprocessingml.document、application/msword、application/vnd.ms-excel、application/vnd.openxmlformats-officedocument。 spreadsheetml.sheet、application/x-excel、application/vnd.ms-powerpoint 或 application/vnd.openxmlformats-officedocument.presentationml.presentation)。

有什么方法可以转换 URI mimeType,以便我可以共享具有 Google 文件类型的文件?例如,将 application/vnd.google-apps.document 作为 mimeType 的文件更改为 application/vnd.openxmlformats-officedocument.wordprocessingml.document,将 application/vnd.google-apps.presentation 更改为 application/vnd.openxmlformats- officedocument.presentationml.presentation 等。有没有办法做到这一点,以便我可以共享具有 Google 文件类型的文件?任何帮助将不胜感激,谢谢!

标签: androidandroid-intent

解决方案


像这样做:

Intent uploadIntent = ShareCompat.IntentBuilder.from(this)
                    .setType(mimeType)
                    .setStream(fileUri)
                    .getIntent()
                    .setPackage("com.google.android.apps.docs");
            startActivity(uploadIntent)

请注意setStream需要 Uri。


推荐阅读