1.權限
在Android8.0版本及其以上需要有安裝權限才能夠進行安裝,否則,包下載完成之后,不會彈出安裝界面。具體權限如下:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
2.吊起安裝界面代碼塊
private void reSetupApk() {
Intent intentUpdate = new Intent("android.intent.action.VIEW");
intentUpdate.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file = new File(Constant.SDCARD_DOWNLOAD_PATH + "/" + fileName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //對Android N及以上的版本做判斷
Uri apkUriN = FileProvider.getUriForFile(mContext,
mContext.getApplicationContext().getPackageName() + ".provider", file);
intentUpdate.addCategory("android.intent.category.DEFAULT");
intentUpdate.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加Flag 表示我們需要什么權限
intentUpdate.setDataAndType(apkUriN, "application/vnd.android.package-archive");
} else {
Uri apkUri = Uri.fromFile(file);
intentUpdate.setDataAndType(apkUri, "application/vnd.android.package-archive");
}
mContext.startActivity(intentUpdate);
}
3.配置文件提供者信息
<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>
4.配置文件路徑過濾器
在res下新建xml文件夾,然后創建provider_paths文件,內容如下:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
path屬性可定位到具體的文件夾,限制達到安全的考慮,android:pathPrefix、android:path或android:pathPatten進行最小化訪問路徑申明和最小權限申明。可防止客戶端本地數據允許被第三方應用讀取、利用,易造成敏感數據泄露。
原文鏈接:https://blog.csdn.net/u012977315/article/details/104850870