- 首先安利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.