7.0以后,谷歌开始收紧Android应用权限
对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在您的应用外部公开 file:// URI。如果一项包含文件 URI 的 intent 离开您的应用,则应用出现故障,并出现 FileUriExposedException 异常。
要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。如需了解有关权限和共享文件的详细信息,请参阅共享文件。
https://developer.android.com/about/versions/nougat/android-7.0-changes.html#accessibility
代码:
public static void shareContent(Context context, String filename) {
Uri uri = null;
if (Build.VERSION.SDK_INT <= 22) {
//6.0及以下
uri = Uri.fromFile(new File(filename));
} else {
//7.0及以上
uri = FileProvider.getUriForFile(context, "com.painttool.file_provider", new File(filename));
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
//在新任务窗体中进行分享
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
其他配置:
AndroidManifest.xml
<provider
android:authorities="com.painttool.file_provider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
在xml文件夹下新建filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<path>
<external-path path="." name="external_storage_root" />
</path>
在res目录下创建xml/file_paths文件,只有在file_paths中配置的目录下的文件才可以在应用间共享
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external-path" path="apk/" />
<cache-path name="cache-path" path="." />
<files-path name="files-path" path="." />
</paths>
external-path 对应Environment.getExternalStorageDirectory()
cache-path对应 getCacheDir()
files-path对应 getFilesDir()
path指定对应目录下的子目录, path="." 表示该目录下所有子目录
“`