close

Intent-filter

  • 判斷Intent的傳遞對象
  • 判斷哪個元件可以接收哪個intent
  • 每個Activity內可以設定0~多組的intent filter,每一組的Intent Filter都是一份比對規則
  • intent發出來時,系統會去檢查Manifest內各元件內的intent filter,而啟動適合的元件
  • Intent filter內會設定的資料包括action,datacategory三種
  • Intent Filter都是以XML方式寫在AndroidManifest.xml檔內,broadcast receiversintent filter例外。
  • intent filter做比對,比對時需進行3test,當這3test都通過,元件才可接手處理這Intent
  • Intent Filter的作用,不僅是找出intent所要啟動的元件,還包括了設定元件該出現在Device的相關訊息
    • 例如在Filter內設定了"android.intent.action.MAIN""android.intent.category.LAUNCHER"這元件會出現在device最上層的Launch清單上
    • 例如元件的filter設定了android.intent.category.HOME"那這元件就會顯示在Home screen上利用PackageManager Class的相關method針對指定intent找出適合的元件

Test(ActionCategoryData)

  • Action
    • filter內至少要有一項action,若都沒有就沒有任何intent可以通過這filter

<intent-filter . . . > 
       <action android:name="com.example.project.SHOW_CURRENT" /> 
       <action android:name="com.example.project.SHOW_RECENT" />     
        . . . 
</intent-filter> 

  • Category
    • intent有設定Category,則需要通過所有filter設定的CategoryTest才會pass
    • intent沒有設定Category,則設定pass
    • Activity要能接收到intent,Mainfest內定義的Category需有"android.intent.category.DEFAULT"的值
  • Data
    • 每個data tag都包含了URIdata type (MIME media type)URI會以scheme, host, port, path來表示
    • 可以把一個完整的URI看成

scheme://host:port/path

  • filter內沒有設定任何data tag,intent內也沒有設定URIdata type,
  • test就通過
    • filter有設定URI,沒有設定data type,intent object也是只有URI沒有data type,這時候通過,這通常只會發生在mailto: tel:
    • filter內只有設定data type 沒有設定URI,intent object有設定相同的data typeURI則通過
    • filter內設定的data typeURI都與intent Object內設定的對應即通過若filter內只有設定data typeURI不設定,只有在intent Objectdata type有對應,而URIcontent: file:才會通過

Example

  • 設定元件可以顯示local 任何Image檔案

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

  • 設定允許播放來自internet的任何影片檔

<data android:scheme="http" android:type="video/*" /> 

  • 設定啟動預設執行的Activity

<intent-filter . . . >
               <action android:name="code android.intent.action.MAIN" /> 
               <category android:name="code android.intent.category.LAUNCHER" />
          </intent-filter>

  • 不需透過任何intent去觸發,在開啟App即會自動執行這個Activity
arrow
arrow

    y23462001 發表在 痞客邦 留言(0) 人氣()