EventBus 2.x升級到3.0使用注意

由于項目處于進行中,采用Android Studio升級也很簡單就升級了。但是升級后原先運行良好的程序,出現頁面刷新異常,log出現以下異常:

Could not dispatch event: class com.powerstick.beaglepro.event.StatusEvent to subscribing class ……
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
…………………………
at org.greenrobot.eventbus.EventBus.postSingleEvent(EventBus.java:370)
at org.greenrobot.eventbus.EventBus.post(EventBus.java:251)
…………………………
No subscribers registered for event class org.greenrobot.eventbus.SubscriberExceptionEvent

簡而言之就是涉及到UI操作必須要再主UI線程,而在EventBus2.x時,直接在onEventMainThread方法內就可以執行UI操作,到3.0時必須要在方法上加上@Subscribe(threadMode = ThreadMode.MAIN),ThreadMode還提供了其他幾種Mode,視情況而定。
  另外值得注意的就是,原先的onEventMainThread等固定命名方法,在3.0下可以由用戶任意定義,只需在方法上加上對應的注解@Subscrib,即,你可以寫成下面的樣子:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventXXX(StatusEvent event) {
  String action = event.getAction();
  String mac = event.getMac();
  // xxxxxxxxxxxxxxx
}

Over.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容