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

Intent Filter 入門:action、category、data 三要素怎麼搭配

編輯:Android 開發實例

在 Android 中,每個元件可以擁有一個或多個 intent filter。它在主設定檔 AndroidManifest.xml 中註冊,作用是告訴系統:Activity、Service、Broadcast Receiver 這三類元件能夠響應哪些「隱式 Intent」。

Intent Filter 由三部分構成:action、data、category。理解它們的分工,是搞懂 Android 元件如何被系統找到、啟動的關鍵。

一個完整的範例

<intent-filter android:label="@string/Asen's blog">

<action android:name="android.intent.action.MAIN" />

<action android:name="android.intent.action.VIEW" />

<action android:name="android.intent.action.EDIT" />

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

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

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

<data android:mimeType="video/mpeg" android:scheme="http".../>

<data android:mimeType="audio/mpeg" android:content="com.example.project:200/folder/subfolder/etc"/>

</intent-filter>

每個 action、category、data 各佔一行,有多個就多寫幾行。

action:元件想做什麼

action 是一段字串,描述這個元件能處理的「動作」。範例中宣告了三個:MAIN、VIEW、EDIT。其中 "android.intent.action.MAIN" 與 "android.intent.category.LAUNCHER" 這兩個組合是程式入口點的必要條件。

什麼是入口點?以短信這個應用為例,當你點擊桌面圖標啟動後,眼前出現的第一個畫面(所有已收短信的列表)就是入口點。通俗地說,就是應用啟動後顯示的第一個介面。

category:誰適合接收

"android.intent.category.DEFAULT" 用來指明元件是否可以接收隱式 Intent。因此規則很明確:除了程式入口點那個 filter 不需要 DEFAULT 之外,其餘所有 intent filter 都必須包含這個 category,否則隱式啟動時系統會找不到你的元件。

而 LAUNCHER 的作用是讓這個 Activity 出現在桌面啟動器中,ALTERNATIVE 則常用於「用其他應用開啟」這類選單場景。

data:處理什麼樣的內容

data 由兩部分構成:資料類型(mimeType)與 URI。每個 URI 包含四個屬性參數,形如:

scheme://host:port/path

舉例來說,content://com.examplproject:200/folder/subfolder/etc 之中,scheme 是 content,host 是 com.examplproject,port 是 200,path 是 folder/subfolder/etc。

要特別注意的是:如果在 intent filter 中宣告了這些屬性,那麼只有當所有屬性都匹配成功時,URI 資料匹配才會成立——並非符合 scheme 就算通過。

總結來說,Intent Filter 與 Intent 兩者相互配合,實現了 Android 四大元件之間的「信使」功能:元件用 filter 昭告自己能做什麼,系統拿 Intent 去逐一比對,找出最合適的那一個來接手。

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