Hot questions for Using EventBus in android lifecycle

Top 10 Java Open Source / EventBus / android lifecycle

Question:

I'm brand new using Event Bus from otto lib, So far I created a Event Bus Singleton class, which I'm using in several parts of my code. Now I'm working on a fragment view, But I still have a question, regarding:

When is the best time to register/unregister my event bus?

In a couple of posts I read that onStart() and onStop(), but without any specific reason why.

public class SomeFragment extends Fragment {
  @Override
    public void onStart() {
        super.onStart();
        EventBusSingleton.register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBusSingleton.unregister(this);
    }
}

If I follow the same approach as in the activities doing the call onResume() and onPause() works fine as well.

public class SomeFragment extends Fragment {
  @Override
    public void onResume() {
        super.onResume();
        EventBusSingleton.register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBusSingleton.unregister(this);
    }
}

What could be the potential risk(if exist) from each call way?


Answer:

onPause()/onResume() is called when your activity does not have the focus anymore but could still be visible (think a dialog or alert on top of your activity).

onStop()/onStart() is called when your activity is not visible anymore.

Which one to use depends your use case. I believe it's not really a problem to have callbacks executed while in the paused state so I would just put the register/unregister in onStop()/onStart() but if you really want to make sure, you can put them in onPause()/onResume().

Question:

I'd like to show a full screen PIN request (e.g. a dedicated activity) when my Application is resumed. How can I achieve this? I'm thinking about creating a flag ASKING_PIN on Application context, specifically on Application resume lifecycle, then sending an event to all activities. The first one that catch that event, update the flag to TRUE and show the PIN request.

@Override
public void onActivityResumed(Activity activity) {
    // POST PIN event on EventBus
}

Will this work as expected? Any other possible solutions? Important note: when the user dismiss the PIN activity should be able to see the latest activity that was interacting with. Many thanks in advance.


Answer:

Create one BaseActivity, and have every other activity inherit from that one. On the BaseActivity's onResume add your condition for launching the PIN lock, and if that's satisfied, launch your PinLockActivity.