淺談 EventBus:Android 上的發布/訂閱事件總線
概述:
EventBus 是一款針對 Android 優化的發布/訂閱事件總線。它的主要功能,是在 Fragment、Activity、Service 乃至線程之間替代 Intent、Handler、BroadCast 來傳遞消息。其優點在於開銷小、程式碼更優雅,並且能把發送者與接收者徹底解耦。
------------------------------------------------------------------
下載:
類庫源碼:https://github.com/greenrobot/EventBus
jar 包:https://download.csdn.net/detail/yy1300326388/8727699
------------------------------------------------------------------
使用:
在 Android Studio 中導入第三方類庫稍嫌麻煩,因此這裡我直接使用 jar 包(導入 jar 包的方式就不多贅述了)。
一、EventBus 的使用,簡單來說就是五步:建立一個類(具體用法見下文)、註冊、發送消息、接收消息、解除註冊。
看一個 Demo:
實現功能:有兩個 Activity,第一個 Activity 跳轉到第二個 Activity,第二個 Activity 點擊按鈕發送消息,第一個 Activity 中的 TextView 顯示接收到的消息內容。

1、先寫下兩個 Activity 的布局

![]()
1 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 2 xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" 3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 4 android:paddingRight="@dimen/activity_horizontal_margin" 5 android:paddingTop="@dimen/activity_vertical_margin" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:orientation="vertical" 8 tools:context=".MainActivity"> 9 10 <TextView 11 android:layout_gravity="center" 12 android:id="@+id/show_msg" 13 android:text="@string/hello_world" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" /> 16 17 <Button 18 android:id="@+id/to_second_activity" 19 android:layout_gravity="center" 20 android:layout_width="wrap_content" 21 android:layout_height="wrap_content" 22 android:text="跳轉第二個Activity"/> 23 24 </LinearLayout> activity_main

![]()
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 3 android:orientation="vertical" android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 <Button 7 android:layout_width="wrap_content" 8 android:layout_height="wrap_content" 9 android:text="發送一個消息" 10 android:id="@+id/send_msg" /> 11 12 <Button 13 android:id="@+id/btn_finish" 14 android:text="銷毀這個Activity,返回第一個Activity" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" /> 17 </LinearLayout> activity_second
2、建立一個類,構造方法的參數並不固定,隨意撰寫即可,哪怕是空類也行,它用於傳遞消息,具體視需求而定。
package com.xqx.com.eventbusdemo; public class MyMessage { private String string; public MyMessage(String string) { this.string = string; } public String getString() { return string; } }
3、在接收消息的頁面(第一個 Activity)註冊並解除註冊 EventBus,然後取得並處理消息。
在 onCreate() 方法中註冊:
EventBus.getDefault().register(this);
在 onDestroy() 方法中取消註冊:
EventBus.getDefault().unregister(this);
實作取得並處理消息的方法,這裡先使用 onEventMainThread(),代表接收到消息並在 UI 線程中操作:
public void onEventMainThread(MyMessage event) { String msg = "onEventMainThread收到了消息:" + event.getString(); show_msg.setText(msg); }
完整程式碼:

![]()
package com.xqx.com.eventbusdemo; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import de.greenrobot.event.EventBus; public class MainActivity extends Activity { //按鈕,開啟第二個Activity private Button to_second_activity; //文本,顯示接收到的消息 private TextView show_msg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); to_second_activity = (Button) findViewById(R.id.to_second_activity); show_msg = (TextView) findViewById(R.id.show_msg); //注冊 EventBus.getDefault().register(this); //點擊按鈕進入到第二個Activity to_second_activity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,SecondActivity.class)); } }); } //接收消息並處理 public void onEventMainThread(MyMessage event) { String msg = "onEventMainThread收到了消息:" + event.getString(); show_msg.setText(msg); } @Override protected void onDestroy() { super.onDestroy(); // 解除注冊 EventBus.getDefault().unregister(this); } } MainActivity.class
4、在要發送消息的頁面發送消息。
發送消息很簡單,參數就是你自己寫的那個類:
EventBus.getDefault().post(new MyMessage("this is a message"));
完整程式碼:

![]()
package com.xqx.com.eventbusdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import de.greenrobot.event.EventBus; public class SecondActivity extends Activity{ private Button send_msg; private Button btn_finish; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); send_msg = (Button) findViewById(R.id.send_msg); btn_finish = (Button) findViewById(R.id.btn_finish); send_msg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new MyMessage("this is a message")); } }); btn_finish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } SecondActivity.class
------------------------------------------------------------------
EventBus 其他知識說明:
1、EventBus 提供了四種不同的消息接收處理方法:
onEvent:
使用onEvent,那麼該事件在哪個線程發布出來的,onEvent就會在這個線程中運行,也就是說發布事件和接收事件線程在同一個線程。使用這個方法時,在onEvent方法中不能執行耗時操作,如果執行耗時操作容易導致事件分發延遲。
onEventMainThread:
使用onEventMainThread,那麼不論事件是在哪個線程中發布出來的,onEventMainThread都會在UI線程中執行,接收事件就會在UI線程中運行,這個在Android中是非常有用的,因為在Android中只能在UI線程中跟新UI,所以在onEvnetMainThread方法中是不能執行耗時操作的。
onEventBackground:
使用onEventBackgrond,那麼如果事件是在UI線程中發布出來的,那麼onEventBackground就會在子線程中運行,如果事件本來就是子線程中發布出來的,那麼onEventBackground函數直接在該子線程中執行。
onEventAsync:
使用onEventAsync,那麼無論事件在哪個線程發布,都會創建新的子線程在執行onEventAsync.
2、如果有多個地方發送消息,並有多個消息處理函式,要如何確定哪個處理方法負責處理哪些消息呢?
關鍵就在於這四個消息處理方法的參數。發送消息的參數是某一個類,接收端也必須是同一個類,否則便接收不到。若有多個 onEvent() 方法參數相同,那麼這些方法都能接收到消息。
------------------------------------------------------------------
總結:
register(註冊)會把當前類中匹配的方法(以 onEvent 開頭的)存入一個 Map,而 post 則會根據實參去 Map 中查找並透過反射呼叫。