/Android6.0 以前升级apk用以下代码
private void installApk() {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
context.startActivity(intent);
}
但是到了Android7.0 时,会报错这个错误:
android.os.FileUriExposedException: file:///storage/emulated/0/Ccq/8974b50c6e7dbf9daf04472c1aa01a93.apk exposed beyond app through Intent.getData()
下面,进行修复:
1. 在AndroidManifest.xml 的 application 里面添加以下代码
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="yun.com.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
...
</application>
其中:exported必须为false,grantUriPermissions必须为true,authorities为”自己的包名.fileProvider”。
2. 在res目录下新建一个xml文件夹,再在xml文件夹里创建file_path.xml文件,添加以下代码
<?xml version="1.0" encoding="utf-8"?>
<paths>
<paths>
<files-path path="Android/data/yun.com/" name="files_root" />
<files-path path="." name="files_path" />
<root-path path="." name="root"/>
<external-path path="." name="files"/>
</paths>
</paths>
这是apk默认保存路径String filePath = Environment.getExternalStorageDirectory();
的时候使用的,若路径有修改,比如
String filePath = Environment.getExternalStorageDirectory() + "/Ccq";
那么,files-path也要做相应修改<files-path path="Android/data/yun.com/Ccq/" name="files_root" />
3. 最后一步,就是修改代码
private void installApk() {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, "yun.com.fileProvider", f);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
此时,应用是能正常升级版本的,但是,也有可能会发现,下载apk的进度条可能一直未0,也就是无法下载apk,这时可以去设置–权限设置里面把内部存储的权限打开,也可在代码中动态申请权限。还有一个方法,在APP的build.gradle文件中将 targetSdkVersion的版本降低。
技术浅陋,欢迎各位大神指正、补充。