Thursday, March 10, 2011

Android's Application Object as a "Singleton"

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.

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;

    public static AndroidApplication getInstance() {
      return sInstance;
    }

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

    protected void initializeInstance() {
      // do all you initialization here
    }
}

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

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

3 comments:

Dragos said...

Hey, in your example http://androidcookbook.com/Recipe.seam?recipeId=1218 there's a SesshionHandler class.

Can you explain a bit what it does?
Perhaps, provide some code?

Thanks!

Anonymous said...

Thank you for ѕome οtheг informаtiѵe sitе.
The plаce else cоuld I am gеtting that tуpе of іnfo ωrittеn in ѕuch an ideal means?
I have a unԁеrtaking that I'm simply now working on, and I've been
at the look οut for suсh info.

My blog; minik kız

Rob Lewis said...

Great tip! Just to make it completely idiot-proof, how about naming the method "getSoleInstance" instead of "getInstance"? The latter name kind of makes it seem like this is a factory method.