Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ContextWrapper directly in an Activity instead of implicit context from "this"

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?

like image 771
Johan Avatar asked Jul 13 '15 11:07

Johan


People also ask

What is the difference between getContext () getApplicationContext () getBaseContext () and this?

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.

What is context context in Android?

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).

How many types of context are there in Android?

There are mainly two types of Context that are available in Android.


1 Answers

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();
    }
};
like image 115
takecare Avatar answered Oct 09 '22 09:10

takecare