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

Android 常用 Uri 寫法整理:一行 Intent 搞定各種系統功能

編輯:關於 Android 程式設計

Android 中大量系統功能都是靠「Uri + Action」組合喚起的。以下整理實務上最常翻閱的幾種寫法,直接複製即可使用。

瀏覽器與地圖

// 開啟網頁
Uri myBlogUri = Uri.parse("https://xxxxx.com");
Intent it = new Intent(Intent.ACTION_VIEW, myBlogUri);

// 地圖座標(經度,緯度順序為 緯度,經度)
Uri mapUri = Uri.parse("geo:38.899533,-77.036476");
it = new Intent(Intent.ACTION_VIEW, mapUri);

電話

// 撥號面板(不立即撥出,較安全)
Uri telUri = Uri.parse("tel:100861");
Intent it = new Intent(Intent.ACTION_DIAL, telUri);

// 直接撥打(需 CALL_PHONE 權限,且 6.0 起屬執行期權限)
Uri callUri = Uri.parse("tel:100861");
it = new Intent(Intent.ACTION_CALL, callUri);

安裝與移除應用

// 移除
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
Intent it = new Intent(Intent.ACTION_DELETE, uninstallUri);

// 安裝(較新版本建議改用 ACTION_VIEW 搭配 file:// 或 FileProvider)
Uri installUri = Uri.fromParts("package", "xxx", null);
it = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

播放媒體

Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, playUri);

電子郵件

// 喚起郵件撰寫
Uri emailUri = Uri.parse("mailto:xxxx@gmail.com");
Intent it = new Intent(Intent.ACTION_SENDTO, emailUri);

// 帶入完整欄位,並讓使用者挑選郵件客戶端
Intent mail = new Intent(Intent.ACTION_SEND);
String[] tos = { "xxxx@gmail.com" };
String[] ccs = { "xxxx@gmail.com" };
mail.putExtra(Intent.EXTRA_EMAIL, tos);
mail.putExtra(Intent.EXTRA_CC, ccs);
mail.putExtra(Intent.EXTRA_TEXT, "body");
mail.putExtra(Intent.EXTRA_SUBJECT, "subject");
mail.setType("message/rfc882");
startActivity(Intent.createChooser(mail, "Choose Email Client"));

簡訊與多媒體簡訊

// 開啟簡訊撰寫
Uri smsUri = Uri.parse("tel:100861");
Intent it = new Intent(Intent.ACTION_VIEW, smsUri);
it.putExtra("sms_body", "yyyy");
it.setType("vnd.android-dir/mms-sms");

// 直接指定收件人
Uri smsToUri = Uri.parse("smsto://100861");
it = new Intent(Intent.ACTION_SENDTO, smsToUri);
it.putExtra("sms_body", "yyyy");

// 附加圖片(彩信)
Uri mmsUri = Uri.parse("content://media/external/images/media/23");
it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "yyyy");
it.putExtra(Intent.EXTRA_STREAM, mmsUri);
it.setType("image/png");

實務上容易踩到的幾點

直接撥號(ACTION_CALL)與讀寫聯絡人等,在 Android 6.0 之後都屬於執行期危險權限,必須動態申請;argetSdk 30 以上已禁止以 file:// URI 分享檔案,安裝與播放請改用 FileProvider 搭配 content:// URI 並授予 FLAG_GRANT_READ_URI_PERMISSION;smsto: 與 mailto: 這類未指定 Action 的寫法,建議統一改用 ACTION_SENDTO,系統才會過濾出真正能處理該協定的應用。另外,任何 startActivity 之前最好包一層 try-catch,避免裝置上沒有可處理的應用時直接崩潰。

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