eventbus报错:org.greenrobot.eventbus.EventBusException: Subscriber class ... its super classes have no

报错信息

2019-05-31 09:15:34.049 2580-2580/com.cxyzy.note E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.cxyzy.note, PID: 2580
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cxyzy.note/com.cxyzy.note.ui.activity.MainActivity}: org.greenrobot.eventbus.EventBusException: Subscriber class com.cxyzy.note.ui.activity.MainActivity and its super classes have no public methods with the @Subscribe annotation
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class com.cxyzy.note.ui.activity.MainActivity and its super classes have no public methods with the @Subscribe annotation
        at org.greenrobot.eventbus.SubscriberMethodFinder.findSubscriberMethods(SubscriberMethodFinder.java:67)
        at org.greenrobot.eventbus.EventBus.register(EventBus.java:140)
        at com.cxyzy.note.ui.base.BaseActivity.onCreate(BaseActivity.kt:22)
        at android.app.Activity.performCreate(Activity.java:6975)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)

背景

我在BaseActivity里注册了eventbus,但是并不是所有的activity都会使用eventbus.

分析

问题点就处在上面的背景里. 只有使用eventbus的activity或fragment才能在初始化的时候注册eventbus,否则就会报上面的错误.

解决方案

在BaseActivity通过开关控制eventbus的注册,默认关闭. 子类中需要用eventbus的就打开此开关,并设置接收函数.
样例:

  • BaseActivity
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (isRegisterEventBus()) {
        EventBus.getDefault().register(this)
    }
}
protected open fun isRegisterEventBus(): Boolean {
    return false
}
  • MainActivity
override fun isRegisterEventBus(): Boolean {
    return true
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(event: BaseEvent) {
    if (event is RefreshEvent) {
        refreshUI()
    }
}

关注头条号,第一时间获取最新文章:

你可能感兴趣的:(安卓)