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

使用 LocalBroadcastManager 實現 Android 組件通信

編輯:關於 Android 程式設計

在 Android 中,組件之間的通信方式有很多種,例如接口回調、EventBus、LiveData、Handler 以及廣播。其中,LocalBroadcastManager 可以用於同一應用內部的組件通信,比普通全局廣播更輕量。

效果說明

本例中,Activity 發送一個本地廣播,同一頁面中的廣播接收器收到後更新 TextView 內容。

布局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="發送廣播" />

</LinearLayout>

Activity 代碼

public class MainActivity extends Activity {
    private Button btn;
    private TextView tv;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.textView1);
        btn = findViewById(R.id.button1);

        broadcastManager = LocalBroadcastManager.getInstance(MainActivity.this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.test1");

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tv.setText("1111");
            }
        };

        broadcastManager.registerReceiver(receiver, filter);

        btn.setOnClickListener(v -> {
            Intent intent = new Intent("com.example.test1");
            broadcastManager.sendBroadcast(intent);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(receiver);
    }
}

使用 LocalBroadcastManager 時,建議在合適的生命週期註冊與解除註冊,例如在 onStart 或 onResume 中註冊,在 onStop 或 onDestroy 中解除,以避免內存泄漏。

相比全局廣播,LocalBroadcastManager 只在本應用內傳遞消息,安全性更高,也更適合處理頁面內部或模塊之間的輕量通信。

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