天天看點

(broadcast,intent,intentfilter消息廣播)(interface接口,回調函數)(eventBus)差別,适用場合

項目中需要把activity裡的狀态傳遞到子fragment裡面,可以用回調函數,可以用消息廣播,調查了一番得出以下總結,三個方法:

1 broadcast發送廣播消息,消息用intent包裝,接收者注冊 intentfilter接收

         适用于系統相關消息,一般用在接收系統消息,網絡變化,電量變化;可以傳遞context, intent參數

2 編寫interface,制作回調函數

    一般使用步驟:消息發送者定義 interface接口

                                消息接收者注冊Listener,注冊回調函數

                                消息發送者通過注冊進來的Listener調用回調函數,實作資料傳遞,可以傳遞context,等任意參數

   由于使用了回調函數原理:是以資料傳遞實時性非常高,相當于直接調用,一般用在功能子產品上:

   比如:開發了一個藍牙資料收發子產品,就可以給這個子產品定義interface接口,資料接收者隻要注冊回調函數即可收的資料,

   同理,Android的按鍵點選事件就是通過回調函數來響應的,回調函數可以實時響應,可以在Android中遇到很多回調函數傳遞界面元素狀态的示例

3 使用eventBus開源事件釋出/訂閱架構

關于 eventBus 一共有兩個分别是:

1 .hehonghui/AndroidEventBus

這裡講hehonghui的 eventBus,其介紹說明原文為:

“這是一個Android平台的事件總線架構, 它簡化了Activity、Fragment、Service等元件之間的互動,很大程度上降低了它們之間的耦合,

使得我們的代碼更加簡潔,耦合性更低,提升我們的代碼品質。”

(broadcast,intent,intentfilter消息廣播)(interface接口,回調函數)(eventBus)差別,适用場合

應用官方文檔的插圖:官方位址為:

https://github.com/hehonghui/AndroidEventBus/blob/master/README-ch.md

2. greenrobot / EventBus

最後:greenrobot的eventbus現在出了3.0 版本了,使用效果也是相當不錯的,官方網站有詳細的文檔說明:

http://greenrobot.org/eventbus/documentation/

https://github.com/greenrobot/EventBus

(broadcast,intent,intentfilter消息廣播)(interface接口,回調函數)(eventBus)差別,适用場合

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适用于Activity,Fragment,等之間的通信。至于其他優勢可以閱讀官方文檔。

總結來說,eventbus适用于消息傳遞,畢竟是消息總線,官方文檔并未提及,資料傳輸效率,但肯定的是對于一般消息傳遞是沒有問題的。

由以上分析,我的項目中适合使用EventBus類型的消息傳遞機制,可以從以上兩個架構選擇一個來使用。

最後決定使用greenrobot 的 eventBus, 在Android studio 裡面 加入,

compile 'org.greenrobot:eventbus:3.0.0'      

沒有效果,添加依賴失敗,沒有一點反應,後來看stackoverflow 說,在allprojects的repositories下面加入 “mavenCentral()”

先開始也是沒有效果,後來,重新開機了Android,然後就可以了,之前好多遍rebuild都不管用