Context
Anti-Pattern: Using Application
Everywhere
We covered the Application
implementation of Context
earlier in the book. There, we saw that an Application
is a process-wide singleton, so we cannot somehow leak it by holding some reference to it. In effect, it is pre-leaked for us.
Some might wonder why we would ever need any other type of Context
. If we need Context
for so many things, and we have this one Context
that is available all the time… why not use it for everything?
The details are a bit complicated. The fundamental rule is fairly simple, though: never use Application
for anything involving the UI, as it may not apply styles and themes correctly.
When it comes time to inflate layouts, we need a LayoutInflater
that is aware of the styles and themes to use — otherwise, whatever we requested in those styles and themes will be ignored. But the theme might be specified on a per-activity basis. Right now, we have been looking at apps with a single activity, but it is possible — perhaps even likely — that your app will have more than one activity. Those activities might have different themes. If we get our LayoutInflater
from an Activity
, it will take the theme into account. If we get our LayoutInflater
from the Application
, it will not, as the Application
has no idea where and how the LayoutInflater
will be used.
Using Application
for non-UI concerns, such as for working with files or databases, is reasonable, as there Application
is as good as Activity
or any other kind of Context
. You do not have to go out of your way to use Application
in general, but if you have your own singletons that need a Context
, Applications
will help to avoid memory leaks.
So, use Application
:
- If you need a long-lived
Context
, and - That
Context
is not going to be used for setting up your UI
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.