Android中EventBus3.0的使用

原文地址http://blog.magicer.xyz/2017/01/android-eventbus3-basic/

简介

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

参考

官方文档
源码地址: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
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EventBus是一种用于Android应用程序发布/订阅事件的库。它遵循发布-订阅模式,允许不同组件之间进行松散耦合的通信。 在基于EventBus 3.0的APP开发,你可以按照以下步骤进行: 1. 添加EventBus依赖 在项目的build.gradle文件添加以下代码: ``` dependencies { implementation 'org.greenrobot:eventbus:3.2.0' } ``` 2. 创建事件类 创建一个事件类,它将包含你需要发送和接收的数据。例如: ``` public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } } ``` 3. 注册订阅者 在需要接收事件的组件,注册订阅者。例如,在Activity: ``` @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } ``` 4. 发布事件 在需要发送事件的组件,发布事件。例如,在Activity: ``` EventBus.getDefault().post(new MessageEvent("Hello, world!")); ``` 5. 处理事件 在订阅者,创建一个方法来处理接收到的事件。例如,在Activity: ``` @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { // Do something with the event Toast.makeText(this, event.message, Toast.LENGTH_SHORT).show(); } ``` 以上就是基于EventBus 3.0的APP开发的基本步骤。通过使用EventBus,你可以轻松地在不同组件之间传递数据,从而实现应用程序的松散耦合通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值