Android 7.0之后下載安裝apk注意事項(xiàng)

在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" />

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容