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

消息總線 EventBus 的基本用法(二十)

編輯:關於 Android 程式設計

前言

專案持續更新中,本篇我們聚焦於消息總線 EventBus 的基本使用方法;至於底層實現原理,則留待下一篇從源碼角度略作剖析。

FastDev4Android 框架專案地址:https://github.com/jiangqqlmj/FastDev4Android

簡介

過去我們在做元件間的消息分發與更新時,通常會採用觀察者模式或接口回調的方式。這些做法雖能解決問題,卻讓元件之間的耦合偏重,程式碼可讀性與可維護性也不理想。EventBus 正是為了解決這一痛點而生。

EventBus 是一款針對 Android 優化的發布/訂閱事件總線,主要用於替代 Intent、Handler、BroadCast,在 Fragment、Activity、Service 與執行緒之間傳遞消息。它的優點是開銷小、程式碼更優雅,並能將發送者與接收者徹底解耦。開源地址:https://github.com/greenrobot/EventBus。

整體的訂閱與接收架構如下圖所示:

EventBus 的主要特點包括:簡化元件間的消息通信、讓程式碼更簡潔、執行速度快、jar 包體積極小(不到 50K),以及支援執行緒間通信、優先級設定等進階能力。

基本用法

在 AndroidStudio 中透過 Gradle 引入依賴:

compile 'de.greenrobot:eventbus:2.4.0'

定義事件物件:

public class MessageEvent {
    /* 如有需要,可加入額外欄位 */
}

在接收頁面進行注册:

eventBus.register(this);

實作接收消息的方法:

public void onEvent(AnyEventType event) {
    /* 在這裡處理消息 */
}

發送消息:

eventBus.post(event);

具體實例

需求描述:第一個 Activity 中有一個按鈕和一個 TextView,點擊按鈕打開第二個 Activity;在第二個 Activity 中點擊按鈕關閉當前頁面,同時把消息回傳給第一個 Activity,顯示在 TextView 上。

我們需要兩個 Activity 的佈局,一個承載按鈕與回顯用的 TextView,另一個則放置觸發回傳的按鈕。

接著建立一個事件類 TestEventFirst,用於封裝回傳的消息內容:

package com.chinaztt.fda.event;

/**
 * EventBus 測試用的事件類
 */
public class TestEventFirst {
    private String msg;
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public TestEventFirst(String msg) {
        this.msg = msg;
    }
}

注册與取消注册分別使用 EventBus.getDefault().register(this) 與 EventBus.getDefault().unregister(this);發送消息則呼叫 EventBus.getDefault().post(new TestEventFirst("我是第二個 Activity 回傳的信息……"))。

在注册的 Activity 中,透過重寫 onEventMainThread() 方法來接收並處理消息(除此之外尚有另外三個方法,將於下一篇介紹):

/**
 * 收到消息後進行相關處理
 */
public void onEventMainThread(TestEventFirst event) {
    textView_one.setText(event.getMsg());
    showToastMsgShort(event.getMsg());
}

其中方法參數 TestEventFirst 就是發送過來的消息類,具體內容皆已封裝其中,我們只需透過 event 物件取出並處理即可。以下為兩個 Activity 的完整程式碼:

@EActivity
public class EventBusTestActivity extends BaseActivity {
    Button button_one;
    TextView textView_one;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_bus_test_layout);
        EventBus.getDefault().register(this);
        button_one = (Button) this.findViewById(R.id.button_one);
        textView_one = (TextView) this.findViewById(R.id.textView_one);
        button_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(EventBusTestTwoActivity_.class);
            }
        });
    }

    public void onEventMainThread(TestEventFirst event) {
        textView_one.setText(event.getMsg());
        showToastMsgShort(event.getMsg());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
@EActivity
public class EventBusTestTwoActivity extends BaseActivity {
    Button button_two;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_bus_test_two_layout);
        button_two = (Button) this.findViewById(R.id.button_two);
        button_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new TestEventFirst("我是第二個 Activity 回傳的信息……"));
                EventBusTestTwoActivity.this.finish();
            }
        });
    }
}

至此,EventBus 的基本用法便講完了。至於更深入的解析、其他幾個方法的介紹以及源碼分析,我們留待下一篇再細說。

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