如果 targetSdkVersion 高于 24,则使用 FileProvider 授予访问权限。
在res\xml中创建一个名为provider_paths.xml的xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
然后你需要在你的应用标签内的AndroidManifest.xml中添加一个Provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
现在像这样获取你的照片路径:
final File photoFile = new File(Environment.getExternalStorageDirectory().toString(), "/path/filename.png");
现在像这样获取照片 URI:
Uri photoURI = FileProvider.getUriForFile(SavedCardActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
要分享,请使用以下代码:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share image using"));
} else {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}