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

Android Intent 入門筆記:從組成到解析機制

編輯:關於 Android 程式設計

Intent 是一種「執行期綁定(run-time binding)」機制,能在程式運行時連接兩個不同組件。透過 Intent,你的程式可以向 Android 表達某種請求或意願,Android 會依意願內容挑選合適的組件來完成。舉例來說,某個 Activity 想開啟瀏覽器看網頁,只要發出 WEB_SEARCH_ACTION,Android 便會比對各組件註冊時宣告的 IntentFilter,找到瀏覽器的 Activity 來處理。

Android 的三大基本組件——Activity、Service、Broadcast Receiver——都是透過 Intent 啟動的,不同組件有不同的傳遞方式:

1.1 啟動新 Activity 或讓現有 Activity 做新操作,用 Context.startActivity() 或 Activity.startActivityForResult()。

1.2 啟動新 Service 或向現有 Service 傳遞指令,用 Context.startService();若要綁定則用 Context.bindService()。

1.3 發送廣播用 Context.sendBroadcast()、sendOrderedBroadcast()、sendStickyBroadcast(),所有匹配 IntentFilter 的 BroadcastReceiver 都會被啟動。

Intent 一旦發出,Android 會精準找到匹配的組件。不同類型的 Intent 不會重疊:廣播只送給 BroadcastReceiver,startActivity() 只送給 Activity,startService() 只送給 Service。

Intent 的構成

要在不同 Activity 間傳遞資料,Intent 通常需包含以下要素:

Action:指明要執行的動作,如 ACTION_VIEW、ACTION_EDIT,定義於 android.content.Intent 的 constants 中。常用者如 ACTION_CALL(撥打電話)、ACTION_EDIT(編輯資料)、ACTION_MAIN(作為 Task 的第一個 Activity)、ACTION_BATTERY_LOW(電量過低廣播)、ACTION_HEADSET_PLUG(耳機插拔廣播)等。

Data:要處理的具體資料,一般由一個 Uri 表示。

Category:關於處理該 Intent 的組件種類資訊,一個 Intent 可含多個 category,用 addCategory()、removeCategory()、getCategories() 操作。

Type:顯式指定 Intent 的資料型別(MIME)。單筆記錄形如 vnd.android.cursor.item/vnd.yourcompanyname.contenttype,多筆記錄形如 vnd.android.cursor.dir/vnd.yourcompanyname.contenttype。

Component:指定目標組件的類名。一旦指定,Android 直接使用該組件,不再進行查找,此時 Intent 的其他屬性皆為可選。

Extras:附加資訊,透過一組 put...()、get...() 設定與讀取,用法與 Bundle 類似:

// 用 Bundle 傳遞數據 Intent it = new Intent(Activity.Main.this, Activity2.class); Bundle bundle=new Bundle(); bundle.putString("name", "This is from MainActivity!"); it.putExtras(bundle); startActivity(it); // 獲得數據 Bundle bundle2=getIntent().getExtras(); String name=bundle2.getString("name");

顯式 Intent 與隱式 Intent

1. 顯式 Intent:指定了 component 屬性(透過 setComponent 或 setClass),直接通知系統啟動對應組件。

2. 隱式 Intent:未指定 component,需包含足夠資訊,讓系統在所有可用組件中找出最合適的一個。

對於顯式 Intent,Android 無須解析,因為目標已明確;需要解析的是隱式 Intent。

Intent 解析機制

解析主要是查找已註冊於 AndroidManifest.xml 的所有 ,透過 PackageManager 找出能處理該 Intent 的組件。判斷依據為 action、type、category 三個屬性:

1. 若 Intent 指定了 action,目標組件的 IntentFilter 必須包含該 action;

2. 若 Intent 未提供 type,系統會從 data 推得資料型別,目標組件的資料型別清單必須包含它;

3. 若資料不是 content: 型別且未指定 type,則依 scheme(如 http:、mailto:)匹配;

4. 若 Intent 指定了一或多個 category,這些類別必須全部出現在目標組件的類別清單中。

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