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

Android 如何開啟 RAR 壓縮檔:Intent 呼叫與降級處理

編輯:關於 Android 程式設計

Android 系統本身沒有內建 RAR 解壓縮能力,實務上的做法是把檔案丟給專門的第三方應用處理。這裡以 RAR for Android(com.rarlab.rar)為例。

private void open(String fileString) {
    Intent intent = new Intent();
    intent.setClassName("com.rarlab.rar", "com.rarlab.rar.MainActivity");
    File file = new File(fileString);
    Uri data = Uri.fromFile(file);
    intent.setData(data);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        try {
            Uri uri = Uri.parse("market://search?q=" + "rar");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
        } catch (ActivityNotFoundException e2) {
            Log.i(TAG, "market no found");
        }
    }
}

邏輯拆解

程式碼做了三件事,並以兩層 try-catch 建立降級鏈:

  1. 用 setClassName() 明確指定目標應用的套件名與 Activity 類名,直接呼叫 RAR 應用
  2. 把檔案包成 Uri 塞進 intent 的 data
  3. 若目標應用未安裝(拋出 ActivityNotFoundException),退而求其次跳到應用市場搜尋「rar」,引導使用者安裝
  4. 若連市場 App 都不存在(例如非 Google 服務的裝置),只記一行日誌

三個必須修正的問題

1. Uri.fromFile() 在 Android 7.0 以上會崩潰

這是最關鍵的問題。從 Android 7.0(API 24) 起,把 file:// 形式的 Uri 傳給其他應用會直接拋出 FileUriExposedException,程式當場崩潰。正確做法是改用 FileProvider:

// AndroidManifest.xml 中宣告
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    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 xmlns:android="https://schemas.android.com/apk/res/android">
    <external-path name="downloads" path="Download/" />
</paths>

// 程式碼
File file = new File(fileString);
Uri uri = FileProvider.getUriForFile(
        context, context.getPackageName() + ".fileprovider", file);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

2. market:// 協定並非所有裝置都有

market:// 是 Google Play 的專屬 scheme。在中國大陸的裝置、Amazon Fire 系列、或沒有安裝任何應用市場的裝置上,這個 scheme 沒有對應的處理者,所以第二層 catch 是必要的。更穩健的寫法是改用 https://play.google.com/store/apps/details?id=com.rarlab.rar 這種網址,至少瀏覽器能開啟。

3. 硬編碼套件名與 Activity 類名風險高

寫死 com.rarlab.rar/com.rarlab.rar.MainActivity 意味著:一旦對方 App 改了套件名或 Activity 名稱,你的功能就靜默失效。更健壮的作法是改用隱式 Intent,讓系統挑選能處理該 MIME 類型的應用:

private void openArchive(File file) {
    Uri uri = FileProvider.getUriForFile(
            this, getPackageName() + ".fileprovider", file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, "application/x-rar-compressed");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    } else {
        // 引導使用者安裝解壓縮應用,或直接實作內建解壓
        Toast.makeText(this, "未安裝可開啟 RAR 的應用", Toast.LENGTH_LONG).show();
    }
}

用 resolveActivity() 先確認有沒有可處理的應用,比用 try-catch 捕捉例外更直觀,也能避免部分 ROM 上不拋例外卻無動靜的情況。

另一條路:自己解壓

如果不希望依賴第三方 App,可以引入 junrar 函式庫在應用內直接解壓:

// build.gradle
implementation 'com.github.junrar:junrar:7.5.2'

// 解壓
Archive archive = new Archive(new File(path));
try {
    for (FileHeader fh : archive) {
        if (!fh.isDirectory()) {
            FileOutputStream fos = new FileOutputStream(targetDir + fh.getFileNameString());
            archive.extractFile(fh, fos);
            fos.close();
        }
    }
} finally {
    archive.close();
}

這樣做的好處是不需要使用者安裝額外應用、流程不中斷;缺點是增加 APK 體積,且需注意解壓路徑穿越(zip slip)攻擊——務必檢查每個條目的目標路徑是否仍在預期目錄內。

其他壓縮格式的 MIME 類型參考

zip  → application/zip
rar  → application/x-rar-compressed
7z   → application/x-7z-compressed
tar  → application/x-tar
gz   → application/gzip
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved