Android高版本安装Apk报错

Android N 安装Apk报错  

android.os.FileUriExposedException: file:///storage/emulated/0/download/1558506119385taiheApp.apk exposed beyond app through Intent.getData()

3d09d67be9a25a2265e38298a0219fa051d.jpg

因为 Android7.0加上了“私有目录被限制访问”

“私有目录被限制访问“ 是指在Android7.0中为了提高私有文件的安全性,面向 Android N 或更高版本的应用私有目录将被限制访问。这点类似iOS的沙盒机制。

解决报错的方法: 

在AndroidManifest.xml清单文件中注册provider


<application
   ...>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.wlhl.dxcount"
        android:grantUriPermissions="true"
        android:exported="false">
        <!--元数据-->
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>
  • exported:要求必须为false,为true则会报安全异常。
  • grantUriPermissions:true,表示授予 URI 临时访问权 
    限。

在res目录下新建一个xml文件夹,然后新建一个provider_paths的xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/com.wlhl.dxcount/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

然后再更新App的地方改写代码

  public static void install(Context context) {
        File file = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                , "dx.apk");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
                       File file= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"dx.apk");
                    //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                    Uri apkUri =
                            FileProvider.getUriForFile(context, "com.wlhl.dxcount", file);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }else{
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"+enqueue+"dx.apk")),
                            "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==
发布了181 篇原创文章 · 获赞 68 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/wx_lanyu/article/details/90446110