簡介
EventBus
是 http://greenrobot.org/
出的一個 發布者/訂閱者
( Publisher/Subscriber
)的事件總線。主要是用來在 Android
各個組件之間進行消息傳遞的。能夠很好地對發布者和訂閱者之間進行解耦。
下圖是官方給出的一個示意圖:
集成
在項目的 build.gradle
文件中添加如下依賴:
compile 'org.greenrobot:eventbus:3.0.0'
使用
發布者Publisher
我們使用EventBus發布消息的時候很方便,只需要一句話就可以。如下:
EventBus.getDefault().post(quot;helloquot;);
在這里我們發布的可以是基本數據類型,可以是字符串,也可以是對象。
訂閱者Subscriber
當我們需要在一個 Activity
或者 Fragment
中訂閱事件時。我們需要注冊 EventBus
EventBus.getDefault().register(this);
當我們注冊了 EventBus
之后我們就需要取消注冊。一般在 Activity
或 Fragment
銷毀的時候注銷。注銷的代碼如下:
EventBus.getDefault().unregister(this);
@Subscriber
當我們注冊了 EventBus
之后。我們就需要寫一個方法。來對事件進行處理。如下:
@Subscribe public void test(String strging){ Log.i(quot;tempquot;,quot;printf quot; string); }
在這里。 EventBus
沒有對函數的命進行規定。只需要加上注解 @Subscribe
,方法為 public void
即可。只要方法的參數跟 post
時的類型一致即可接受到改事件。
實例
比如說現在我們有個需求是。點擊一個按鈕就退出應用程序。那么我們使用EventBus可以怎么實現呢?
首先。我們可以在 BaseActivity
中注冊退出應用程序的時間,讓其他的 Activity
都集成該類。
public class BaseActvity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } @Subscribe public void exitApp(ExitApp exitApp){ finish(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
這時候我們只需要在按鈕的點擊時間中發送改消息即可了。
EventBus.getDefault().post(new ExistApp());
事件類 ExistApp
可以隨意,這里只是用來表明語義。
@Subscribe(threadMode = xxx)
@Subscriber
函數的線程。此時默認為:
ThreadMode.POSTING
ThreadMode
是一個枚舉類型。它的值有: POSTING
, MAIN
, BACKGROUND
, ASYNC
.源碼中的注釋寫的很詳細,見參考中 ThreadMode
的代碼。
簡單的說就是。
-
POSTING:
Subscriber在發布消息(調用post函數的線程)的線程中執行。 -
MAIN:
Subscriber將在Android主線程中執行。 -
BACKGROUND:
Subscriber在后臺線程中執行 -
ASYNC:
Subscriber在異步線程,也就是在獨立的線程中執行。
優先級
我們可以通過 @Subscribe(priority = 100)
指定一個Subscriber函數的優先級.默認的優先級是0。高優先級的Subscriber將會優先訂閱事件。
@Subscribe(priority = 100) public void onEvent(String string){ Log.i(quot;subscriberquot;,quot;subscriber quot; string); }
取消事件分發
在某些情況下,我們不想讓事件被繼續分發了。那么我們就可以在 onEvent
(這里的onEvent名稱任意)中取消事件:
@Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(String string){ Log.i(quot;subscriberquot;,quot;subscriber quot; string); EventBus.getDefault().cancelEventDelivery(exitApp); }
ProGuard
這里參考官方文檔中的代碼: 點我進入官方文檔ProGuard部分
-keepattributes *Annotation* -keepclassmembers class ** { @org.greenrobot.eventbus.Subscribe lt;methodsgt;; } -keep enum org.greenrobot.eventbus.ThreadMode { *; } # Only required if you use AsyncExecutor -keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent { lt;initgt;(java.lang.Throwable); }
Android Studio插件
在這里我推薦個 Android Studio
的插件: EventBus Intellij Plugin 。
Subscriber
事件和
Publisher
參考
/** * Each event handler method has a thread mode, which determines in which thread the method is to be called by EventBus. * EventBus takes care of threading independently from the posting thread. * * @see EventBus#register(Object) * @author Markus */ public enum ThreadMode { /** * Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery * implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for * simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread. */ POSTING, /** * Subscriber will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is * the main thread, event handler methods will be called directly. Event handlers using this mode must return * quickly to avoid blocking the main thread. */ MAIN, /** * Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single * background thread, that will deliver all its events sequentially. Event handlers using this mode should try to * return quickly to avoid blocking the background thread. */ BACKGROUND, /** * Event handler methods are called in a separate thread. This is always independent from the posting thread and the * main thread. Posting events never wait for event handler methods using this mode. Event handler methods should * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number * of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus * uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications. */ ASYNC }
Tags: EventBus
文章來源:https://segmentfault.com/a/1190000008097089