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使用及相關第三方沖突的完美解決