Your application’s Application object remains instantiated whenever your application runs. Unlike Activities, the Application is not restarted as a result of configuration changes. Extending the Application class with your own implementation enables you to do three things:
- Respond to application level events broadcast by the Android run time such as low memory conditions
- Transfer objects between application components.
- Manage and maintain resources used by several application components
Of these, the latter two can be better achieved using a separate singleton class. When your Application implementation is registered in the manifest, it will be instantiated when your application process is created. As a result, your Application implementation is by nature a singleton and should be implemented as such to provide access to its methods and member variables.
Extending and Using the Application Class
import android.app.Application;
import android.content.res.Configuration;
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;
}
}
When created, you must register your new Application class in the manifest’s application node using a name attribute
<application android:icon=”@drawable/icon”
android:name=”.MyApplication”>
[... Manifest nodes ...]
</application>
Your Application implementation will be instantiated when your application is started. Create new state variables and global resources for access from within the application components:
MyObject value = MyApplication.getInstance().getGlobalStateValue();
MyApplication.getInstance().setGlobalStateValue(myObjectValue);