org.greenrobot.eventbus.EventBusException: Subscriber class already registered to event class

org.greenrobot.eventbus.EventBusException: Subscriber class com.hj.eventbus.Activity2 already registered to event class com.hj.eventbus.BtnEvent

直譯: EventBus異常:Activity2已經註冊過EventBus。
相關代碼:

 class Activity2
 {

    @Override
    public void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    ......
    onClick()//點擊按鈕啓動Activity3,從Activity3返回Activity2時出現異常
    {
        startActivity(new Intent(Activity2.this, Activity3.class));
    }
    ......

 }

原因: Activity2創建時會調用onStart方法註冊eventbus,Activity3返回Activity2時會再次調用onStart方法,此時會重複註冊報異常。
解決方案 一:(省事的方法)

  if (!EventBus.getDefault().isRegistered(this)) 
    {
      EventBus.getDefault().register(this);
    }

解決方案 二:改變註冊與反註冊eventbus的位置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章