EventBus的其余经常使用函数

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

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

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

首先,是github上的描述

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

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

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

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

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

EventBus…this

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.spa

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

关于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最大的缺点之一。

若是你喜欢个人博客 请关注我。

相关文章
相关标签/搜索