Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Intent 一鍵開啟 Android 常見應用與服務

編輯:Android 開發實例

Intent 是 Android 元件溝通的核心。當你呼叫 startActivity(),系統會依 Intent 攜帶的 action 與資料,找出最合適的程式來接單執行。以下整理開發時最常用到的幾種意圖寫法。

開啟瀏覽器顯示網頁

Uri uri = Uri.parse("https://www.fengfly.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

以座標顯示地圖

Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent intent = new Intent(Intent.Action_VIEW, uri);
startActivity(intent);

撥打電話(呼叫撥號程式)

Uri uri = Uri.parse("tel:13800138000");
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);

開啟簡訊程式並帶入內容

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("sms_body", "FENGFLY.COM");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);

指定號碼傳送簡訊

Uri uri = Uri.parse("smsto:13800138000");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "FENGFLY.COM");
startActivity(intent);

透過多媒體訊息服務傳送圖片

Uri uri = Uri.parse("content://media/external/images/media/exp");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "FENGFLY.COM");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/png");
startActivity(intent);

寄送 Email

Uri uri = Uri.parse("mailto:[email protected]");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(intent);

用 chooser 讓使用者挑選郵件用戶端:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, "[email protected]");
intent.putExtra(Intent.EXTRA_TEXT, "郵件內容。");
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, "Choose Email Client"));

同時指定收件人、副本、主旨與格式:

Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = {"[email protected]"};
String[] ccs = {"[email protected]"};
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_TEXT, "郵件內容。");
intent.putExtra(Intent.EXTRA_SUBJECT, "郵件主題");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Choose Email Client"));

加上附件:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "主題");
intent.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/fengfly.mp3");
intent.setType("audio/mp3");
startActivity(Intent.createChooser(intent, "Choose Email Client"));

播放本機多媒體檔

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/fengfly.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);

實務提醒

原文中的 startActivintenty() 應為 startActivity() 的筆誤。另外 ACTION_DIAL 只會帶使用者到撥號畫面而不會直接撥出,若真要直接撥號需用 ACTION_CALL 並加上 CALL_PHONE 權限;基於資安與使用者體驗,多數應用商店政策建議優先用前者。發送郵件時 EXTRA_EMAIL 要傳字串陣列,傳單一字串在部分版本上不會生效。

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