Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 用程式碼安裝與解除安裝 APK 的實作範例

編輯:關於 Android 程式設計

應用市場之外,很多情境需要 App 自己去安裝或移除另一支程式,例如企業內部下發工具、遊戲啟動器下載擴充包等等。Android 其實把這件事設計得很直覺:安裝靠 ACTION_VIEW 搭配特定的 MIME 型別,解除安裝則用 ACTION_DELETE。以下是一份可直接參考的最小範例。

public class TestInstallAPK extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // this.unInstallFile();
        installFile();
    }

    /**
     * 安裝 APK
     */
    private void installFile() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        // String type = getMIMEType(f);
        // intent.setDataAndType(Uri.fromFile(f), type);
        intent.setDataAndType(
                Uri.parse("file://" + "/sdcard/Android_gc.apk"),
                "application/vnd.android.package-archive");
        this.startActivity(intent);
    }

    /**
     * 解除安裝 APK
     */
    private void unInstallFile() {
        Uri uri = Uri.parse("package:com.gameclient");
        Intent intent = new Intent(Intent.ACTION_DELETE, uri);
        this.startActivity(intent);
    }
}

程式碼重點說明

安裝:關鍵是 MIME 型別 application/vnd.android.package-archive。系統收到這個 Intent 後,會自動開啟安裝確認畫面,由使用者手動按下安裝。注意這裡只是「交給系統處理」,App 本身並沒有靜默安裝的能力,使用者一定會看到並需要確認的對話框。

解除安裝:URI 的格式是 package: 加上目標應用的套件名稱(package name),例如 package:com.gameclient。同樣地,系統會跳出確認視窗,不會默默把別人的 App 移除掉。

實務上要注意的眉角

首先是權限。若要安裝 APK,需要在 AndroidManifest.xml 中宣告 android.permission.REQUEST_INSTALL_PACKAGES;而從 Android 8.0(API 26)開始,除了這個權限,還必須引導使用者到「安裝未知應用」清單中,為你的 App 開啟允許,否則會收到 SecurityException。

其次是 URI 形式。Android 7.0 之後禁止直接把 file:// URI 暴露給其他應用,必須改用 FileProvider 產生 content:// 形式的 URI,並在 Intent 上加 FLAG_GRANT_READ_URI_PERMISSION,同時在 res/xml/file_paths.xml 中宣告可分享的目錄。範例中的寫法屬於舊版風格,理解原理後記得替換成新寫法。

最後,解除安裝他人應用的行為在部分應用市場審核規範中屬於敏感操作,上架前建議先確認政策,避免因此被拒。整體來說,這兩個 Intent 的用法本身非常簡單,真正需要花心思的反而是伴隨而來的權限與版本相容性處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved