美文网首页
EventBus 3 for Android

EventBus 3 for Android

作者: xyxzfj | 来源:发表于2017-02-13 20:21 被阅读78次

    一、简介

    官方介绍

    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 DiagramEventBus 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));
    

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

    相关文章

      网友评论

          本文标题:EventBus 3 for Android

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