Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication()
and getApplicationContext()
return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext()
and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext()
exist in the first place ?
getApplication()
is only available in the Activity class and the Service class, whereas getApplicationContext()
is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext()
. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext()
delegates it's call to baseContext.getApplicationContext()
.
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass Application
. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context
which internally uses Context.getApplicationContext()
when
first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
Application
object in your app. – Christopher Orr