Android - EventBus-简单使用

2018-06-15  本文已影响0人  Lisiony

EventBus 通过发布/订阅的方式进行消息传递。主要功能是替代 Intent、Handler、BroadCast 在 Fragment、Activity、Service、线程之间传递消息。

使用方法:(跟广播的使用有点相似)

 compile 'org.greenrobot:eventbus:3.0.0'
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
public class MessageEvent {
    private String name;
    private String sex;

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public MessageEvent(){

    }

    public MessageEvent(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }
}
   MessageEvent messageEvent = new MessageEvent();
   messageEvent.setName("lisheny");
   messageEvent.setSex("boy");
   EventBus.getDefault().post(messageEvent);
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final MessageEvent event){
        textView.setText(event.getName()+","+event.getSex());
    }
-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);
}
特别的:四种 threadMode:

官网:https://github.com/greenrobot/EventBus
上面代码Demo:https://github.com/lisheny/EventBusTest

上一篇下一篇

猜你喜欢

热点阅读