Which Activity lifecycle methods are best to register/unregister to event bus?

后端 未结 4 1277
迷失自我
迷失自我 2021-02-07 00:00

What is the best place to register and unregister to an event bus (like otto, EventBus, or tinybus) in an Activity and why?

  1. onCre
4条回答
  •  -上瘾入骨i
    2021-02-07 00:28

    Form EventBus Documentation that I found and it's works fine for me:

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

    And if you need to send the EventBus reference to the child then:

    private EventBus eventBus = EventBus.getDefault();
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            .......
    }
    
    @Override
    public void onStart() {
        super.onStart();
        if(!eventBus.isRegistered(this)){
            eventBus.register(this);
        }else{
            Log.e(TAG, "EventBus is registered");
        }
    }
    
    @Override
    public void onStop() {
        super.onStop();
        if(eventBus.isRegistered(this)){
           eventBus.unregister(this);
        }else{
           Log.e(TAG, "EventBus is not registered");
        }
    }
    

提交回复
热议问题