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

Android 隨手記:廣播(Broadcast)的發送與接收

編輯:關於 Android 程式設計

廣播(Broadcast)是 Android 中一項重要的元件間通訊機制,可用於在應用程式內外傳遞訊息。以下分別說明廣播的發送與接收流程。

一、廣播的發送

Android 在發送廣播時使用的方法是 sendBroadcast(Intent),主要步驟如下:

  1. 建立 Intent 物件:
    Intent myIntent = new Intent();
  2. 設定要執行的動作:
    myIntent.setAction(String);
    參數為動作的名稱(如 ACTION_VIEW)。應用程式的具體行動,建議以其套件名稱作為前綴,以避免與其他應用衝突。
  3. 加入額外資料:
    myIntent.putExtra(String, Object);
    其中 String 為自訂的 key,Object 則代表多種資料型別,用於在廣播中附帶傳遞資料。
  4. 發送廣播:
    sendBroadcast(myIntent);

二、廣播的接收

Android 在接收廣播時,方法是註冊一個廣播接收器 registerReceiver(MyReceiver, IntentFilter),步驟如下:

  1. 建立廣播接收器:先建立 MyReceiver 類別(類名自訂),繼承 BroadcastReceiver 類別。
  2. 重寫處理方法:在 MyReceiver 中重寫 public void onReceive(Context context, Intent intent) 方法,這個方法會在接收到廣播後觸發。
  3. 啟動時實例化:在 Activity 或 Service 啟動時(如 onCreate()、onStartCommand() 等方法中)實例化 MyReceiver 類別。
  4. 建立 IntentFilter 物件:
    IntentFilter filter = new IntentFilter();
    即「意圖過濾器」。
  5. 加入過濾條件:
    filter.addAction(String);
    說明要接收哪些廣播。
  6. 註冊廣播:
    registerReceiver(cmdReceiver, filter);
    參數分別為(廣播接收器、意圖過濾器)。

重點提醒:記得在 Activity 的 onPause() 或 onDestroy() 中呼叫 unregisterReceiver() 取消註冊,避免造成記憶體洩漏。此外,發送端設定的 action 必須與接收端 IntentFilter 中的過濾條件一致,廣播才能被正確接收。

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