Android調用系統郵件類應用的正確實現方法

來源:互聯網
上載者:User

標籤:

Android應用開發中,很多情況下免不了要調用手機上的郵件類應用,實現郵件發送的功能,這一般是通過調用系統已有的Intent來實現的。看到網上很多郵件發送都是調用action為android.content.Intent.ACTION_SEND的Intent來實現的,下面我們就來看下這種方式實現的效果如何。

 

【使用Intent.ACTION_SEND方式】

具體的UI搭建我就不說了,很easy,直接看下發送的核心代碼就行:

  1. String[] email = {"3802**[email protected]"}; // 需要注意,email必須以數組形式傳入  
  2. Intent intent = new Intent(Intent.ACTION_SEND);  
  3. intent.setType("message/rfc822"); // 設定郵件格式  
  4. intent.putExtra(Intent.EXTRA_EMAIL, email); // 接收人  
  5. intent.putExtra(Intent.EXTRA_CC, email); // 抄送人  
  6. intent.putExtra(Intent.EXTRA_SUBJECT, "這是郵件的主題部分"); // 主題  
  7. intent.putExtra(Intent.EXTRA_TEXT, "這是郵件的本文部分"); // 本文  
  8. startActivity(Intent.createChooser(intent, "請選擇郵件類應用"));  

上面代碼的效果如所示,將會拉起不止郵件類應用,這是很坑爹的事情,使用者體驗相當差。

從上面結果可以看出,ACTION_SEND不是首選的方案,更好的方案是能夠過濾非郵件類應用,只識別郵件類應用。這可以通過使用另外一個action來實現的。

 

【使用Intent.ACTION_SENDTO方式】

核心代碼如下:

  1. // 必須明確使用mailto首碼來修飾郵件地址,如果使用  
  2. // intent.putExtra(Intent.EXTRA_EMAIL, email),結果將匹配不到任何應用  
  3. Uri uri = Uri.parse("mailto:3802**[email protected]");   
  4. String[] email = {"3802**[email protected]"};  
  5. Intent intent = new Intent(Intent.ACTION_SENDTO, uri);  
  6. intent.putExtra(Intent.EXTRA_CC, email); // 抄送人  
  7. intent.putExtra(Intent.EXTRA_SUBJECT, "這是郵件的主題部分"); // 主題  
  8. intent.putExtra(Intent.EXTRA_TEXT, "這是郵件的本文部分"); // 本文  
  9. startActivity(Intent.createChooser(intent, "請選擇郵件類應用"));  

如下所示:

當手機上只有一個匹配的郵件類應用時,系統將不會彈出ChooserActivity,供使用者從候選的應用中挑選一個,而是直接跳轉到匹配的那個應用去。這時查看Eclipse的logcat可以發現,出現如下異常資訊:

 

 

但是,當系統中存在多於一個的匹配應用時,會彈出ChooserActivity,讓使用者選擇一個應用發送郵件,這時查看logcat不會出現之前的異常。這又是為何呢?

 

【ChooserActivity的bug】

從異常資訊中可以看出,代碼在某個地方註冊了IntentReceiver,但卻沒有代碼去解除註冊。具體原因是Android源碼的一個bug,但不影響正常功能,因此可忽略之。想知道詳細原因的可以自己查看Android源碼。是stackoverflow上面的解答,可參考之。

 

 

網址:

http://stackoverflow.com/questions/10068954/why-does-intent-createchooser-need-a-broadcastreceiver-and-how-to-implement/10290486#10290486

 

Demo源碼地址: http://download.csdn.net/detail/ace1985/4695230  

Android調用系統郵件類應用的正確實現方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.