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

Android 應用程式的安裝與解除安裝:Intent 實作與權限清單

編輯:關於 Android 程式設計

「下載完 APK 直接跳安裝程式」和「一鍵卸載」這兩個需求,本質上都是發出一個 Intent 交給系統處理。程式碼不長,但權限和 MIME type 這兩個細節最容易出錯。

一、從 SD 卡安裝

String fileName = Environment.getExternalStorageDirectory() + "/myApp.apk";

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + fileName),
        "application/vnd.android.package-archive");
startActivity(intent);

也可以用 Uri.fromFile() 取代字串拼接:

intent.setDataAndType(Uri.fromFile(new File(fileName)),
        "application/vnd.android.package-archive");
startActivity(intent);

二、從網路下載後安裝或升級

Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);

// 依副檔名判斷 MIME type
String type = getMIMEType(f);
intent.setDataAndType(Uri.fromFile(f), type);
startActivity(intent);

輔助的 MIME type 判斷方法:

private String getMIMEType(File f) {
    String type = "";
    String fName = f.getName();
    String end = fName.substring(fName.lastIndexOf(".") + 1,
            fName.length()).toLowerCase();

    if ("m4a".equals(end) || "mp3".equals(end) || "wav".equals(end)) {
        type = "audio";
    } else if ("3gp".equals(end) || "mp4".equals(end) || "rmvb".equals(end)) {
        type = "video";
    } else if ("jpg".equals(end) || "gif".equals(end) || "png".equals(end)
            || "jpeg".equals(end) || "bmp".equals(end)) {
        type = "image";
    } else if ("apk".equals(end)) {
        type = "application/vnd.android.package-archive";
    } else {
        type = "*";
    }
    return type;
}

三、需要的權限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

四、解除安裝

Uri packageURI = Uri.parse("package:com.android.myapp");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);

若想直接跳轉到系統的「應用程式資訊」頁面讓使用者自行選擇,改用 Settings.ACTION_APPLICATION_DETAILS_SETTINGS 會更友善。

五、現代 Android 的兩個重大變更

上面這套寫法在 Android 7.0 之後會失效,務必注意:

  • FileUriExposedException:Android 7.0(API 24)起禁止把 file:// URI 傳給其他 App,必須改用 FileProvider 產生 content:// URI,並在 Intent 加上 FLAG_GRANT_READ_URI_PERMISSION。
  • REQUEST_INSTALL_PACKAGES 權限:Android 8.0(API 26)起,觸發安裝的 App 必須宣告此權限,並引導使用者到「安裝未知應用程式」頁面手動授權。而 INSTALL_PACKAGES 是系統應用專用權限,一般 App 拿不到。

另外,Uri.parse("file://" + path) 這種字串拼接若路徑含空格或中文會出錯,建議一律用 Uri.fromFile() 或 FileProvider.getUriForFile()。

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