What is the difference between methods for obtaining a context?

Asked

Viewed 813 times

8

One can, beyond the this, get the context in several ways, with different methods. As shown in the code below, we have the getApplicationContext() and the getBaseContext() which apparently serves the same purpose.

public class MainActivity extends AppCompatActivity{

    public Context context;

    public void umMetodoQualquer() {
        context = this;
        context = getApplicationContext();
        context = getBaseContext();
    }
}

And in practice, what are the differences between the methods for obtaining a context?

3 answers

9


They return different "types" of Context, with lifetimes and access to Resources different.

Context is an abstract class, implemented internally by the class Contextimpl.
The various "types" (behaviors) of Context are obtained using Factory methods contextimpl.

Publicly, a Context is made available through classes inherited from Contextwrapper.
Contextwrapper inherits from Context and implements its methods in a way that simply delegates calls to another Context().
This allows subclasses such as Application, Service and Activity (indirectly via Contextthemewrapper), modify its behavior without changing the original Context.

  • this - In this case it refers to an Activity. Its life time is linked to the life time of the Activity and, through it, access to Resources(1) defined for this Activity.

    java.lang.Object
       ↳    android.content.Context
           ↳    android.content.ContextWrapper
               ↳    android.view.ContextThemeWrapper
                   ↳    android.app.Activity  
    
  • getApplicationContext() - It refers to the application. Its lifespan is linked to the lifespan of the application and, through it, access to Resources(1) defined for the application.

    java.lang.Object
       ↳    android.content.Context
           ↳    android.content.ContextWrapper
               ↳    android.app.Application 
    
  • getBaseContext() - The context which was used when creating the Contextwrapper object, passed to or assigned to the constructor by the method attachBaseContext(). He’s the Contextimpl type.

    java.lang.Object
       ↳    android.content.Context
           ↳    android.content.ContextImpl
    

    If the Contextwrapper subclass does not overwrite any of the methods, the Context returned will have a behavior equal to that of the subclass.
    For example, the context passed to the method onReceive() Broadcastreceiver is the type Receiverrestrictedcontext. In it the methods registerReceiver() and bindService() are superscripted to release Receivercallnotallowedexception, if called.

(1) For example, if for this Activity you set a Theme other than Theme of the application, the views created with the context this look different from those created with the context returned by getApplicationContext().

You can check the type of each Context, obtained by each of the methods, using this code:

activity = this;
applicationContext = getApplicationContext();
baseContext = getBaseContext();

Log.d("Context", activity.getClass().getName());
Log.d("Context", applicationContext.getClass().getName());
Log.d("Context", baseContext.getClass().getName());
  • getbaseContext also refers to Activity or it would be something more complex?

  • getbaseContext() returns the context created by the system, an instance of Contextimp that is created and configured(I suppose) depending on the type of component that will use it: Activity/Service or Application. It is accessed through the proxy Contextwrapper, from which they inherit. Each of them is a context but its "implementation/configuration" is provided externally.

  • I don’t know if the Acrivity class overwrites any of the Contextwrapper methods. If it doesn’t overwrite the Context returned by getBaseContext() will behave in the same way as (Context)this.

  • I did the following test using the logo: this.getClass().getName() returned the name of Activity; getApplicationContext().getClass().getName() returned android.app.application; getBaseContext().getClass().getName() returned android.app.ContextImpl. I would like to know in practice, how/when/where it is used. It would have as you exemplify?

  • Use the Context of the component within which you are(this), provided that the reference to it does not extend beyond the life cycle of that component. If that is not the case, use getApplicationContext(). So far I have found no reason to use getBaseContext(). See this post where you have more complete information.

  • I still have a flea behind my ear, but I will validate the answer, then you put this link of the post (which is very interesting) to a question of deepening the subject, which is also a complement. Thank you.

  • What doubts you still have?

  • For example, this getBaseContext() nor should exist, because the this and the getApplicationContext are already enough considering its functionalities. So because of that, I also got to thinking. In the post you passed has no reference on it.

  • Usually a wrapper/proxy does not expose the internal object(s). It is possible that there is some situation where it is useful/necessary to use getBaseContext(), I haven’t found any yet.

Show 4 more comments

9

getApplicationContext() how the name is associated to the context of the application and will be the same while the application lasts.

Already getBasecontext() associated with the activity and will be destroyed along with the activity.

  • then getBaseContext is the same as this?

  • Yes. this is the current context, context of the activity on screen, or the current fragment, which forces us to search the context of the application to access some specific method.

5

this: It is the current context of your Activity, belongs to activiy, when activiy is destroyed, the context will also be. Note: Extension of Activity, which may turn, also extends from a class Context.

getApplicationContext(): It is the context of the application, the whole application lifecycle, when the application is destroyed, then the context of the application will also be.

getBaseContext(): It is a method of ContextWrapper, is the simplest context implementation that delegates all calls to another context. Can be subclassified to modify behavior and change original context.

When to use:

Use this: When you need to present Dialogs, Alertdialogs, etc., messages to the user in the Activity he is in.

Use getApplicationContext: Use when you want a context that is independent of the Activity lifecycle, that is, that exists throughout the application cycle.

Use getBaseContext: When you want to access Context from another context within the application you can access. Example: Widgets, Views, etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.