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

Android Intent 與 Intent Filter:元件溝通的完整指南

編輯:進階開發

Intent 顧名思義就是「意圖」,是一個承載意圖的物件,負責把訊息從一個元件傳到另一個元件——可能在同一个 App 內部,也可能跨越 App 邊界。它是 Android 三大核心元件(Activity、Service、Broadcast Receiver)之間溝通的唯一途徑。

Intent 本身是一個被動的資料結構,只描述「想做什麼」,不決定「誰來做」。舉個例子:某個 Activity 想寄信,它就送出一個帶有 ACTION_SEND 的 Intent 交給 Android 的 Intent 解析器,並附上合適的 choices,由使用者挑選要用哪個郵件用戶端處理。同樣地,若 Activity 想用瀏覽器開啟網址,就送出 ACTION_VIEW,解析器會從所有活動中挑出最合適的那一個(此例即瀏覽器)並啟動它。

每種元件都有各自的送出機制:

方法說明
Context.startActivity()傳入 Intent 以啟動新 Activity,或讓既有 Activity 執行新的工作。
Context.startService()傳入 Intent 以啟動服務,或對持續執行的服務下達新指令。
Context.sendBroadcast()傳入 Intent,把訊息散播給所有感興趣的廣播接收器。

Intent 物件的組成

Intent 是一包資訊,依「要做什麼」與「和誰溝通」而異,主要由以下幾個部分構成。

Action(動作)

一個字串,用來命名要執行的操作或正在發生的動作,它極大程度地決定了 Intent 其餘部分的結構。Intent 類別定義了許多對應不同意圖的標準動作常數,可用 setAction() 設定、getAction() 讀取。

Data(資料)

動作作用的對象,由 URI 與該資料的 MIME 型別組成。例如當 action 為 ACTION_EDIT 時,data 就會放要編輯的文件的 URI。設定方式有三種:setData() 只指定 URI、setType() 只指定 MIME 型別、setDataAndType() 兩者都指定;讀取則用 getData() 與 getType()。以下幾組動作/資料的搭配很常見:

動作/資料配對說明
ACTION_VIEW content://contacts/people/1顯示 id 為「1」的聯絡人資訊。
ACTION_DIAL content://contacts/people/1開啟撥號程式並帶入該聯絡人的號碼。
ACTION_VIEW tel:123開啟撥號程式並帶入號碼 123。
ACTION_DIAL tel:123開啟撥號程式並帶入號碼 123。
ACTION_EDIT content://contacts/people/1編輯 id 為「1」的聯絡人資訊。
ACTION_VIEW content://contacts/people/顯示可瀏覽的聯絡人清單。

Category(類別)

類別是可選的補充資訊,以字串形式告訴系統哪些元件適合處理這個 Intent。以 addCategory() 加入、removeCategory() 移除、getCategories() 取得目前所有類別。它常與 Intent Filter 搭配,用來篩選出合適的目標活動。

Extras(額外資料)

這是一組鍵值對,用來攜帶更多處理所需的資訊,以 putExtras() 設定、getExtras() 讀取。

Flags(旗標)

這些旗標是 Intent 的可選部分,用來指示 Android 系統如何啟動一個 Activity,以及啟動後要如何對待它(例如是否納入回退堆疊)。

Component Name(元件名稱)

可選欄位,用來指定目標 Activity、Service 或 BroadcastReceiver 的類別名稱。若未設定,Android 會依 Intent 中的其他資訊自行尋找合適的目標。可用 setComponent()、setClass()、setClassName() 設定,以 getComponent() 讀取。

兩種 Intent

顯式 Intent(Explicit Intent)

直接指定目標元件的類別名稱,通常用於應用程式內部的溝通,例如由一個 Activity 啟動同 App 的服務或另一個 Activity:

 // Explicit Intent by specifying its class name Intent i = new Intent(this, TargetActivity.class); i.putExtra("Key1", "ABC"); i.putExtra("Key2", "123"); // Starts TargetActivity startActivity(i);

隱式 Intent(Implicit Intent)

不指名目標,而是宣告「我想做什麼」,交由系統找出所有符合的元件:

 // Implicit Intent by specifying a URI Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com")); // Starts Implicit Activity startActivity(i);

目標元件可以用 getExtras() 取出對方送來的額外資料:

 // Get bundle object at appropriate place in your code Bundle extras = getIntent().getExtras(); // Extract data using passed keys String value1 = extras.getString("Key1"); String value2 = extras.getString("Key2");

範例一:啟動系統內建應用

這個範例示範用 Intent 啟動 Android 內建的瀏覽器與電話功能。

步驟說明
1用 Eclipse IDE 建立專案 IntentDemo,套件 com.example.intentdemo。建立時請把目標 SDK 設為最新版本,以便使用較新的 API。
2修改 MainActivity.java,為兩個按鈕加上監聽器,分別啟動瀏覽器與電話。
3修改 res/layout/activity_main.xml,以線性配置放入按鈕。
4在 res/values/strings.xml 定義所需常數。
5執行應用程式並驗證結果。

MainActivity.java:

 package com.example.intentdemo; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBrowser = (Button) findViewById(R.id.start_browser); startBrowser.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.example.com")); startActivity(i); } }); Button startPhone = (Button) findViewById(R.id.start_phone); startPhone.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel:9510300000")); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

activity_main.xml:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start_browser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser"/> <Button android:id="@+id/start_phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_phone" /> </LinearLayout>

strings.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">IntentDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="start_browser">Start Browser</string> <string name="start_phone">Start Phone</string> </resources>

執行 IntentDemo(確認 AVD 與環境都已就緒,點擊工具列上的「Run」圖示),按下「Start Browser」就會開啟瀏覽器並載入 https://www.example.com;按下「Start Phone」則會帶入指定號碼的撥號畫面。

Intent Filter 的運作機制

前面看到 Intent 如何呼叫一個 Activity,而 Android 判斷「誰能處理這個 Intent」靠的就是過濾器。在 manifest 檔中以 <intent-filter> 元素列出某個 Activity、Service 或 Receiver 所能處理的 action、category 與資料型別:

 <activity android:name=".CustomActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="com.example.intentdemo.LAUNCH" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> </intent-filter> </activity>

以上宣告意味著:只要 Intent 的 action 是 android.intent.action.VIEW 或 com.example.intentdemo.LAUNCH,且 category 符合 android.intent.category.DEFAULT,而資料以「https://」開頭,就可以呼叫 CustomActivity。

Android 的比對規則可以整理成幾項測試:

  • 動作測試:過濾器至少要包含一個 <action> 元素,否則會阻擋所有 Intent。若列出多個 action,Intent 只要符合其中一個就算通過。
  • 類別測試:<intent-filter> 可以列零個、一個或多個類別。沒有列任何類別時一律通過;若 Intent 帶有多個類別,則每一個都必須能在過濾器中對應上。
  • 資料測試:每個 <data> 元素可指定 URI 與 MIME 型別,URI 又能拆成 scheme、host、port、path 等屬性分別比對。同時帶有 URI 與型別的 Intent,只有當型別相符、且 URI 各段落在過濾器宣告的範圍內時才會通過。

若同一個 Intent 同時符合多個元件的過濾器,系統會讓使用者選擇要啟動哪一個;若完全找不到符合的目標,則會丟出例外。

範例二:Intent 衝突與例外

這個範例示範三種情況:兩個 Activity 同時符合而需由使用者選擇、只有自訂 Activity 符合、以及完全沒有符合目標而拋出例外。

步驟說明
1建立專案 IntentDemo,套件 com.example.intentdemo,目標 SDK 設為最新版本。
2修改 MainActivity.java,為三個按鈕加上監聽器。
3新增 src/CustomActivity.java,作為被不同 Intent 呼叫的自訂活動。
4修改 res/layout/activity_main.xml,加入三個按鈕。
5新增 res/layout/custom_view.xml,用 <TextView> 顯示 Intent 傳來的資料。
6修改 res/values/strings.xml 定義所需常數。
7修改 AndroidManifest.xml,為自訂活動加上 <intent-filter> 規則。
8執行應用程式並驗證三種情境。

MainActivity.java:

 package com.example.intentdemo; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // First intent to use ACTION_VIEW action with correct data Button startBrowser_a = (Button) findViewById(R.id.start_browser_a); startBrowser_a.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.example.com")); startActivity(i); } }); // Second intent to use LAUNCH action with correct data Button startBrowser_b = (Button) findViewById(R.id.start_browser_b); startBrowser_b.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse("https://www.example.com")); startActivity(i); } }); // Third intent to use LAUNCH action with incorrect data Button startBrowser_c = (Button) findViewById(R.id.start_browser_c); startBrowser_c.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent("com.example.intentdemo.LAUNCH", Uri.parse("https://www.example.com")); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

CustomActivity.java 會把收到的 URI 顯示出來:

 package com.example.intentdemo; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.widget.TextView; public class CustomActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_view); TextView label = (TextView) findViewById(R.id.show_data); Uri url = getIntent().getData(); label.setText(url.toString()); } }

activity_main.xml:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start_browser_a" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_a"/> <Button android:id="@+id/start_browser_b" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_b"/> <Button android:id="@+id/start_browser_c" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_browser_c"/> </LinearLayout>

custom_view.xml:

 <?xml version="1.0" encoding="utf-8"?> <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:id="@+id/show_data" android:layout_width="fill_parent" android:layout_height="400dp"/> </LinearLayout>

strings.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">IntentDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="start_browser_a">Start Browser with VIEW action</string> <string name="start_browser_b">Start Browser with LAUNCH action</string> <string name="start_browser_c">Exception Condition</string> </resources>

AndroidManifest.xml 中,CustomActivity 帶上了自訂的過濾器規則:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.intentdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.intentdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.intentdemo.CustomActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="com.example.intentdemo.LAUNCH" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> </intent-filter> </activity> </application> </manifest>

觀察三種結果

按下「Start Browser with VIEW Action」:系統發現瀏覽器與 CustomActivity 都符合這個 Intent,於是跳出選擇清單。選瀏覽器就會開啟 example.com;選 IntentDemo 則會進入 CustomActivity,它什麼也不做,只把收到的資料顯示在文字方塊上。

用返回鍵回到主畫面,按「Start Browser with LAUNCH Action」:只有 CustomActivity 的過濾器宣告了這個自訂 action,因此系統直接啟動它,畫面呈現相同。

再按返回鍵並點「Exception Condition」:這次 Intent 的資料是 https 而非 http,雖然 action 正確,但 scheme 與過濾器宣告的 http 不符,系統找不到任何有效目標,於是丟出例外並顯示錯誤畫面。

這三個情境把 Intent 解析的核心邏輯講得很清楚:action、category、data 三者必須同時通過測試,元件才會被納入候選;候選不唯一時交給使用者決定,候選為零時則是錯誤。實務上,為避免 ActivityNotFoundException 造成閃退,呼叫 startActivity() 前可以用 resolveActivity() 或 queryIntentActivities() 先確認目標是否存在。

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