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

Android 使用 setDataAndType 開啟各種檔案與 Intent 範例

編輯:關於 Android 開發

Android 使用 setDataAndType 開啟各種檔案

Android 可透過 Intent 的 ACTION_VIEW 搭配 setDataAndType 開啟不同檔案。關鍵在於取得檔案 URI,並提供正確的 MIME 類型,讓系統找到能處理該檔案的應用程式。

基本流程

建立 Intent,設定 ACTION_VIEW,取得檔案的 MIME 類型,再呼叫 setDataAndType。若裝置沒有可處理的應用程式,startActivity 可能會拋出 ActivityNotFoundException,因此建議加上例外處理。

private void openFile(File file) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_VIEW);
    String type = getMIMEType(file);
    intent.setDataAndType(Uri.fromFile(file), type);
    startActivity(intent);
}

MIME 類型判斷

可根據副檔名查詢對應的 MIME 類型。常見包含 image、video、audio、application、text 等。若無法判斷,可退回使用通用類型,讓系統嘗試開啟。

常見對應:jpg 為 image/jpeg,png 為 image/png,mp4 為 video/mp4,mp3 為 audio/mpeg,pdf 為 application/pdf,doc 為 application/msword,xls 為 application/vnd.ms-excel,ppt 為 application/vnd.ms-powerpoint,txt 為 text/plain,zip 為 application/zip。

常見 Intent 範例

  • 開啟圖片:使用 image/* 或 image/jpeg、image/png 等。
  • 開啟 PDF:使用 application/pdf。
  • 開啟文字檔:使用 text/plain。
  • 播放音訊:使用 audio/* 或 audio/mp3。
  • 播放影片:使用 video/* 或 video/mp4。
  • 開啟 Word、Excel、PowerPoint:使用對應 Office MIME 類型。

其他常用 Intent

除了開啟檔案,也可使用 Intent 開啟網頁、地圖、電話、簡訊、電子郵件、Market 搜尋或分享文字。不同 Action 與 URI 組合可對應不同系統功能。

注意事項

使用 setDataAndType 時,URI 與 MIME 類型必須一致。若 URI 是 content URI,需確認內容提供者可讀;若是檔案 URI,需注意 Android 版本對 FileUriExposedException 的限制,必要時改用 FileProvider。

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