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

Android 調起系統郵件客戶端並帶多個附件

編輯:關於 Android 程式設計

專案裡需要發郵件,於是打算直接調起系統自帶的郵件客戶端,並且一次帶上多個附件。問題來了:該用哪個 Action?Intent.ACTION_SEND、Intent.ACTION_SENDTO,還是 Intent.ACTION_SEND_MULTIPLE?

答案是 ACTION_SEND_MULTIPLE。顧名思義,它就是為「一次分享多項內容」準備的,附件列表透過 Intent.EXTRA_STREAM 以 ArrayList<Uri> 的形式傳入。

參考做法

翻一遍 Android 郵件應用的源碼,在收尾處可以看到類似這樣的寫法:

String subject = ...
String text = ...
ArrayList<Uri> attachments = ...

Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
intent.setClassName("com.android.email", "com.android.email.activity.MessageCompose");
try {
    startActivity(intent);
} catch (ActivityNotFoundException anfe) {
    anfe.printStackTrace();
}

版本差異要注意

上面這段在 Android 4.0 到 4.3 上都能正常工作。但到了 Android 4.4(KitKat),郵件應用的 Activity 名稱已經改為 com.android.email.activity.ComposeActivityEmail,寫死類名的方式就會失效。

更穩健的思路有兩種:一是只發 ACTION_SEND_MULTIPLE 而不指定具體組件,交給系統彈出選擇器;二是同時把已知的多個候選類名都試一遍,捕獲 ActivityNotFoundException 後再退化處理。前者相容性更好,也更符合現代 Android 的分享習慣。

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