程式想告訴Android系統自己能夠響應和處理哪些Intent,那麼就需要用到IntentFilter對象,IntentFilter對象負責過濾掉組件能夠處理的Intent請求,隱式Intent(Explicit
Intents)和Intent Filter(Implicit Intents)進行比較時的三要素是Intent的動作、資料以及類別。實際上,一個隱式Intent請求要能夠傳遞給目標組件,必要通過這三個方面的檢查。如果任何一方面不匹配,Android都不會將該隱式Intent傳遞給目標組件,當匹配一個intent到一個能夠處理資料的組件,通常知道資料的類型(它的MIME類型)和它的URI很重要。例如,一個組件能夠顯示映像資料,不應該被調用去播放一個音頻檔案。
1.動作測試
<intent-filter>元素中可以包括子項目<action>,比如:
<intent-filter>
<action android:name=”com.example.match1” />
<action android:name=”com.example.match2” />
<action android:name=”com.examplematch3” />
</intent-filter>
一條<intent-filter>元素至少應該包含一個<action>,否則任何Intent請求都不能和該<intent-filter>匹配。如果Intent請求中沒有設定Action類型,那麼只要<intent-filter>中包含有Action類型,這個
Intent請求就將順利地通過<intent-filter>的行為測試
2.類別測試
<intent-filter>元素可以包含<category>子項目,比如:
<intent-filter . . . >
<category android:name=”android.Intent.Category.DEFAULT” />
<category android:name=”android.Intent.Category.BROWSABLE” />
</intent-filter>
只有當Intent請求中所有的Category與組件中某一個IntentFilter的<category>完全符合時,才會讓該 Intent請求通過測試,IntentFilter中多餘的<category>聲明並不會導致匹配失敗。一個沒有指定任何類別測試的 IntentFilter僅僅只會匹配沒有設定類別的Intent請求。
3.資料測試
資料在<intent-filter>中的描述如下:
<intent-filter . . . >
<data android:type=”video/*” android:scheme=”http” . . . />
<data android:type=”audio/*” android:scheme=”http” . .
. />
<data
android:type=”image/*” android:scheme=”http” . . . />
</intent-filter>
<data>元素指定了希望接受的Intent請求的資料URI和資料類型,URI被分成三部分來進行匹配:scheme、 authority和path。其中,用setData()設定的Inteat請求的URI資料類型和scheme必須與IntentFilter中所指定的一致。若IntentFilter中還指定了authority或path,它們也需要相匹配才會通過測試。
在許多情況下,資料類型能夠從URI中推測,特別是content:URIs,它表示位於裝置上的資料且被內容提供者(content provider)控制。但是類型也能夠顯示地設定,setData()方法指定資料的URI,setType()指定MIME類型,setDataAndType()指定資料的URI和MIME類型。通過getData()讀取URI,getType()讀取類型。
假如要弄個 XX瀏覽器,要開啟http/https開頭的網址~
在AndroidManifest.xml裡面的 XX Activity屬性下面 配置個 intent-filter
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http"/>
<data android:scheme="https"/>
</intent-filter>
這麼一來,在遇到類似這種代碼( YY Activity 中 啟動一個XX Activity)的時候
Uri uri = Uri.parse("http://www.baidu.com");
startActivity(new Intent(Intent.ACTION_VIEW,uri));
這個時候,在XX Activity裡面就要接收並處理請求了!
getIntent().getData().toString()
就可以得到 http://www.baidu.com 了!
大部分應用程式能啟動新的活動,而不引用任何特別的資料。活動有指定"android.intent.action.MAIN"的動作的過濾器,能夠啟動應用程式。如果它們出現在應用程式啟動列表中,它們也指定"android.intent.category.LAUNCHER"種類: