android 8.0 的未知來源apk安裝
阿新 • • 發佈:2019-01-24
android每次版本的升級都開始原來越來越重視使用者的安全,需要更多的許可權。我們的專案現在將sdk更新到27後,出現了大量的問題,今天為大家處理一下安裝apk。
android從7.0(24)開始就已經對安裝進行了修改,增加了xml檔案的路徑處理。
8.0安裝apk的流程如下:
註冊檔案新增許可權 - 新增xml - 申請許可權(27) - 安裝處理(24) - 修改compileSdkVersion大於26
第一步:註冊檔案新增許可權和privde
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<application android:name=".app.MainApplicaton"> <provider android:name="android.support.v4.content.FileProvider" android:authorities="包名" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
第二步:res檔案中新增xml包,新增file_paths.xml檔案,內容如下:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="apk_path" path="." /> </paths>
第三步:判斷sdk是否是8.0以上,新增未知來源安裝apk的判斷
private voidinstallApkPermission(@NonNull String apkPath) { if(TextUtils.isEmpty(apkPath)){ return; } mApkPath = apkPath; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls(); //沒有未知來源的安裝許可權需要引導使用者進入到設定頁面 if(!haveInstallPermission){ Toast.makeText(UpgradeActivity.this,"安裝應用需要開啟未知來源許可權,請去設定中開啟許可權",Toast.LENGTH_LONG).show(); Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES); startActivityForResult(intent, INSTALLPERMISSIO_REQUESTCODE); }else { installApk(apkPath); } }else { installApk(apkPath); } }
第四步:安裝,根據sdk是否大於24進行處理
private void installApk(@Nullable String apkPath) { if(TextUtils.isEmpty(apkPath)){ return; } File file = new File(apkPath); Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } else { //Android7.0之後獲取uri要用contentProvider Uri apkUri = FileProvider.getUriForFile(this, "包名", file); //Granting Temporary Permissions to a URI intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getBaseContext().startActivity(intent); }第五步:修改compileSdkVersion 大於等於26 ,如果小於26就會導致獲取未知安裝許可權(canRequestPackageInstalls)的時候永遠返回false。