來源:https://blog.51cto.com/u_16213385/12575668
整個安裝過程一般可以分為以下幾個步驟:獲取 APK 文件的路徑、請求權限、調用安裝 Intent、完成安裝
在 Android 7.0(API Level 24)及以上版本中,安裝應用包需要用戶人工干預并且設備需要開啟未知來源的安裝選項。在開始安裝之前,確保你具有存儲和安裝應用的權限。
在你的 AndroidManifest.xml 文件中添加如下權限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
安裝代碼,apkPath:/data/data/com.study.apptest/download/upgrade/apptest.1.0.1.apk
整個安裝過程一般可以分為以下幾個步驟:獲取 APK 文件的路徑、請求權限、調用安裝 Intent、完成安裝
在 Android 7.0(API Level 24)及以上版本中,安裝應用包需要用戶人工干預并且設備需要開啟未知來源的安裝選項。在開始安裝之前,確保你具有存儲和安裝應用的權限。
在你的 AndroidManifest.xml 文件中添加如下權限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
安裝代碼,apkPath:/data/data/com.study.apptest/download/upgrade/apptest.1.0.1.apk
private void installApk(String apkPath) { File apkFile = new File(apkPath); if (!apkFile.exists()) { Toast.makeText(this, "APK文件不存在", Toast.LENGTH_SHORT).show(); return; } Uri apkUri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", apkFile); Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); intent.setData(apkUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else { apkUri = Uri.fromFile(apkFile); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
使用 FileProvider,為了在 Android 7.0 及以上版本中安全地共享文件,你需要在 AndroidManifest.xml 中聲明 FileProvider,如下:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" 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 文件以配置路徑,比如:
<paths>
<external-path name="external_files" path="." />
</paths>
浙公網安備 33010602011771號