小菜今天自己写测试 Demo 时,需要用到 EventBus,目前集成 3.1.1 版本,集成的方式很简单,在某个 Fragment 实践应用中,却一直报入下错:
Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class com.roating.ace.frag.FragmentSign and its super classes have no public methods with the @Subscribe annotation
出问题就解决嘛,尝试如下:
- 检查 EventBus 集成是否添加混淆文件:
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
- 检查 Fragment 中 EventBus 的注册是否正确:
@Override
protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
EventBus.getDefault().register(this);
View view = inflater.inflate(R.layout.activity_sign, null);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getDefault().unregister(this);
}
- 检查接受 Event 的方法是否添加 @Subscribe:
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
void refreshSignTime(EventMessageK.SignStateME event) {
if (event != null) {
if (event.getType() == 1) {
mUpTv.setText(event.getTime());
} else {
mDownTv.setText(event.getTime());
}
}
}
乍一看应该没啥问题,但是每次都会报 its super classes have no public methods with the @Subscribe annotation,很尴尬,之后各种查网上大神解释,依然没注意问题所在,查看以前写的代码,突然醒悟,因为最近在学 Kotlin,方法定义的时候可以直接定义方法,经常省略方法权限 public/private/protected 等,意识到接收 Event 消息必须是 public 才可以,一个很简单等知识点却因为基础不扎实而浪费了很多时间,希望大家不会遇到小菜的问题。
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
fun checkLoginInfo(event: MessageEvent.LoginInfoME) {
loginPhone = event.phone
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void checkLoginInfo(MessageEvent.LoginInfoME event) {
loginPhone = event.phone
}
网友评论