Search code examples
androidandroid-activityondestroyeventhandler

Registering "onDestroy event handler" with Android Activity


Let's say I have a library object which needs to be notified of an Activity.onDestroy() event if it happens. Is there a way that I can register some sort of handler with the Activity from inside the library or will I need to require anyone using the library to override onDestroy() and pass it on to the library (very bug-prone as there is no way to enforce this at compile-time)?


Solution

  • You can make your library class implement Application.ActivityLifecycleCallbacks and then register it using getApplication().registerActivityLifecycleCallbacks(libraryClass);

    Then your library class will receive all activity lifecycle callbacks from your application. If you're only looking for one activity's lifecycle events, the ActivityLifeCycleCallbacks methods have Activity parameters and you can filter for the activity you're looking for.