Passing `Context` everywhere seems messy - create classes to handle different interactions with context?
Whenever passing a Context
instance to another class, think,
"Is it possible that this class will actually live longer than the
Context
I'm passing to it?"
If the answer is no, don't worry. If the answer is yes, think why.
View
s for example, when used normally, will never live longer than your Activity
. As soon as the Activity
gets garbage collected, your View
will get garbage collected, so there's nothing to worry about.
Singletons however, do live longer, and will leak the Context
. That is, when the Activity
is supposed to be garbage collected, it will not be, because the singleton still has a reference to it.
A couple of solutions come to mind:
- Use
getApplicationContext()
for singletons. This type ofContext
lives for as long as your application lives - thus for as long as your singleton lives. - Use
WeakReference
s. This ensures that you will not keep an active reference to yourContext
, and avoid leakage. You will however need to compensate for possible nullity of theContext
.
Obviously, it is required you understand the basics of garbage collection. Here's an article about that.
As for the example code you've given, I see no difference in passing this instance around than passing the actual Context
around. In both cases you hold a reference to the Context
. In fact, the StateStorer
class seems to be a singleton, and - like you did - should be provided with the ApplicationContext
.
You will also often see that singletons, when supplied a Context
, call getApplicationContext()
on it themselves to avoid such mistakes:
public static MySingleton getInstance(final Context context) {
if(sInstance == null) {
sInstance = new MySingleton(context.getApplicationContext());
}
return sInstance;
}