What's the difference between the various methods to get a Context?

前端 未结 8 597
情书的邮戳
情书的邮戳 2020-11-22 04:06

In various bits of Android code I\'ve seen:

 public class MyActivity extends Activity {
    public void method() {
       mContext = this;    // since Activi         


        
相关标签:
8条回答
  • 2020-11-22 04:44

    I've only used this and getBaseContext when toasting from an onClick (very green noob to both Java and android). I use this when my clicker is directly in the activity and have to use getBaseContext in an anonymous inner clicker. I'm guessing that is pretty much the trick with getBaseContext, it is perhaps returning the context of the activity in which the inner class is hiding.

    0 讨论(0)
  • 2020-11-22 04:53

    I agree that documentation is sparse when it comes to Contexts in Android, but you can piece together a few facts from various sources.

    This blog post on the official Google Android developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:

    In a regular Android application, you usually have two kinds of Context, Activity and Application.

    Reading the article a little bit further tells about the difference between the two and when you might want to consider using the application Context (Activity.getApplicationContext()) rather than using the Activity context this). Basically the Application context is associated with the Application and will always be the same throughout the life cycle of your app, where as the Activity context is associated with the activity and could possibly be destroyed many times as the activity is destroyed during screen orientation changes and such.

    I couldn't find really anything about when to use getBaseContext() other than a post from Dianne Hackborn, one of the Google engineers working on the Android SDK:

    Don't use getBaseContext(), just use the Context you have.

    That was from a post on the android-developers newsgroup, you may want to consider asking your question there as well, because a handful of the people working on Android actual monitor that newsgroup and answer questions.

    So overall it seems preferable to use the global application context when possible.

    0 讨论(0)
  • 2020-11-22 04:59

    In simple words

    getApplicationContext() as the method name suggest will make your app aware of application wide details which you can access from anywhere in the app. So you can make use of this in service binding, broadcast registration etc. Application context will be alive till the app exits.

    getActivity() or this will make your app aware of the current screen which is visible also the app level details provided by application context. So whatever you want to know about the current screen like Window ActionBar Fragementmanger and so are available with this context. Basically and Activity extend Context. This context will alive till the current component(activity) is alive

    0 讨论(0)
  • 2020-11-22 05:00

    In some cases you may use Activity context over application context when running something in a thread. When thread completes execution and you need to return the result back to the caller activity, you need that context with a handler.

    ((YourActivity) context).yourCallbackMethod(yourResultFromThread, ...);
    
    0 讨论(0)
  • 2020-11-22 05:03

    The confusion stems from the fact that there are numerous ways to access Context, with (on the surface) no discernible differences. Below are four of the most common ways you may be able to access Context in an Activity.

    getContext()
    getBaseContext()
    getApplicationContext()
    getActionBar().getThemedContext() //new
    

    What is a Context? I personally like to think of Context as the state of your application at any given time. The application Context represents a global or base configuration of your application and an Activity or Service can build upon it and represents a configuration instance of your Application or a transitive state for it.

    If you look at the source for android.content.Context, you see that Context is an abstract class and the comments on the class are as follows:

    Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. What I take away from this is that Context provides a common implementation to access application level as well as system level resources. Application level resources may be accessing things like String resources [getResources()] or assets [getAssets()] and system-level resource is anything that you access with Context.getSystemService().

    As a matter of fact, take a look at the comments on the methods and they seem to reinforce this notion:

    getSystemService(): Return the handle to a system-level service by name. The class of the returned object varies by the requested name. getResources(): Return a Resources instance for your application’s package. getAssets(): Return a Resources instance for your application’s package. It may be worth pointing out that in the Context abstract class, all of the above methods are abstract! Only one instance of getSystemService(Class) has an implementation and that invokes an abstract method. This means, the implementation for these should be provided mostly by the implementing classes, which include:

    ContextWrapper
    Application
    Activity
    Service
    IntentService
    

    Looking at the API documentation, the hierarchy of the classes looks like this:

    Context

    | — ContextWrapper

    |— — Application

    | — — ContextThemeWrapper

    |— — — — Activity

    | — — Service

    |— — — IntentService

    Since we know that Context itself is not providing any insight, we move down the tree and take a look at the ContextWrapper and realize that there isn't much there either. Since Application extends ContextWrapper, there isn't much to look at over there either since it doesn't override the implementation provided by ContextWrapper. This means that the implementation for Context is provided by the OS and is hidden from the API. You can take a look at the concrete implementation for Context by looking at the source for the ContextImpl class.

    0 讨论(0)
  • 2020-11-22 05:07

    First, I agree that we should use appcontext whenever possible. then "this" in activity. i've never had a need for basecontext.

    In my tests, in most cases they can be interchanged. In most cases, the reason you want to get a hold of a context is to access files, preferences, database etc. These data is eventually reflected as files in your app's private data folder (/data/data/). No matter which context you use, they'll be mapped to the same folder/files so you are OK.

    That's what I observed. Maybe there are cases you should distinguish them.

    0 讨论(0)
提交回复
热议问题