Search code examples
androidandroid-activitylistenerlifecycle

Which lifecycle event is best to register/unregister listeners?


I have manager classes that take an activity as a listener. I use the managers to do threaded calls, work etc and then call back to the listener(activity) when things are done, need changed and so on.

I want to register and unregister the activity as a listener when it is no longer visible. This will prevent unwanted changes from happening (like dialogs appearing when the activity is no longer visible).

My question is, what lifecycle events are best to do this registering. I started with onPause() and onResume() which worked well except when I had an activity that was doing stuff in onActivityResult(). Since onActivityResult() gets called before onResume() my managers are not always registered in time.

Do I need to register in onResume() AND onActivityResult() or is there a better way to approach this?


Solution

  • An alternative approach may be to postpone the processing currently done in onActivityResult() until after the listeners are registered in onResume().

    Possible ways of doing this include posting to the message queue, e.g. using a Handler, setting a Runnable object to be called by onResume, or simply storing the result data received by onActivityResult().

    This would also ensure that the activity really has come to the foreground when the listener methods are called.