Android7.0使用FileProvider安装apk

来源:互联网 发布:淘宝链接转微信二维码 编辑:程序博客网 时间:2024/06/01 08:19

Android7.0安装文件的话默认会抛出FileUriExposedException 解决方法:

1.在AndroidManifest.xml中activity同节点下定义一个fileProvider

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

2.在res目录下,增加xml文件夹,并新建一个名为 file_paths.xml 的文件

<paths><external-path path="包名/" name="files_root" /></paths>

这里写图片描述

这里写图片描述
3.安装时调用此方法

    //安装文件(适配Android7.0)    public static void installApk(Context context,String filePath) {        Intent intent = new Intent(Intent.ACTION_VIEW);        //判断是否是AndroidN以及更高的版本        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", new File(filePath));            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");        } else {            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        }        context.startActivity(intent);    }

遇到的坑

Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

解决方法:

    检查AndroidManifest.xml中    android:authorities="包名.fileProvider"    是否与安装的方法中    FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(filePath));    检查是否相同,注意大小写
阅读全文
0 0
原创粉丝点击