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

消息總線 EventBus 基本用法(二十):組件解耦實戰

編輯:關於 Android 開發

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

一、前言

專案持續更新,這一期講 EventBus 的基本用法,下一篇會從源碼角度剖析它的實現過程。

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

二、為什麼需要 EventBus

以前做組件間的消息分發,通常是觀察者模式或者接口回調。這些做法能解決問題,但代價是組件之間耦合嚴重,程式碼可讀性和可維護性都變差。

EventBus 是一款針對 Android 優化的發布/訂閱事件總線,主要用來替代 Intent、Handler、BroadCast 在 Fragment、Activity、Service 與線程之間傳遞消息。它的優點是開銷小、寫法優雅,並把發送者與接收者彻底解耦。

開源地址:https://github.com/greenrobot/EventBus

它的特點可以歸納為:

  • 簡化組件間的消息通信
  • 讓程式碼更簡潔
  • 性能很好
  • jar 包極小,不到 50K
  • 支援線程切換、事件優先級等進階能力

三、基本用法

3.1 Gradle 配置

compile 'de.greenrobot:eventbus:2.4.0'

3.2 定義事件對象——一個普通 POJO 即可,不需要繼承任何類:

public class MessageEvent {
    /* Additional fields if needed */
}

3.3 在接收方註冊

eventBus.register(this);

3.4 撰寫接收方法——方法名以 onEvent 開頭,參數類型即為事件類型:

public void onEvent(AnyEventType event) {
    /* Do something */
}

3.5 發送消息

eventBus.post(event);

四、完整示例:Activity 之間回傳消息

4.1 需求:第一個 Activity 有一個按鈕和一個 TextView。點擊按鈕打開第二個 Activity;在第二個 Activity 點擊按鈕關閉自己,同時把消息回傳給第一個 Activity 顯示在 TextView 上。

用傳統寫法,這需要 startActivityForResult + onActivityResult 一整套流程;用 EventBus,只需一次 post。

4.2 兩個布局

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

    <Button
        android:id="@+id/button_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點擊打開第二個 Activity" />

    <TextView
        android:id="@+id/textView_one"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:text="這邊顯示消息內容..." />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第二個 Activity 的按鈕" />

    <TextView
        android:id="@+id/textView_two"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:text="當前為第二個 Activity" />
</LinearLayout>

4.3 定義事件類——把要傳遞的資料封裝在裡面:

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;
    }
}

4.4 註冊與反註冊

// 註冊
EventBus.getDefault().register(this);

// 反註冊,必須成对出現,否則會內存洩漏
EventBus.getDefault().unregister(this);

4.5 發送消息

EventBus.getDefault().post(new TestEventFirst("我是第二個 Activity 回傳的信息...."));

4.6 接收消息——在已註冊的 Activity 中重寫 onEventMainThread(),它保證回調發生在主線程,可以直接更新 UI:

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

方法參數的類型就是事件類型,所有資料都封裝在 event 對象裡,取出使用即可。(除此之外 EventBus 還有另外三個回調方法,下一篇再細說。)

4.7 兩個 Activity 的完整程式碼

package com.chinaztt.fda.test;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chinaztt.fda.event.TestEventFirst;
import com.chinaztt.fda.ui.R;
import com.chinaztt.fda.ui.base.BaseActivity;

import org.androidannotations.annotations.EActivity;

import de.greenrobot.event.EventBus;

/**
 * EventBus 組件間數據通信示例
 */
@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);
    }
}
package com.chinaztt.fda.test;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.chinaztt.fda.event.TestEventFirst;
import com.chinaztt.fda.ui.R;
import com.chinaztt.fda.ui.base.BaseActivity;

import org.androidannotations.annotations.EActivity;

import de.greenrobot.event.EventBus;

@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();
            }
        });
    }
}

這裡最容易踩的坑只有一個:register 與 unregister 必須成对,否則 Activity 被銷毀後仍被總線持有,內存洩漏與「更新已死界面」的怪異 bug 都會跟著來。EventBus 的基本用法到此結束,更深入的解析與其他回調方法留待下一篇。

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