Android7.0以后跨应用

263 阅读1分钟

FileUriExposedException概述

Android N 上 安装Apk时报错:android.os.FileUriExposedException: file:///storage/emulated/0/Download/appName.apk exposed beyond app through Intent.getData();

示例代码

  public static void installApk(Context context, File file) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.customToastView("安装失败");
        }
    }

原因

官网解释:app内可以使用file://这种形式,7.0以后跨应用只能使用content://这种形式,并且要声明权限,安全问题。

解决方案

  1. 在AndroidManifest.xml中application节点里面添加如下代码
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

说明:

  • authorities:app的包名.fileProvider (fileProvider可以随便写),上面采用的是gradle的替换直接写成包名也可以,但是推荐这种方式,多渠道分包的时候不用关心了
  • grantUriPermissions:必须是true,表示授予 URI 临时访问权限
  • exported:必须是false
  • resource:中的@xml/file_paths是我们接下来要添加的文件
  1. 在res目录下新建一个xml文件夹,并且新建一个provider_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>

说明:

  • name:可以随意写,只是一个名字
  • path:表示文件路径,.表示所有
  1. 安装代码调用
public static void installApk(Context context, File file) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri FileURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider",file);
                intent.setDataAndType(FileURI,
                        "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);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.customToastView("安装失败");
        }
    }

说明:低于7.0的版本还使用老的方式,而高于的要用新的获取uri的方式。