Overriding the Application Life Cycle Events

The Application class also provides event handlers for application creation and termination, low available memory, and configuration changes (as described in the previous section).

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.

> onTerminate Can be called when the application object is terminated. Note that there is no guarantee of this method handler's being called. If the application is terminated by the kernel in order to free resources for other applications, the process will be terminated without warning and without a call to the application object's onTerminate handler.

> 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.

> onConfigurationChanged Unlike with Activities, your application object is not killed and restarted for configuration changes. Override this handler if it is necessary to handle configuration changes at an application level.

As shown in Listing 3-8, you must always call through to the superclass event handlers when overriding these methods.

LISTING 3-8: Overriding the application life cycle handlers Available for download on public class MyApplication extends Application { Wrax.com 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 onTerminate() { super.onTerminate();

@Override public final void onLowMemory() { super.onLowMemory();

@Override public final void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig);

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment