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

用廣播(Broadcast)在元件之間傳遞資料的完整機制

編輯:關於 Android 程式設計

廣播是 Android 元件間通訊的常見方式,特別適合在同一個應用內的不同元件之間傳遞資料。整個流程可分為三個步驟:註冊廣播、發送廣播、接收廣播。切記:註冊廣播必須在接收廣播之前完成。

步驟一:註冊廣播

MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter(); // 建立 IntentFilter 物件
filter.addAction("android.intent.action.test");
registerReceiver(receiver, filter);

其中 MyReceiver 是廣播接收器。若需要同時接收多個廣播,可重複呼叫 filter.addAction("不同的標識") 來加入多組 action。

步驟二:發送廣播

Intent intent = new Intent();
intent.setAction("android.intent.action.test"); // action 需與接收器相同

Bundle bundle = new Bundle();
bundle.putSerializable("showAllFriends", list); // 在這裡放入要傳遞的資料
intent.putExtras(bundle);

sendBroadcast(intent);

關鍵在於發送時設定的 action 必須與接收器註冊時一致,資料則透過 Bundle 封裝後隨 Intent 一起送出。

步驟三:接收廣播

/**
 * 廣播接收器
 */
public static class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Object data = bundle.getSerializable("showAllFriends");
        System.out
            .println("---------------------------------------------------------------------");
    }

    public MyReceiver() {
        System.out.println("MyReceiver");
        // 建構子,可做初始化工作,本例中無實際作用
    }
}

接收器會在 onReceive() 中透過 getExtras() 取出 Bundle,再用發送時約定好的 key(此例為 showAllFriends)把資料取回。透過這套機制,就能在同一應用的元件之間靈活傳遞物件資料。

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