最近忙于后台开发,但是之前做的android,客户提出Bug,说软件打开后的提示更新,更新之后依旧提示。后来我才知道,原来是更新是更新了,但是并没有安装最新版。原来以前的传统的跳转安装页面,在新版本的android系统的手机,是无法调起安装页面的。
于是找了个Android7.0的手机运行,控制台报错FileUriExposedException异常
查了下资料,原来狗哥又把安全性能提高了,私有文件访问被限制,当targetSdkVersion > = 24,推荐使用FileProvider来访问特定的文件或文件夹,把 file:// URI 替换为 content:// URI
1.在Androidmanifest.xml文件中声明FileProvider
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xxx.xxx.fileprovider" //自定义名字 可用:包名.fileprovider
android:exported="false"
android:grantUriPermissions="true">
...
</provider>
...
</application>
</manifest>
2.指定访问的文件的路径
在res下,创建xml文件夹,创建file_paths.xml文件
file_paths.xml内容为:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<root-path name="root_path" path="." />
<files-path name="xxxx" path="download/" />
<external-path name="xxxx" path="download/" />
<external-files-path name="xxxx" path="download/" />
</paths>
3.引用指定的路径
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xxx.xxx.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths />
</provider>
4.编写调起安装页面代码
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 7.0+以上版本
Uri apkUri = FileProvider.getUriForFile(mContext, "com.xxxx.fileProvider", file); //与manifest中定义的provider中的authorities="com.xxxx.fileprovider"保持一致
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
mContext.startActivity(intent);
这样就完成了,OK。
本人个人原创,如有雷同,纯属巧合,或者与本人联系,做改动。请转载或者CV组合标明出处,谢谢!(如有疑问或错误欢迎指出,本人QQ:752231513)