android - 调用系统分享功能分享图片

时间:2023-03-08 16:53:59

step1: 编写分享代码, 将Uri的生成方式改为由FileProvider提供的临时授权路径,并且在intent中添加flag

注意:在Android7.0之后,调用系统分享,传入URI的时候可能会导致程序闪退崩溃。这是由于7.0的新的文件权限导致的。下面的代码对其做了处理

public static int sharePic(Context context, String picFilePath) {
File shareFile = new File(picFilePath);
if (!shareFile.exists()) return SHARE_RESULT_FILE_NOT_FOUND;
Intent intent = new Intent(Intent.ACTION_SEND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName()+".flightlog.fileprovider", shareFile);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(shareFile));
}
intent.setType(MIME_TYPE_IMAGE);
Intent chooser = Intent.createChooser(intent, context.getString(R.string.flight_log_dialog_share_title));
if(intent.resolveActivity(context.getPackageManager()) != null){
context.startActivity(chooser);
}
return SHARE_RESULT_NO_ERROR;
}

step2: 在 AndroidManifest.xml 中的 application 标签中添加 provider 的配置

<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yongdaimi.android.fileprovider"//注意和上面FileProvider方法中声明的authorities保持一致
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths_share_img" />
</provider>
</application>

注意: provider 标签中 name 属性和 authorities 声明的值是有可能与第三方库冲突的,可酌情修改。

step3: 在res/xml中新建一个文件 file_paths_share_img.xml

<?xml version="1.0" encoding="utf-8"?>
<resource xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="images"
path="DCIM/IMAGE" />
</resource>

参考链接:

FileProvider使用及相关第三方冲突的完美解决