- 首先安利EventBus:https://github.com/greenrobot/EventBus
由于項目處于進行中,采用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.