EventBus 3 for Android

一、简介

官方介绍

EventBus: Events for Android

EventBus is an open-source library for Android using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.

EventBus Diagram
EventBus Diagram

为应用程序中的各个组件(Activity, Fragment, Service等)提供了一个共享消息总线。

它们都可以注册接入消息总线,从而接收广播的消息,也可以往总线发消息。

二、上手

官方教程

1)Add EventBus as a dependency to your module.

compile 'org.greenrobot:eventbus:3.0.0'

2)Register Activity or Fragment to the event bus between onStart and onStop.

 @Override
 protected void onStart() {
      super.onStart();

      EventBus.getDefault().register(this);
 }

 @Override
 protected void onStop() {
      EventBus.getDefault().unregister(this);

      super.onStop();
 }

3)Define an Event class.

public class MessageEvent {
    private final String message;

    MessageEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

4)Add event listener functions with annotation @Subscribe .

 @Subscribe(threadMode = ThreadMode.MAIN)
 public void onMessageEvent(MessageEvent event) {
      Log.d(TAG, "onMessageEvent " + event.getMessage());
      textView.setText(TAG + " " + event.getMessage());
 }

 @Subscribe
 public void onYAMessageEvent(MessageEvent event) {
      Log.d(TAG, "onYAMessageEvent " + event.getMessage());
 }

5)Post event from anywhere.

EventBus.getDefault().post(new MessageEvent(message));

详见官方文档。有问题欢迎回帖交流。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,751评论 25 709
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,591评论 2 45
  • 秋日的阳光 ,倾洒在阳台上 ,伫立,任那温热的光覆盖脸庞, 想象家乡冬日的暖阳 , 让人慵懒倦怠。 灰色的深圳 深...
    逝我阅读 772评论 8 7
  • 静谧的午夜没有华灯初上的妖娆与生动,亦没有喧嚣的汽笛声助眠,只有静静的音乐,一本略有些陈旧的《三毛文集》,就这样打...
    小蚂蚁的自留地阅读 1,365评论 0 16
  • 暮春拾趣上优山,叠翠茶畦接远川。 嘉木发陈枝吐嫩,竹萌崭露角呈尖。 芬芳多向闲暇舞,心绪偏将孤寂添。 时日好催风物...
    知一先生阅读 398评论 0 3