首頁>技術>

在AndroidManifest.xml新增provider

<provider    android:name="androidx.core.content.FileProvider"    android:authorities="包名.fileProvider"    android:exported="false"    android:grantUriPermissions="true">    <meta-data        android:name="android.support.FILE_PROVIDER_PATHS"        android:resource="@xml/file_paths" /></provider> 

file_paths檔案:

<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">    <external-path name="external_files" path="."/></paths>
安裝APK
File completeApkfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), aApkName);if (!completeApkfile.exists()) {    return;}completeApkfile.renameTo(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), aApkName.replace(".md", ".apk")));File apkfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), aApkName.replace(".md", ".apk"));// 透過Intent安裝APK檔案Intent intent = new Intent(Intent.ACTION_VIEW);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);Uri apkUri;// Android 7.0 以上不支援 file://協議 需要透過 FileProvider 訪問 sd卡 下面的檔案,所以 Uri 需要透過 FileProvider 構造,協議為 content://if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {    // 宣告需要的臨時許可權    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);    // content:// 協議    apkUri = FileProvider.getUriForFile(mContext.getApplicationContext(), "包名.fileProvider", apkfile);} else {    // file:// 協議    apkUri = Uri.fromFile(apkfile);}intent.setDataAndType(apkUri, "application/vnd.android.package-archive");aContext.startActivity(intent);

10
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • Android震動手機程式碼