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

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

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方法內(nèi)就可以執(zhí)行UI操作,到3.0時必須要在方法上加上@Subscribe(threadMode = ThreadMode.MAIN),ThreadMode還提供了其他幾種Mode,視情況而定。
  另外值得注意的就是,原先的onEventMainThread等固定命名方法,在3.0下可以由用戶任意定義,只需在方法上加上對應(yīng)的注解@Subscrib,即,你可以寫成下面的樣子:

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

Over.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容