getApplicationContext() is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext() when you know why you are using getApplicationContext() and only when you need to use getApplicationContext().
To be blunt, “some programmers” use getApplicationContext() (or getBaseContext(), to a lesser extent) because their Java experience is limited. They implement an inner class (e.g., an OnClickListener for a Button in an Activity) and need a Context. Rather than using MyActivity.this to get at the outer class’ this, they use getApplicationContext() or getBaseContext() to get a Context object.
You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal. Scenarios include:
-
Use
getApplicationContext()if you need something tied to aContextthat itself will have global scope. I usegetApplicationContext(), for example, inWakefulIntentService, for the staticWakeLockto be used for the service. Since thatWakeLockis static, and I need aContextto get atPowerManagerto create it, it is safest to usegetApplicationContext(). -
Use
getApplicationContext()when you bind to aServicefrom anActivity, if you wish to pass theServiceConnection(i.e., the handle to the binding) betweenActivityinstances viaonRetainNonConfigurationInstance(). Android internally tracks bindings via theseServiceConnectionsand holds references to theContextsthat create the bindings. If you bind from theActivity, then the newActivityinstance will have a reference to theServiceConnectionwhich has an implicit reference to the oldActivity, and the oldActivitycannot be garbage collected.
Some developers use custom subclasses of Application for their own global data, which they retrieve via getApplicationContext(). That’s certainly possible. I prefer static data members, if for no other reason than you can only have one custom Application object. I built one app using a custom Application object and found it to be painful. Ms. Hackborn also agrees with this position.
Here are reasons why not to use getApplicationContext() wherever you go:
-
It’s not a complete
Context, supporting everything thatActivitydoes. Various things you will try to do with thisContextwill fail, mostly related to the GUI. -
It can create memory leaks, if the
ContextfromgetApplicationContext()holds onto something created by your calls on it that you don’t clean up. With anActivity, if it holds onto something, once theActivitygets garbage collected, everything else flushes out too. TheApplicationobject remains for the lifetime of your process.