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

Android Intent 解析(一):從 sendBroadcast 出發看架構與發送流程

編輯:關於 Android 程式設計

Intent 是 Android 四大元件之間溝通的核心,但很多人只會用它跳轉 Activity,對它的分發機制並不清楚。這一篇先從最簡單的廣播發送切入,建立整體架構的認識。

Intent 架構的三個角色

Client:發送 Intent 的一方,通常是一個 Activity;
Server:ActivityManagerService(實作在 ActivityManagerService.java 中),負責把 Intent 分發給合適的對象;
Target:真正要處理這個 Intent 的元件,也就是 Receiver。

Intent 的三個主要屬性 Action、Data、Category 決定了「誰有資格收到」,這部分基本概念不再贅述。

回到最簡單的例子

Intent intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
mContext.sendBroadcast(intent);

第一句話構造了一個 Intent,注意只傳入一個參數,也就是 Action,並未指定 Data 與 Category。這意味著只要某個 Receiver 在 AndroidManifest.xml 中宣告了相符的 intent-filter,就能收到:

<receiver android:name="MediaButtonIntentReceiver">
    <intent-filter>
        <action android:name="android.media.AUDIO_BECOMING_NOISY" />
    </intent-filter>
</receiver>

當然,若不喜歡寫在 XML 裡,也可以直接在程式中呼叫 registerReceiver() 動態註冊,效果相同,差別在於動態註冊的接收器只在元件存活期間有效,且必須記得在 onDestroy() 中 unregisterReceiver()。

如此一來,一旦系統監測到這個廣播訊息,該 Receiver 的 onReceive() 就會被呼叫。

第二句話的目的是把訊息廣播出去。這個過程是非同步的:呼叫端把 Intent 交出去就立刻返回,後續誰處理、何時處理,與呼叫端再無關係。

mContext.sendBroadcast(intent) 中的 mContext 是 Application Context,這其實是一次典型的 binder 調用,呼叫之後流程便轉到 ActivityManagerNative.java 中處理,也就是跨進程進入了系統服務端。從這裡開始,接下來的一切都發生在另一個世界裡,下一篇再往下追。

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