Android安裝apk文件并適配Android 7.0詳解
首先在AndroidManifest.xml文件,activity同級節點注冊provider:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.file_provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>將apk文件下載到此路徑:
String cachePath = ( getExternalFilesDir("upgrade_apk") + File.separator + getPackageName() + ".apk");在res目錄xml文件夾下創建名為file_paths的文件:upgrade_apk代表上面保存路徑的文件夾名稱,可隨意更改,相同即可。
<?xml version="1.0" encoding="utf-8"?><paths> <external-files-path name="bga_upgrade_apk" path="upgrade_apk" /></paths>
最后編寫代碼,區分不同Android系統版本號,安裝apk(注意:【com.apkinstall.demo】要替換自己應用的包名)
/** * 安裝 apk 文件 * * @param apkFile */ public void installApk(File apkFile) { Intent installApkIntent = new Intent(); installApkIntent.setAction(Intent.ACTION_VIEW); installApkIntent.addCategory(Intent.CATEGORY_DEFAULT); installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { installApkIntent.setDataAndType(FileProvider.getUriForFile(getApplicationContext(), "com.apkinstall.demo.file_provider", apkFile), "application/vnd.android.package-archive"); installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { installApkIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); } if (getPackageManager().queryIntentActivities(installApkIntent, 0).size() > 0) { startActivity(installApkIntent); } }感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答