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

用 EventBus 在元件之間傳遞訊息的實作教學

編輯:關於 Android 程式設計

一、EventBus 是什麼

EventBus 是一套針對 Android 最佳化過的發布/訂閱事件總線,主要用來取代 Intent、Handler 與 Broadcast,在 Fragment、Activity、Service 與各執行緒之間傳遞訊息。它的優點是開銷小、程式碼乾淨,並能把訊息的發送者與接收者徹底解耦。

EventBus 類庫原始碼:EventBus_jb51.rar

二、五個基本步驟

1. 定義一個事件類別,內容可以是空的:

 public class AnyEventType {
 public AnyEventType() {}
 }

2. 在接收方註冊:

 eventBus.register(this);

3. 發送訊息:

 eventBus.post(new AnyEventType());

4. 在接收方實作對應的接收方法(EventBus 提供四種方法,可依需求選擇,這裡先實作一種):

 public void onEvent(AnyEventType event) { }

5. 註銷:

 eventBus.unregister(this);

順序大致如此,但真正動手時仍容易糊塗,因此下面用一個完整例子說明。取得實例時,建議一律使用 EventBus.getDefault(),避免自行 new 出多個物件造成訊息收不到。

三、實戰演練

目標:點擊 btn_try 跳到第二個 Activity;在第二頁點「First Event」按鈕後向第一頁發送訊息;第一頁收到後,一方面用 Toast 提示,一方面把內容顯示在 TextView 上。

先把兩個頁面的骨架搭好。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/btn_try"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="btn_bty"/>
 <TextView
 android:id="@+id/tv"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"/>
 </LinearLayout>

activity_second.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"
 tools:context="com.harvic.try_eventbus_1.SecondActivity" >
 <Button
 android:id="@+id/btn_first_event"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="First Event"/>
 </LinearLayout>

MainActivity 先只負責跳轉:

 public class MainActivity extends Activity {
 Button btn;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 btn = (Button) findViewById(R.id.btn_try);
 btn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
 startActivity(intent);
 }
 });
 }
 }

接著建立事件類別 FirstEvent,構造時帶入一則訊息,並提供 getter:

 package com.harvic.other;

 public class FirstEvent {
 private String mMsg;

 public FirstEvent(String msg) {
 mMsg = msg;
 }

 public String getMsg() {
 return mMsg;
 }
 }

由於要接收訊息的是 MainActivity,註冊就寫在它的 onCreate 中,並在 onDestroy 註銷:

 package com.example.tryeventbus_simple;

 import com.harvic.other.FirstEvent;
 import de.greenrobot.event.EventBus;
 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity extends Activity {
 Button btn;
 TextView tv;

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

 EventBus.getDefault().register(this);

 btn = (Button) findViewById(R.id.btn_try);
 tv = (TextView) findViewById(R.id.tv);
 btn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
 startActivity(intent);
 }
 });
 }

 public void onEventMainThread(FirstEvent event) {
 String msg = "onEventMainThread 收到了訊息:" + event.getMsg();
 Log.d("harvic", msg);
 tv.setText(msg);
 Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
 }

 @Override
 protected void onDestroy() {
 super.onDestroy();
 EventBus.getDefault().unregister(this);
 }
 }

發送端用 post(),傳過去的就是事件類別的實例:

 package com.example.tryeventbus_simple;

 import com.harvic.other.FirstEvent;
 import de.greenrobot.event.EventBus;
 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;

 public class SecondActivity extends Activity {
 private Button btn_FirstEvent;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_second);
 btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
 btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
 }
 });
 }
 }

接收端這裡選用 onEventMainThread(),因為它保證回呼發生在主執行緒,可以直接更新 UI;至於其他三種接收方法與 EventBus 的內部識別機制,留待下一篇再深入說明。

原始碼:EventBus_jb51.rar

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