getApplication() vs. getApplicationContext()

I couldn’t find a satisfying answer to this, so here we go: what’s the deal with Activity/Service.getApplication() and Context.getApplicationContext()?

In our application, both return the same object. In an ActivityTestCase however, mocking the application will make getApplication() come back with the mock, but getApplicationContext will still return a different context instance (one injected by Android). Is that a bug? Is it on purpose?

I don’t even understand the difference in the first place. Are there cases outside a test suite where both calls may come back with different objects? When and why? Moreover, why is getApplication defined on Activity and Service, but not on Context? Shouldn’t there always be a valid application instance available from anywhere?

4 Answers
4

Leave a Comment