Overriding the Application Lifecycle Events in Android

The Application class provides event handlers for application creation and termination, low memory conditions, and configuration changes

By overriding these methods, you can implement your own application-specific behavior for each of these circumstances:

onCreate — Called when the application is created. Override this method to initialize your application singleton and create and initialize any application state variables or shared resources

onLowMemory — Provides an opportunity for well-behaved applications to free additional memory when the system is running low on resources. This will generally only be called when background processes have already been terminated and the current foreground applications are still low on memory. Override this handler to clear caches or release unnecessary resources

onTrimMemory — An application specific alternative to the onLowMemory handler introduced in Android 4.0 (API level 13). Called when the run time determines that the current application should attempt to trim its memory overhead – typically when it moves to the background. It includes a level parameter that provides the context around the request.

onConfigurationChanged — Unlike Activities Application objects are not restarted due to configuration changes. If your application uses values dependent on specific configurations, override this handler to reload those values and otherwise handle configuration changes at an application level

Overriding the Application Lifecycle Handlers

public class MyApplication extends Application {
 private static MyApplication singleton;
 // Returns the application instance
 public static MyApplication getInstance() {
 return singleton;
 }
 @Override
 public final void onCreate() {
 super.onCreate();
 singleton = this;
 }
 @Override
 public final void onLowMemory() {
 super.onLowMemory();
 }
 @Override
 public final void onTrimMemory(int level) {
 super.onTrimMemory(level);
 }
 @Override
 public final void onConfigurationChanged(Configuration newConfig) {
 super.onConfigurationChanged(newConfig);
 }
}

Leave a Comment