萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 程式碼安裝與解除安裝 APK:Intent.ACTION_VIEW / ACTION_DELETE 完整範例

核心原理

Android 系統內建安裝/解除安裝 Activity,我們只需發送對應 Intent 即可喚起系統安裝器或解除安裝確認頁。

安裝 APK

public void install(View v) {
    File apk = new File(Environment.getExternalStorageDirectory(), "HtmlUI1.apk");
    if (!apk.exists()) { Toast.makeText(this, "檔案不存在", Toast.LENGTH_SHORT).show(); return; }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // Android 7.0+ 必須使用 FileProvider
        uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", apk);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    } else {
        uri = Uri.fromFile(apk);
    }
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent);
}

注意:Android 7.0 (API 24) 以上嚴禁 file:// Uri,需配置 FileProvider,詳見官方文件。

解除安裝 APK

public void uninstall(View v) {
    Intent intent = new Intent(Intent.ACTION_DELETE);
    intent.setData(Uri.parse("package:com.njupt.htmlui1")); // 目標套件名
    startActivity(intent);
}

版面 (main.xml)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button android:text="安裝" android:onClick="install"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <Button android:text="解除安裝" android:onClick="uninstall"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

Manifest 權限

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <!-- Android 8.0+ -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

總結

兩行 Intent 即可完成安裝/解除安裝,關鍵在於 Android 7.0+ 的 FileProvider 適配與安裝未知來源權限申請。

copyright © 萬盛學電腦網 all rights reserved