原文地址: http://blog.magicer.xyz/2017/...

简介

EventBushttp://greenrobot.org/出的一个发布者/订阅者Publisher/Subscriber)的事件总线。主要是用来在Android各个组件之间进行消息传递的。能够很好地对发布者和订阅者之间进行解耦。

下图是官方给出的一个示意图:
官方描述

集成

在项目的build.gradle文件中添加如下依赖:

compile 'org.greenrobot:eventbus:3.0.0'

使用

发布者Publisher

我们使用EventBus发布消息的时候很方便,只需要一句话就可以。如下:

 EventBus.getDefault().post("hello");

在这里我们发布的可以是基本数据类型,可以是字符串,也可以是对象。

订阅者Subscriber

当我们需要在一个Activity或者Fragment中订阅事件时。我们需要注册EventBus

 EventBus.getDefault().register(this);

当我们注册了EventBus之后我们就需要取消注册。一般在ActivityFragment销毁的时候注销。注销的代码如下:

EventBus.getDefault().unregister(this);

@Subscriber

当我们注册了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可以随意,这里只是用来表明语义。

@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("subscriber","subscriber "+string);
    }

取消事件分发

在某些情况下,我们不想让事件被继续分发了。那么我们就可以在onEvent(这里的onEvent名称任意)中取消事件:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String string){
        Log.i("subscriber","subscriber "+string);
        EventBus.getDefault().cancelEventDelivery(exitApp);
    }

ProGuard

这里参考官方文档中的代码:点我进入官方文档ProGuard部分

-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
 
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

Android Studio插件

在这里我推荐个Android Studio的插件:EventBus Intellij Plugin
该插件会在代码的左侧显示一个Android机器人的图标,点击该图标能够列出所有的Subscriber事件和Publisher
EventBus Intellij Plugin

参考

官方文档
源码地址: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
}

Magicer
246 声望11 粉丝

[链接]