在android 7.0之前版本更新其實(shí)相當(dāng)簡(jiǎn)單,只需要使用系統(tǒng)下載器就能夠完成下載之后安裝,但是在7.0之后android升級(jí)安全機(jī)制,下載安裝受到一些限制,以至于安裝無(wú)反應(yīng)或無(wú)法正常安裝。
1、清單文件AndroidManifest.xml?application中添加
<provider
? ? android:name="android.support.v4.content.FileProvider"
? ? android:authorities="${applicationId}.fileprovider"
? ? android:exported="false"
? ? android:grantUriPermissions="true">
? ? ? ? android:name="android.support.FILE_PROVIDER_PATHS"
? ? ? ? android:resource="@xml/provider_paths" />
</provider>
2、資源目錄res新建xml文件夾,新建provider_paths.xml
文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
? ? ? ? name="external"
? ? ? ? path="." />
</paths>
3、安裝方法如下:
private void installApk() {
File apkfile =new File(saveFileName);
? ? if (!apkfile.exists()) {
return;
? ? }
//Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
? ? Intent intent =new Intent(Intent.ACTION_VIEW);
? ? if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
? ? ? ? //intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
? ? ? ? intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
? ? }else {
// 聲明需要的臨時(shí)的權(quán)限
? ? ? ? intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
? ? ? ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
? ? ? ? // 第二個(gè)參數(shù),即第一步中配置的authorities
// 注意這里, 因?yàn)檫@里容易導(dǎo)錯(cuò)包,如果你是多module開(kāi)發(fā),一定要使用主Module(即:app)的那個(gè)BuildConfig
// 這里說(shuō)明一下,我上面的清單文件是主Module的,所以這里也要導(dǎo)包導(dǎo)入主module的,我覺(jué)得寫(xiě)到被依賴(lài)module也是可以的,但要保持一致,這個(gè)我沒(méi)試過(guò))
? ? ? ? Uri contentUri = FileProvider.getUriForFile(context, xx.xxx.BuildConfig.APPLICATION_ID +".fileprovider", apkfile);
? ? ? ? intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
? ? }
startActivity(intent);
}
注:Android8.0、9.0添加請(qǐng)求未知來(lái)源應(yīng)用安裝權(quán)限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />