EventBus的其他常用函数

上一篇EventBus最简易使用方式介绍了EventBus最简易的使用方式,摆脱了叽里呱啦+图片的长篇大论。目的是为了让刚开始接触的人们不晕头转向。那么这篇。。我也要开始图片+叽里呱啦了。

转载请注明出处:http://blog.csdn.net/wingichoy/article/details/50628011

怎么才能了解EventBus呢。。当然是直接看github上的README了。

首先,是github上的描述

Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

意思为:安卓平台上一个用于Activity,Fragment,Thread,Service被优化简化的通讯协议。 加量不加价(少代码,高质量)!

这个…… 呃~~ -__-” 说的很明白了。

  • 再来看readme
    发现一张图片:
    这里写图片描述

描述了发布者和订阅者的关系。即:一个发布者 发布事件到总线,总线分发给订阅者。

EventBus…

simplifies the communication between components
decouples event senders and receivers
performs well with Activities, Fragments, and background threads
avoids complex and error-prone dependencies and life cycle issues
makes your code simpler
is fast
is tiny (<50k jar)
is proven in practice by apps with 100,000,000+ installs
has advanced features like delivery threads, subscriber priorities, etc.

妈蛋,最讨厌看英文了,反正叽里呱啦一大堆,用我们博大精深的中文来概括就是:EventBus:短、小、快!

关于EventBus的方法

  • 注册和注销这里就不说了,这里首先说说他的post方法

昨天我给出的使用示例是:

 EventBus.getDefault().post("hello Eventbus");

其实我们可以自己定制消息类型,如

public class MessageEvent {
    public final String message;

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

然后将它发送出去:

  EventBus.getDefault().post(new MessageEvent("Hello everyone!"));

其实和handler很像了有木有~~ 有了这样定制消息的功能,我们就可以个性化消息,来对消息进行分类啊等等工作。

PostThread

是说该方法将会在同一个线程来调用,避免了线程之间的切换,比如你是在主线程发送的消息,那么将会运行在主线程,如果为其他线程,那么将在其他线程调用。

// 在相同线程里调用 (默认)
    public void onEvent(MessageEvent event) {
        log(event.message);
    }

MainThread

将会在主线程调用,如果本身就在主线程,将直接调用

// 在主线程(UI线程)调用
    public void onEventMainThread(MessageEvent event) {
        //进行UI操作
        textField.setText(event.message);
    }

BackgroundThread

将会在工作线程(后台线程)调用

  // 在后台线程调用
    public void onEventBackgroundThread(MessageEvent event){
        //进行耗时操作
        saveToDisk(event.message);
    }

额。。关于EventBus的常用函数就是这些了。 EventBus的优点到底是什么? 我觉得就是短小快吧 哈哈哈啊哈哈哈哈哈

关于EventBus的缺点

因为他是通过反射来获取方法名的。所以如果方法被混淆的话。。就不会起作用了。。这是EventBus最大的缺点之一。

如果你喜欢我的博客 请关注我。

posted on 2016-02-03 10:51  木鱼哥  阅读(153)  评论(0编辑  收藏  举报

导航