0
点赞
收藏
分享

微信扫一扫

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

爱写作的小土豆 2021-09-29 阅读 46

EventBus

​ 传统的事件传递方式包括: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);
        }

接收消息的方法

@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用法全解析

举报

相关推荐

0 条评论