1. 程式人生 > >EventBus 3.0的用法詳解

EventBus 3.0的用法詳解

基本用法

註冊

  舉個例子,你需要在一個activity中註冊eventbus事件,然後定義接收方法,這和Android的廣播機制很像,你需要首先註冊廣播,然後需要編寫內部類,實現接收廣播,然後操作UI,在EventBus中,你同樣需要這麼做。

@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EventBus.getDefault().register
(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }
訂閱者

類似廣播,但是有別於2.4版本,你不必再去約定OnEvent方法開頭了(看不懂沒關係):

@Subscribe(threadMode = ThreadMode.MainThread)
public void helloEventBus(String message) { 
    mText.setText(message);
}

  該操作很簡單,定義了一個hello方法,需要傳入String引數,在其中操作UI操作,注意:我們添加了註解@Subscribe,其含義為訂閱者,在其內傳入了threadMode,我們定義為ThreadMode.MainThread,其含義為該方法在UI執行緒完成,這樣你就不要擔心丟擲異常啦。是不是很簡單?

釋出者

既然你在某個地方訂閱了內容,當然就會在某個地方釋出訊息。舉個例子,你的這個activity需要http請求,而http請求你肯定是在非同步執行緒中操作,其返回結果後,你可以這麼寫:

String json="";
EventBus.getDefault().post(json);

這樣就OK了,你可以試下能否正常運行了!

原理初探

  你訂閱了內容,所以你需要在該類註冊EventBus,而你訂閱的方法需要傳入String,即你的接收資訊為String型別,那麼在post的時候,你post出去的也應該是String型別,其才會接收到訊息。

如果你post的是物件,首先你需要定義一個類似pojo類:

public class MessageEvent { 
    public final String name; 
    public final String password; 
    public MessageEvent(String name,String password) { 
        this.name = name; this.password=password; 
    }
}

然後你post的時候:

EventBus.getDefault().post(new MessageEvent("hello","world"));

當然,你接收的方法也需要改為:

@Subscribe(threadMode = ThreadMode.MainThread)
public void helloEventBus(MessageEvent message) { 
    mText.setText(message.name);
}