5

我尝试通过手动启动 Google 驱动器(安装在设备上)从我的 android 应用程序上传文件。我试过这个发送使用Intent.createChooser和上传文件附件的工作正常。但我需要上传特定意图的文件(如 Dropbox,仅限 Google 驱动器)。所以我更改了代码并尝试通过以下方式将文件上传到谷歌驱动器,但没有成功,只有谷歌驱动器应用程序在设备上打开,没有上传文件:

PackageManager pm = this.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.google.android.apps.docs");
intent.setType("application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://sdcard/sdcard0/test.pdf"));
intent.putExtra(Intent.EXTRA_SUBJECT, "attach a file test");
intent.addCategory(Intent.ACTION_ATTACH_DATA);
startActivity(intent);

我们可以像上面那样通过手动打开意图来上传 PDF 文件吗?

4

1 回答 1

17

经过研究,我得到了执行以下代码的解决方案:

import android.support.v4.app.ShareCompat;

Uri pdfUri = Uri.parse("file://sdcard/sdcard0/test.pdf");                
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                                     .setText("Share PDF doc")
                                         .setType("application/pdf")
                                         .setStream(pdfUri )
                                         .getIntent()
                                 .setPackage("com.google.android.apps.docs");
startActivity(shareIntent);

同样我们可以用于其他的分享意图,几个意图对应的包名如下:

  • com.dropbox.android = Dropbox
  • com.android.bluetooth = 蓝牙
  • com.android.email = 电子邮件
  • com.google.android.gm = 邮箱
  • com.microsoft.skydrive = Skydrive
  • com.google.android.apps.docs = Googledrive

对于 gmail 共享,我们需要使用以下类型的代码:

Uri zipUri = Uri.parse("file://sdcard/sdcard0/test.zip");  
String[] emailArr = {"test@gmail.com"};              
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                                  .setText("Share ZIP doc")
                                  .setType("application/zip")
                                  .setEmailTo(emailArr)
                                  .setStream(zipUri)
                                  .setSubject("Share zip doc")
                                  .setText("Sent with email app.")
                                  .getIntent()
                           .setPackage("com.google.android.gm");
startActivity(shareIntent);
于 2013-06-07T14:38:26.383 回答