我试图允许用户将图像共享到设备上的其他应用程序.该图像位于我的应用程序内部存储区域的files /子目录中.它适用于Gmail,但Facebook和Twitter在响应我的意图时都崩溃了.
编辑:Google+也可以.
以下是相关的代码部分.
在Application.xml中
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="org.iforce2d.myapp.MyActivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
Run Code Online (Sandbox Code Playgroud)
XML/filepaths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="shared" path="shared"/>
</paths>
Run Code Online (Sandbox Code Playgroud)
以下是我的活动中的共享代码:
File imagePath = new File(getContext().getFilesDir(), "shared");
File newFile = new File(imagePath, "snapshot.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(),
"org.iforce2d.myapp.MyActivity", newFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> resInfos =
getPackageManager().queryIntentActivities(shareIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : resInfos) {
getContext().grantUriPermission(info.activityInfo.packageName,
contentUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(Intent.createChooser(shareIntent, "Share image..."));
Run Code Online (Sandbox Code Playgroud)
contentUri记录时的值是:
content://org.iforce2d.myapp.MyActivity/shared/snapshot.jpg
我只使用Gmail,Facebook和Twitter作为接收应用程序进行了检查,但结果在各种操作系统版本(从2.2.1到4.4.3)中都非常一致,7个设备包含Kindle.
Gmail效果很好.图像缩略图显示在邮件撰写中,并在发送时成功附加到邮件.
Twitter和Facebook都崩溃了,如下所示.
以下是来自logcat的堆栈跟踪,显示了这两个应用程序所遇到的问题,对于它们来说似乎是同样的问题(这取自4.4.3,但错误实际上一直回到2.2. 1尽管错误消息的措辞略有不同):
Caused by:
java.lang.IllegalStateException: …Run Code Online (Sandbox Code Playgroud)