安卓7.0开始,不再允许在App中把 file://Uri 暴露给其他App,因此在代码中需要做下版本判断,在7.0版本及以上需要使用 FileProvider 生成 content://Uri 来代替 file://Uri。同时安卓工程需要做以下调整:
1、在 AndroidManifest.xml 的 application 标签页下增加 provider 声明
<application......<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="com.smartphone.wifikey.fileProvider"android:grantUriPermissions="true"android:exported="false"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/filepath" /></provider></application>
以上内容需注意 android:authorites 必须填写为实际访问的 App 包名称。
2、在 res 目录下创建 xml 文件夹,新建 filepath.xml 并填写以下内容
<?xml version="1.0" encoding="utf-8"?>
<paths><external-path name="external_files" path="."/>
</paths>
3、代码中增加对7.0版本的判断与处理
private void installApk(File apkFile) {Intent intent = new Intent(Intent.ACTION_VIEW);//判断是否是Android N以及更高的版本if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);Uri contentUri = FileProvider.getUriForFile(mContext, "com.smartphone.wifikey" + ".fileProvider", apkFile);intent.setDataAndType(contentUri, "application/vnd.android.package-archive");} else {intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);}startActivity(intent);}
以上代码必须注意,getUriForFile 方法的第二个参数必须为”实际访问的App包名.fileProvider”。另外在测试时,如果出现其他异常,留心检查下应用权限。
有问题给我邮件或者评论哦,觉得对你有帮助就点赞吧~:-)