app安装报错FileUriExposedException

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/lylodyf/article/details/79882503

原因

从Android 7.0开始,不再允许在app中把file:// Uri暴露给其他app,否则应用会抛出FileUriExposedException。原因在于,Google认为使用file:// Uri存在一定的风险。比如,文件是私有的,其他app无法访问该文件,或者其他app没有申请READ_EXTERNAL_STORAGE运行时权限。解决方案是,使用FileProvider生成content:// Uri来替代file:// Uri。

解决方案

  1. 在manifests.xml清单文件中添加:
<application>
...
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.xxxxx.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_path"/>
</provider>
</application>

authorities属性可自定义,exported必须设置成 false,grantUriPermissions用来控制共享文件的访问权限。

  1. 编写file_path.xml文件,放在res/xml目录下
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--<external-path name="name" path="tienal" />-->
    <external-path
        name="tienal_external_path"
        path="." />
</paths>

path中的可配置选项

<files-path name="name" path="path" /> //相当 Context.getFilesDir() + path, name是分享url的一部分

<cache-path name="name" path="path" /> //getCacheDir()

<external-path name="name" path="path" /> //Environment.getExternalStorageDirectory()

<external-files-path name="name" path="path" />//getExternalFilesDir(String) Context.getExternalFilesDir(null)

<external-cache-path name="name" path="path" /> //Context.getExternalCacheDir()    
  1. 使用
private void installApk(String filename) {
//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(Intent.ACTION_VIEW);
//        String type = "application/vnd.android.package-archive";
//        intent.setDataAndType(Uri.fromFile(file), type);
//        startActivity(intent);

        File file = new File(filename);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "com.tienal.FileProvider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(mActivity, "com.tienal.FileProvider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);
    }

猜你喜欢

转载自blog.csdn.net/lylodyf/article/details/79882503