Android7.0 android.os.FileUriExposedException错误小记

导致该问题的只要原因是当buildsdk >=24时,调用Uri.fromFile时会报错,按照如下步骤即可解决:

1、在AndroidManifest.xml中添加如下代码

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

注意替换当前应用的包名

2、在res目录下新建一个xml文件夹,并新建一个file_paths的xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="files_root"
        path="Android/data/包名/" />
    <external-path
        name="external_storage_root"
        path="." />
</paths>

同样注意替换当前应用的包名

3、修改隐式启动Intent的代码

public static void installApp(Context context, File file) {
        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, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

这里以安装apk的操作为例,需要针对Build.VERSION.SDK_INT >= 24 和小于24分别处理,用不同的方式获得Uri。

到这里问题就解决了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容