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

Android 開發實踐:BroadcastReceiver 從廣播發送到接收的完整鏈路

編輯:關於 Android 程式設計

BroadcastReceiver 用於接收系統全局或應用主動發出的廣播意圖,是 Android 四大組件中實現鬆耦合事件通知的關鍵角色。

一、Broadcast 與 BroadcastReceiver 的基本概念

廣播分為兩類:普通廣播(Normal Broadcast)與有序廣播(Ordered Broadcast)。Context 提供了對應的發送方法:

  • sendBroadcast():發送普通廣播,所有匹配的接收者幾乎同時收到,彼此之間沒有先後之分。
  • sendOrderedBroadcast():發送有序廣播,系統會依據接收者聲明的優先級依次執行。優先收到廣播的接收者可以調用 abortBroadcast() 截斷後續傳播。

啟動一個 BroadcastReceiver 只需兩步:

  1. 構造封裝了目標接收者的 Intent;
  2. 調用 sendBroadcast() 或 sendOrderedBroadcast() 將其發出。

需要特別區分的是:OnXxxListener 這類接口只是程序級別的監聽器,而 BroadcastReceiver 是系統級別的組件,可以跨進程工作。

二、發送廣播並接收

(1)在 Activity 中構造 Intent 並發送一條廣播:

Intent intent = new Intent();
intent.setAction("com.gc.action.CRAZY_BROADCAST");
intent.putExtra("msg", "Test Message");
sendBroadcast(intent);

(2)自定義接收者:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("接收到的 Intent Action:" + intent.getAction());
        System.out.println("消息內容是:" + intent.getStringExtra("msg"));
    }
}

(3)為接收者配置需要監聽的 Action,有兩種方式。

方式一,代碼中動態註冊:

IntentFilter filter = new IntentFilter("com.gc.action.CRAZY_BROADCAST");
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, filter);

記得在 Activity 銷毀時調用 unregisterReceiver() 解除註冊,否則容易造成內存洩漏。

方式二,在 AndroidManifest.xml 中靜態聲明:

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="com.gc.action.CRAZY_BROADCAST" />
    </intent-filter>
</receiver>

三、接收系統廣播

系統預置了大量常用 Action 常量,下表列出了一部分,完整清單可查閱官方文檔中 android.content.Intent 的說明。

Action 常量對應字符串說明
ACTION_TIME_CHANGEDandroid.intent.action.TIME_SET系統時間被修改
ACTION_DATE_CHANGEDandroid.intent.action.DATE_CHANGED系統日期被修改
ACTION_BOOT_COMPLETEDandroid.intent.action.BOOT_COMPLETED系統啟動完成
ACTION_SHUTDOWNandroid.intent.action.ACTION_SHUTDOWN系統即將關閉
ACTION_BATTERY_LOWandroid.intent.action.BATTERY_LOW電量過低
ACTION_POWER_CONNECTEDandroid.intent.action.ACTION_POWER_CONNECTED已連接電源
ACTION_POWER_DISCONNECTEDandroid.intent.action.ACTION_POWER_DISCONNECTED與電源斷開

實戰中要留意兩點:其一,靜態註冊的接收者在 Android 8.0 及以上受到隱含廣播限制,多數系統廣播需改用動態註冊或 JobScheduler 等方案;其二,onReceive() 運行在主線程且必須短暫返回,耗時任務應轉交 Service 或線程池處理,切勿在其中做網絡請求或長時間計算。

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