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:
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!
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
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.
Post a Comment