Android7.0及以上android.os.FileUriExposedException

Home / Android @百晓生 2017-11-16 4059

Android版本迭代非常快,我们这些monkey也要与时俱进,不断的学习Android新版本的特性。最近发现以往上架的APP不能自动更新,下载完了就出现安装失败(异常被捕获)。后来查了下原因,原来是Android7.0以上系统安全机制出现了变化导致路径和权限需要申请。首先在AndroidManifest.xml中添加以下代码,告诉系统我们这个APP是需要这个服务及相关权限

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            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 xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

最后安装代码稍微改装一下,如下

    public void update(File apkfile, Context c) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(c, String.format("%s.provider", c.getApplicationContext().getPackageName()), apkfile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, c.getContentResolver().getType(apkUri));
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), getMIMEType(apkfile));
        }
        c.startActivity(intent);
    }
    public String getMIMEType(File f) {
        String name = f.getName();
        String ext = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
        ext = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
        return ext;
    }

搞定收工!

本文链接:https://www.it72.com/12284.htm

推荐阅读
最新回复 (0)
返回