美文网首页开源库
Android EventBus详解以及使用(页面间的传值操作)

Android EventBus详解以及使用(页面间的传值操作)

作者: KingWorld | 来源:发表于2020-11-07 17:18 被阅读0次

    EventBus

    EventBus是一个Android事件发布/订阅框架,通过解耦发布者和订阅者简化Android事件传递,这里的事件可以理解为消息。事件传递既可以用于Android四大组件间通讯,也可以用于异步线程和主线程间通讯等。

    ​ 传统的事件传递方式包括:Handler、BroadcastReceiver、Interface回调,相比之下EventBus的有点是代码简洁,使用简单,并将事件发布和 订阅充分解耦。

    build.gradle添加依赖:

    implementation 'org.greenrobot:eventbus:3.2.0'
    

    或者用Maven:

    <dependency>
        <groupId>org.greenrobot</groupId>
        <artifactId>eventbus</artifactId>
        <version>3.2.0</version>
    </dependency>
    

    R8, ProGuard

    If your project uses R8 or ProGuard add the following rules:

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

    基本使用
    自定义一个事件类

    public class ReturnPayResult {
        private String status;
        public ReturnPayResult(String status) {
            this.status = status;
        }
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
    }
    

    初始化的时候在要接受消息的页面注册比如onCreate方法

    if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
    

    EventBus的四种ThreadMode(线程模型)

    EventBus3.0有以下四种ThreadMode

    POSTING(默认):如果使用事件处理函数指定了线程模型为POSTING,那么该事件在哪个线程发布出来的,事件处理函数就会在这个线程中运行,也就是说发布事件和接收事件在同一个线程。在线程模型为POSTING的事件处理函数中尽量避免执行耗时操作,因为它会阻塞事件的传递,甚至有可能会引起ANR。
    MAIN: 事件的处理会在UI线程中执行。事件处理时间不能太长,长了会ANR的。
    BACKGROUND:如果事件是在UI线程中发布出来的,那么该事件处理函数就会在新的线程中运行,如果事件本来就是子线程中发布出来的,那么该事件处理函数直接在发布事件的线程中执行。在此事件处理函数中禁止进行UI更新操作。
    ASYNC:无论事件在哪个线程发布,该事件处理函数都会在新建的子线程中执行,同样,此事件处理函数中禁止进行UI更新操作。

    接收消息的方法

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ReturnPayResult result) { 
        //接收以及处理数据
    
       if (event != null) {
             //处理数据
        }
    };
    

    发送消息

    String status = "";
    EventBus.getDefault().post(new ReturnPayResult(status));
    

    取消注册

    @Override
        public void onDestroy() {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
            super.onDestroy();
        }
    

    参考:Android EventBus3.0用法全解析

    相关文章

      网友评论

        本文标题:Android EventBus详解以及使用(页面间的传值操作)

        本文链接:https://www.haomeiwen.com/subject/eucqbktx.html