Android7.0须知--应用间共享文件(FileProvider) log: exposed beyond app through Intent.getData()

来源:互联网 发布:网络购物用户行为报告 编辑:程序博客网 时间:2024/06/14 04:39

  • 对于面向 Android N 的应用,Android 框架执行的 StrictMode,API 禁止向您的应用外公开 file://URI。

    如果一项包含文件 URI 的 Intent 离开您的应用,应用失败,并出现 FileUriExposedException异常。

  • 若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。
    进行此授权的最简单方式是使用 FileProvider类。 如需有关权限和共享文件的更多信息,

解决

AndroidManifest.xml中添加一个provider

<provider            android:name="android.support.v4.content.FileProvider"            android:authorities="APP包名.fileprovider"            android:grantUriPermissions="true"            android:exported="false"            >            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/file_paths" /><?/provider>

添加一个XML文件 名为 file_paths.xml

<xml version="1.0" encoding="utf-8"?><paths>    <external-path path="你需要访问的路径" name="files_root" />    <external-path path="." name="external_storage_root" /></paths>

然后调用安装的时候 判断下sdk版本 做区分对待

 Intent intent = 
Intent intent = new Intent(Intent.ACTION_VIEW);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            Uri contentUri = FileProvider.getUriForFile(context, "com.coderstory.Purify.fileprovider", new File(filePath));            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");        } else {            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        }        startActivity(intent);
new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(context, "com.coderstory.Purify.fileprovider", new File(filePath)); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } startActivity(intent);

阅读全文
0 0