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

Android 自訂廣播的發送與接收實作

編輯:關於 Android 程式設計

廣播(Broadcast)是 Android 元件間通訊的重要機制之一。本文示範如何發送並接收自訂廣播,同時發送兩個不同 action 的廣播訊息。

發送廣播

透過 sendBroadcast() 即可發送自訂 action 的廣播:

Intent intent = new Intent();
intent.setAction("com.wxq.CUSTOM_INTENT");
sendBroadcast(intent);
intent.setAction("com.wxq.test2");
sendBroadcast(intent);

接收方

在 BroadcastReceiver 的 onReceive() 方法中,可以透過判斷 action 來區分不同的廣播並做相應處理:

@Override
public void onReceive(Context context, Intent intent) {
    String intentName = "com.wxq.CUSTOM_INTENT";
    String intentName2 = "com.wxq.test2";
    if (intent.getAction().equals(intentName))
        Toast.makeText(context, intentName + " Intent Detected", Toast.LENGTH_LONG).show();
    else if (intent.getAction().equals(intentName2))
        Toast.makeText(context, intentName2 + " Intent Detected", Toast.LENGTH_LONG).show();
}

在 AndroidManifest 中註冊接收器

最後別忘了在 AndroidManifest.xml 中加入 receiver 宣告,並為每個 action 配置對應的 intent-filter:

<receiver android:name="MyReceiverTest">
    <intent-filter>
        <action android:name="com.wxq.CUSTOM_INTENT" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.wxq.test2" />
    </intent-filter>
</receiver>

透過以上三個步驟,就能完成自訂廣播的發送與接收。這種機制常用於元件鬆耦合的通訊場景,例如 Activity 之間、Service 與 Activity 之間的通知傳遞。

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