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

Android Intent 機制全解:六大屬性、匹配規則與 11 個高頻用法示例

編輯:關於 Android 程式設計

做 Android 開發時,把 Intent 傳給目標組件並完成調用這一步經常出問題,而網上資料又多是零碎片段。本文把 Intent 的介紹、屬性、匹配規則與常見用法做一次系統性整理。

一、Intent 是什麼

Intent 的中文意思是「意圖、意向」。Android 提供 Intent 機制來協助應用間的交互與通訊:它負責描述一次操作要執行的動作、動作涉及的數據以及附加數據,Android 系統再依這份描述找到匹配的組件,把 Intent 傳遞過去並完成調用。

Intent 不僅用於應用之間,也可用於同一應用內部 Activity/Service 的交互。因此可以把 Intent 理解為不同組件之間通信的「媒介」,專門承載組件互相調用所需的信息。

二、Intent 的作用

Intent 是「一個將要執行的動作」的抽象描述,通常作為參數使用,協助完成 Android 各組件之間的通訊。例如呼叫 startActivity() 啟動一個 Activity,用 sendBroadcast() 把消息發送給所有感興趣的廣播接收者,或用 startService()/bindService() 啟動後台服務。可以看出,Intent 主要用來啟動其他 Activity 或 Service,可以理解為 Activity 之間的粘合劑。

三、啟動組件的對應方法

組件方法
ActivitystartActivity()/startActivityForResult()
ServicestartService()/bindService()
BroadcastsendBroadcast()/sendOrderedBroadcast()/sendStickyBroadcast()

四、六大屬性詳解

Intent 由動作(Action)、數據(Data)、分類(Category)、類型(Type)、組件(Component)以及擴展信息(Extras)組成,其中最常用的是 Action 與 Data。

1. Action:要執行的動作

對於這樣的 Activity 聲明:

 <activity android:name=".TargetActivity"> <intent-filter> <action android:name="com.scott.intent.action.TARGET"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> 

TargetActivity 在 <intent-filter> 中聲明了目標 action。要做跳轉時,只需在 Intent 中指定這個 action:

 public void gotoTargetActivity(View view) { Intent intent = new Intent("com.scott.intent.action.TARGET"); startActivity(intent); } 

調用 startActivity 後,系統會依 action 找到並跳轉到對應的 Activity。

除了自定義 action,Intent 也內含大量默認 action:

 public static final String ACTION_MAIN = "android.intent.action.MAIN"; public static final String ACTION_VIEW = "android.intent.action.VIEW"; public static final String ACTION_WEB_SEARCH = "android.intent.action.WEB_SEARCH"; public static final String ACTION_CALL = "android.intent.action.CALL"; 

每個 action 都有其特定用途,能熟記常用幾個,很多功能一行就能實現。

2. Data 與 Extras:操作對象與附帶參數

先看兩個與瀏覽器交互的例子:

 /** * 打開指定網頁 * @param view */ public void invokeWebBrowser(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.google.com.hk")); startActivity(intent); } /** * 進行關鍵字搜索 * @param view */ public void invokeWebSearch(View view) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, "android"); //關鍵字 startActivity(intent); } 

前者對應 ACTION_VIEW,需指定網頁地址;後者對應 ACTION_WEB_SEARCH,需指定關鍵字,瀏覽器會用系統默認搜索引擎執行搜索。

打開網頁時設定的 data 是一個 URI,表示「要操作的數據」。可以把帶特定前綴的字符串轉成 URI 類型,例如 http:/https: 表示網絡地址、tel: 表示電話號碼、mailto: 表示郵件地址。例如撥打電話:

 public void call(View view) { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:")); startActivity(intent); } 

那麼目標是否接受這種前綴,取決於目標 <data/> 元素的匹配規則。它包含幾個子元素:

  • android:scheme:匹配 URL 的前綴,除 http/https/tel 之外也可以自定義。
  • android:host:匹配主機名部分,如 google.com;寫成 * 表示任意主機名。
  • android:port:匹配端口。
  • android:path:匹配路徑。

改寫一下 TargetActivity 的聲明:

 <activity android:name=".TargetActivity"> <intent-filter> <action android:name="com.scott.intent.action.TARGET"/> <category android:name="android.intent.category.DEFAULT"/> <data android:scheme="scott" android:host="com.scott.intent.data" android:port="" android:path="/target"/> </intent-filter> </activity> 

此時只指定 action 已經不夠,必須同時提供匹配的 data:

 public void gotoTargetActivity(View view) { Intent intent = new Intent("com.scott.intent.action.TARGET"); intent.setData(Uri.parse("scott://com.scott.intent.data:/target")); startActivity(intent); }

URL 的每一部分都要與配置完全一致才能跳轉成功,否則系統直接拒絕。顯然把 path 寫死並不靈活——如果實際 URL 是 scott://com.scott.intent.data:7788/target/hello 或 .../target/hi,就匹配不上了。這時改用 android:pathPrefix 聲明「路徑前綴」即可,把 android:path="/target" 換成 android:pathPrefix="/target" 就能覆蓋所有以 /target 開頭的路徑。

而搜索示例中的 putExtra,是把關鍵字作為附加信息(Extras)放進 Intent,背後涉及一個 Bundle 對象。

Bundle 與 Intent 關係密切,主要負責保存附加參數。它實現了 android.os.Parcelable 接口,內部維護一個 Map 屬性以鍵值對形式存放數據。呼叫 putExtra 時,方法會檢查默認的 Bundle 實例是否為空,為空則新建一個,再把參數放進去。也可以自己創建 Bundle 再指定給 Intent:

 public void gotoTargetActivity(View view) { Intent intent = new Intent("com.scott.intent.action.TARGET"); Bundle bundle = new Bundle(); bundle.putInt("id", ); bundle.putString("name", "scott"); intent.putExtras(bundle); startActivity(intent); }

要注意:putExtras 內部做的是復制而非引用。所以設置完 Bundle 之後再修改原 bundle 對象中的數據,不會影響 Intent 內部的附加信息。取值時對應地先取出 Bundle 再逐個讀:

 Bundle bundle = intent.getExtras(); int id = bundle.getInt("id"); String name = bundle.getString("name"); 

也可以直接用 getIntExtra/getStringExtra,數據源同樣是 Intent 內部的 Bundle 實例。

3. Category:目標組件的特質歸類

例如主界面 Activity 通常配置:

 <category android:name="android.intent.category.LAUNCHER" /> 

代表它是該應用所在 task 的初始 Activity,並出現在系統 launcher 的應用列表中。幾個常見 category:

常量解釋
CATEGORY_DEFAULT默認的 category
CATEGORY_BROWSABLE指定後,在網頁點擊圖片或鏈接時,系統會把此 Activity 列入可選列表供用戶選擇
CATEGORY_GADGET該 Activity 可嵌入到承載 gadget 的另一個 Activity 中
CATEGORY_HOME該 Activity 顯示主屏幕,即設備開機或按下 HOME 鍵時的首屏
CATEGORY_LAUNCHER可作為 task 的初始 Activity,並列出在頂層應用列表中
CATEGORY_PREFERENCE表示該 Activity 是一個首選項界面

為 Intent 添加 category 用 addCategory(String)。一個回到 Home 界面的完整例子:

main.xml:

 <?xml version="." encoding="utf-"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="測試Intent Category" /> <Button android:id="@+id/Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="轉到Home界面" /> </LinearLayout> 

strings.xml:

 <?xml version="." encoding="utf-"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">IntentCategoryDemo</string> </resources> 

MainActivity.java:

 package com.android.category.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button)findViewById(R.id.Button); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_MAIN);// 添加Action屬性 intent.addCategory(Intent.CATEGORY_HOME);// 添加Category屬性 startActivity(intent);// 啟動Activity } }); } } 

效果如下:

Home 界面:

4. Type:目標能處理的 MIME 類型

例如一個可處理圖片的 Activity 會聲明:

 <data android:mimeType="image/*" /> 

使用 Intent 匹配時,可用 setType(String) 或 setDataAndType(Uri, String) 設置 mimeType。注意如果同時需要指定 data 與 type,必須用 setDataAndType,分開呼叫 setData() 和 setType() 會互相清空對方的值。

5. Component:明確指定目標組件

 intent.setComponent(new ComponentName(getApplicationContext(), TargetActivity.class)); intent.setComponent(new ComponentName(getApplicationContext(), "com.scott.intent.TargetActivity")); intent.setComponent(new ComponentName("com.scott.other", "com.scott.other.TargetActivity"));

前兩種用於匹配同一包內的目標,第三種用於匹配其他包內的目標。

重要:一旦在 Intent 中指定了 Component,系統將不再對 action、data/type、category 進行匹配。這就是「顯式 Intent」與「隱式 Intent」的分界——前者精確直達、不會彈出選擇框;後者依賴系統匹配,可能出現多個候選應用。

五、11 個高頻用法示例

1. 調用撥號程序

 // 給移動客服撥打電話 Uri uri = Uri.parse("tel:"); Intent intent = new Intent(Intent.ACTION_DIAL, uri); startActivity(intent); 

2. 發送短信或彩信

 // 給發送內容為“Hello”的短信 Uri uri = Uri.parse("smsto:"); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", "Hello"); startActivity(intent); // 發送彩信(相當於發送帶附件的短信) Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra("sms_body", "Hello"); Uri uri = Uri.parse("content://media/external/images/media/"); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.setType("image/png"); startActivity(intent); 

3. 通過瀏覽器打開網頁

 // 打開Google主頁 Uri uri = Uri.parse("https://www.google.com"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); 

4. 發送電子郵件

 // 給someone@domain.com發郵件 Uri uri = Uri.parse("mailto:someone@domain.com"); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); startActivity(intent); // 給someone@domain.com發送內容為“Hello”的郵件 Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, "someone@domain.com"); intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); intent.putExtra(Intent.EXTRA_TEXT, "Hello"); intent.setType("text/plain"); startActivity(intent); // 給多人發郵件 Intent intent=new Intent(Intent.ACTION_SEND); String[] tos = {"@abc.com", "@abc.com"}; // 收件人 String[] ccs = {"@abc.com", "@abc.com"}; // 抄送 String[] bccs = {"@abc.com", "@abc.com"}; // 密送 intent.putExtra(Intent.EXTRA_EMAIL, tos); intent.putExtra(Intent.EXTRA_CC, ccs); intent.putExtra(Intent.EXTRA_BCC, bccs); intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); intent.putExtra(Intent.EXTRA_TEXT, "Hello"); intent.setType("message/rfc"); startActivity(intent); 

5. 顯示地圖與路徑規劃

 // 打開Google地圖中國北京位置(北緯.,東經.) Uri uri = Uri.parse("geo:.,."); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); // 路徑規劃:從北京某地(北緯.,東經.)到上海某地(北緯.,東經.) Uri uri = Uri.parse("https://maps.google.com/maps?f=d&saddr=. .&daddr=. ."); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);

6. 播放多媒體

 Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse("file:///sdcard/foo.mp"); intent.setDataAndType(uri, "audio/mp"); startActivity(intent); Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, ""); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); 

7. 拍照

 // 打開拍照程序 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, ); // 取出照片數據 Bundle extras = intent.getExtras(); Bitmap bitmap = (Bitmap) extras.get("data"); 

8. 獲取並剪切圖片

 // 獲取並剪切圖片 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); intent.putExtra("crop", "true"); // 開啟剪切 intent.putExtra("aspectX", ); // 剪切的寬高比為: intent.putExtra("aspectY", ); intent.putExtra("outputX", ); // 保存圖片的寬和高 intent.putExtra("outputY", ); intent.putExtra("output", Uri.fromFile(new File("/mnt/sdcard/temp"))); // 保存路徑 intent.putExtra("outputFormat", "JPEG");// 返回格式 startActivityForResult(intent, ); // 剪切特定圖片 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setClassName("com.android.camera", "com.android.camera.CropImage"); intent.setData(Uri.fromFile(new File("/mnt/sdcard/temp"))); intent.putExtra("outputX", ); // 剪切的寬高比為: intent.putExtra("outputY", ); intent.putExtra("aspectX", ); // 保存圖片的寬和高 intent.putExtra("aspectY", ); intent.putExtra("scale", true); intent.putExtra("noFaceDetection", true); intent.putExtra("output", Uri.parse("file:///mnt/sdcard/temp")); startActivityForResult(intent, ); 

9. 打開 Google Market

 // 打開Google Market直接進入該程序的詳細頁面 Uri uri = Uri.parse("market://details?id=" + "com.demo.app"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); 

10. 卸載程序

 Uri uri = Uri.fromParts("package", "com.demo.app", null); Intent intent = new Intent(Intent.ACTION_DELETE, uri); startActivity(intent); 

11. 進入系統設置界面

 // 進入無線網絡設置界面(其它可以舉一反三) Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); startActivityForResult(intent, );

六、實戰中容易踩的坑

  1. 找不到匹配 Activity。隱式 Intent 若無任何應用能匹配,startActivity() 會拋 ActivityNotFoundException 直接崩潰。上線前應統一封裝並 try-catch,或先用 resolveActivity() 判斷。
  2. Android 11 的包可見性限制。若需查詢其他應用的組件,要在 manifest 中通過 <queries> 聲明,否則 queryIntentActivities() 會返回空結果。
  3. file:// URI 的文件暴露問題。Android 7.0 起 file:// 形式的 URI 會觸發 FileUriExposedException,應改用 FileProvider 生成 content:// URI 並通過 FLAG_GRANT_READ_URI_PERMISSION 授權。
  4. 示例中的硬編碼路徑。如 /mnt/sdcard/temp 在現今系統上已不可用,應改用 getExternalFilesDir() 或 MediaStore。
  5. ACTION_CALL 需要權限。直接撥號需 CALL_PHONE 這類敏感權限;若不想申請,改用 ACTION_DIAL 只跳到撥號盤並帶入號碼,體驗損失很小。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved