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

Android 依 mimeType 對應開啟不同 Activity

編輯:關於 Android 程式設計

當 App 需要「打開某個檔案」,卻不想自己處理所有格式時,最自然的做法就是把檔案交給系統,讓系統依 MIME 類型挑選合適的 Activity。

步驟一:在 AndroidManifest 宣告意圖篩選器

若想攔下所有類型的檔案:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:mimetype="*/*" />
</intent-filter>

實務上更建議把 mimetype 寫得更具體,例如只處理 video/*、audio/*、application/pdf,否則使用者在檔案管理器中點任何檔案都會冒出你的 App,體驗很差。

步驟二:在 Activity 中依 mimeType 分流

String mimeType = intent.getType();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
    if (mimeType != null
            && (mimeType.matches("video/(.+)") || mimeType.matches("audio/(.+)"))) {
        startActivity1();   // 交給自建的播放器
    } else {
        startActivity2();   // 其他類型走通用處理
    }
}

更清楚的寫法是用 startsWith() 取代正規表示式:

if (mimeType != null && mimeType.startsWith("video/")) { ... }

幾個實務細節

  • URI 的取得:除了 getType(),通常還需要 getData() 或 getScheme() 來判斷來源是 file:// 還是 content://。
  • content:// 的權限:Android 4.4 之後跨應用讀取 content URI 需搭配 FLAG_GRANT_READ_URI_PERMISSION,否則會拿到 SecurityException。
  • FileProvider:Android 7.0 起禁止暴露 file:// URI,對外分享檔案請改用 FileProvider.getUriForFile()。
  • 反向送出:如果你自己的 App 想把檔案丟給別人開,就用 Intent.setType() 搭配 Intent.createChooser(),讓使用者自己挑。

核心概念其實一句話:mimeType 是系統派工的分類依據,宣告得精準,路由就乾淨。

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