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最大的缺點之一。

若是你喜歡個人博客 請關注我。

相關文章
相關標籤/搜索