Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
HomeF.A.Q.
Community
Writing Recipes
Login
Android's Application Object as a "Singleton"
Contributed by Adrian Cowham 2011-04-13 12:29:31 (updated 2013-05-29 02:13:07)
In Published Edition? Yes
2
Votes
Problem

In the all too common case when you need to access "global" data from within your Android app, the best solution is to to use subclass android.app.Application and treat it as a Singleton with static accessors.

Solution

Every Android app is guaranteed to have exactly one android.app.Application instance for the lifetime of the app. If you choose to subclass android.app.Application, Android will create an instance of your class and invoke the android.app.Application life cycle methods on it. Because there's nothing preventing you from creating another instance of your subclassed android.app.Application, it isn't a genuine Singleton, but it's close enough.

Having objects such as Session Handlers, Web Service Gateways, or anything that your application only needs a single instance of, globally accessible will dramatically simplify your code. Sometimes these objects can be implemented as singletons, and sometimes they cannot because they require a Context instance for proper initialization. In either case, it's still valuable to add static accessors to your subclassed android.app.Application instance so that you consolidate all globally accessible data in one place, have guaranteed access to a Context instance, and easily write "correct" singleton code without having to worry about synchronization.

Discussion

When writing your Android app you may find it necessary to share data and services across multiple Activities. For example, if your app has session data, such as the currently logged in user, you will likely want to expose this information. When developing on the Android platform, the pattern for solving this problem is to have your android.app.Application instance own all global data, and then treat your Application instance as a Singleton with static accessors to the various data and services.

When writing an Android app, you're guaranteed to only have one instance of the android.app.Application class so it's safe ( and recommended by the Google Android team ) to treat it as a Singleton. That is, you can safely add a static getInstance() method to your Application implementation. Below is an example.

public class AndroidApplication extends Application {

    private static AndroidApplication sInstance;

    private SessionHandler sessionHandler;

    public static AndroidApplication getInstance() {
      return sInstance;
    }

    public SessionHandler getSessionHandler()
        return sessionHandler;
    }

    @Override
    public void onCreate() {
      super.onCreate();  
      sInstance = this;
      sInstance.initializeInstance();
    }

    protected void initializeInstance() {
        // do all your initialization here
        sessionHandler = new SessionHandler( 
            this.getSharedPreferences( "PREFS_PRIVATE", Context.MODE_PRIVATE ) );
    }
}

This isn't the classical Singleton implementation but given the constraints of the Android framework, this is the closest thing we have, it's safe, and it works.

Using this technique in my app has simplified and cleaned up our implementation. Also, it has made developing tests much easier. Using this technique in conjunction with the 4447 Robolectric testing framework, mock out our entire execution environment in a straight forward fashion.

Also, don't forget to add the application declaration to your AndroidManifest.xml file.

<application android:icon="@drawable/app_icon" 
  android:label="@string/app_name"  
  android:name="com.company.abc.AbcApplication">
Comments (0)
Leave a comment
Edit History (12)
There are no (moderator-approved) comments on this recipe yet.