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

EventBus 實戰:用發布訂閱模式取代 Intent 與 Handler 傳遞訊息

編輯:關於 Android 程式設計

做過 Android 開發,遲早都會碰到 EventBus。這是一個針對 Android 最佳化的發布/訂閱事件總線,主要用來取代 Intent、Handler、BroadCast 在 Fragment、Activity、Service 與執行緒之間傳遞訊息。它的優點是開銷小、程式碼更乾淨,而且能把「發送者」與「接收者」徹底解耦——發送方不需要知道誰在聽,接收方也不需要知道訊息從哪來。

一、定義事件類別

事件本身就是一個普通的 POJO,不需要繼承任何基底類別:

package com.example.eventbusdemo;

/**
 * 事件消息實體類
 */
public class MainSendEvent {
    protected String mstrMsg;

    public MainSendEvent(String msg) {
        mstrMsg = msg;
    }

    public String getStringMsgData() {
        return mstrMsg;
    }
}

二、接收方:MainActivity

package com.example.eventbusdemo;

import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 事件註冊
        EventBus.getDefault().register(this);
        InitUI();
    }

    private void InitUI() {
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, TwoActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    // 事件接收:方法名以 onEventMainThread 開頭,表示在主執行緒回呼
    public void onEventMainThread(MainSendEvent event) {
        if (event != null) {
            Toast.makeText(getApplicationContext(),
                    "MainActivity 接受數據 " + event.getStringMsgData(),
                    Toast.LENGTH_LONG).show();
            TextView textView = (TextView) findViewById(R.id.textView1);
            textView.setText(event.getStringMsgData());
        }
    }

    @Override
    public void onDestroy() {
        // 取消註冊,避免記憶體洩漏
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}

三、發送方:TwoActivity

package com.example.eventbusdemo;

import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * TwoActivity 負責發送事件
 */
public class TwoActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                // 事件發送
                EventBus.getDefault().post(new MainSendEvent("from TwoActivity msg"));
                break;
            default:
                break;
        }
    }
}

四、布局檔

activity_main.xml:

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

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第二個 activity" />

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

activity_two.xml:

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

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MainActivity" />
</LinearLayout>

整體流程是:進入 MainActivity → 點按鈕跳到 TwoActivity → 在 TwoActivity 點按鈕發送事件 → MainActivity 收到後用 Toast 提示並 setText,返回後就能看到文字已更新。

五、效果

六、三步驟總結

1. 註冊/訂閱

EventBus.getDefault().register(this);

2. 撰寫接收方法

public void onEventMainThread(MainSendEvent event) {
    if (event != null) {
        Toast.makeText(getApplicationContext(),
                "MainActivity 接受數據 " + event.getStringMsgData(),
                Toast.LENGTH_LONG).show();
        TextView textView = (TextView) findViewById(R.id.textView1);
        textView.setText(event.getStringMsgData());
    }
}

3. 取消註冊

EventBus.getDefault().unregister(this);

前兩步與第三步都在同一個頁面完成,第四步則由發送方執行:

EventBus.getDefault().post(new MainSendEvent("from TwoActivity msg"));

實務上的注意事項

一定要在 onDestroy 中 unregister。這是新手最常犯的錯誤,忘記取消註冊會導致 Activity 被 EventBus 持有的 listener 引用而無法回收,也就是記憶體洩漏。

方法命名決定執行緒。EventBus 3.x 改用 @Subscribe(threadMode = ...) 註解,而上面示範的 2.x 則靠方法名前綴辨識:onEventMainThread 在主執行緒、onEventBackgroundThread 在背景執行緒、onEvent 則在發送時所在的執行緒。若要在背景執行緒更新 UI 之外處理耗時工作,選錯 threadMode 是常見效能問題的來源。

别把它當成資料快取。EventBus 是「一次性事件」,沒有接收方時訊息就直接丟掉了。需要持久保存的狀態應該放在 ViewModel、Repository 或資料庫裡,事件只用來通知「有東西變了」。

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