1. 程式人生 > >Android8.0+應用內更新安裝apk失敗

Android8.0+應用內更新安裝apk失敗

描述
應用內更新,下載apk呼叫系統api進行安裝,在android8.0+手機上無法安裝,在android8.0以下可以安裝成功,看了看google for android 官網得知android8.0許可權控制的更嚴格,安裝應用需要應用本身具有“安裝未知來源”許可權。

解決方案:

一,如果構建 compileSdkVersion<27
先判斷應用是否具有“安裝未知應用”許可權,沒有則引導開啟,有則調起安裝View
其次安裝是需要判斷大於ADK.API>=24,條件成立則apk檔案uri需要從FileProvider中獲取,否則安裝最簡單方式調起安裝。

       <provider
android:name="android.support.v4.content.FileProvider" android:authorities="com.xxx.fileprovider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>

xml目錄下新建file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">;;
    <external-path name="pic" path="zzTong/"  />
</paths>

調起安裝

@TargetApi(Build.VERSION
_CODES.O) private void openFile(File file) { HPLog.i(HPLog.LFP_TAG,"openFile:"+file.getAbsolutePath()); apkFile=file; //判讀版本是否在8.0以上 if (Build.VERSION.SDK_INT >= 26) { //來判斷應用是否有許可權安裝apk boolean installAllowed= getPackageManager().canRequestPackageInstalls(); HPLog.e(HPLog.LFP_TAG,"installAllowed="+installAllowed); if(installAllowed){ install(apkFile); }else { AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_INSTALL_APK). permission(Manifest.permission.REQUEST_INSTALL_PACKAGES). rationale(new RationaleListener() { @Override public void showRequestPermissionRationale(int requestCode, Rationale rationale) { AndPermission.rationaleDialog(DownloadApkActivity.this, rationale).show(); } }).send(); } } else { install(apkFile); } } private void install(File file){ Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= 24) { //provider authorities Uri apkUri = FileProvider.getUriForFile(this, "com.handpay.fileprovider", file); //Granting Temporary Permissions to a URI intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); }else { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); } startActivity(intent); }

二,compileSdkVersion>=27
如果構建SDK版本在27版本及以上則不需要判斷是否有“安裝未知應用”許可權,直接調起安裝應用即可,系統會自動提示。

這裡寫圖片描述

private void install(File file){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }