原文地址http://blog.magicer.xyz/2017/01/android-eventbus3-basic/
EventBus
是http://greenrobot.org/
出的一个发布者/订阅者
(Publisher/Subscriber
)的事件总线。主要是用来在Android
各个组件之间进行消息传递的。能够很好地对发布者和订阅者之间进行解耦。
下图是官方给出的一个示意图:
在项目的build.gradle
文件中添加如下依赖:
compile 'org.greenrobot:eventbus:3.0.0'
我们使用EventBus发布消息的时候很方便,只需要一句话就可以。如下:
EventBus.getDefault().post("hello");
在这里我们发布的可以是基本数据类型,可以是字符串,也可以是对象。
当我们需要在一个Activity
或者Fragment
中订阅事件时。我们需要注册EventBus
EventBus.getDefault().register(this);
当我们注册了EventBus
之后我们就需要取消注册。一般在Activity
或Fragment
销毁的时候注销。注销的代码如下:
EventBus.getDefault().unregister(this);
当我们注册了EventBus
之后。我们就需要写一个方法。来对事件进行处理。如下:
@Subscribe
public void test(String strging){
Log.i("temp","printf "+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
可以随意,这里只是用来表明语义。
在上面的例子中,我们并没有制定@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("subscriber","subscriber "+string);
}
在某些情况下,我们不想让事件被继续分发了。那么我们就可以在onEvent
(这里的onEvent名称任意)中取消事件:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(String string){
Log.i("subscriber","subscriber "+string);
EventBus.getDefault().cancelEventDelivery(exitApp);
}
这里参考官方文档中的代码:点我进入官方文档ProGuard部分
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe ;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
(java.lang.Throwable);
}
在这里我推荐个Android Studio
的插件:EventBus Intellij Plugin。
该插件会在代码的左侧显示一个Android机器人的图标,点击该图标能够列出所有的Subscriber
事件和Publisher
官方文档
源码地址:Github
EventBus JavaDoc
/**
* 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
}