Going through some supposedly "good" sources sources to learn the details and tricks of context handling in Android I have come across one pattern multiple time that I fail to understand.
What is the advantage of using a ContextWrapper when you could equally well use the implicit context?
For example why use the following in an activity method (defined directly in an Activity class)
...
ContextWrapper cw = new ContextWrapper(getApplicationContext())
File filesDir = cw.getFilesDir();
...
Instead of just
...
File filesDir = getFilesDir();
...
even though getFilesDir() is defined in the ContextWrapper class the Activity is anyway a subclass of ContextWrapper so you have direct access to the method anyway.
So what potential issue (that I fail to see) does this added complexity address?
getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity.
Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).
There are mainly two types of Context that are available in Android.
I'd say (and I might be wrong) that in the scenario (and context) you presented might not make a difference. getApplicationContext().getFilesDir()
could have been used just as easily.
However, I believe ContextWrapper
might be useful in other scenarios. From what I understand, this is the adapter pattern. You may want to provide different behaviour only for certain methods while proxying all other to the original context reference you pass in.
Check out this piece of code from RemoteViews
:
// RemoteViews may be built by an application installed in another
// user. So build a context that loads resources from that user but
// still returns the current users userId so settings like data / time formats
// are loaded without requiring cross user persmissions.
final Context contextForResources = getContextForResources(context);
Context inflationContext = new ContextWrapper(context) {
@Override
public Resources getResources() {
return contextForResources.getResources();
}
@Override
public Resources.Theme getTheme() {
return contextForResources.getTheme();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With