"Android" context, what context

Source: Internet
Author: User

What Context?

English Original: Context, what context?
GitHub Address: Context, what context?

Context

Context estimation is the most commonly used element in Android development, and its acquisition and use is so common that loading resources, starting new Activity, getting system services, getting internal file paths, and creating a View are inseparable from the context. At the same time, the Context is also the most error-prone element, so it is easy to take you into the pit. Let's look at the Context and make your development more handy.

Type of Context

Different types of contexts vary: depending on the Android component, the context you get is different.

Application

Application is a single-instance Context object that exists in the app process. In Activity or Service, you can use the Getapplication () method to get the Application object. In addition, the component from which he inherits the Context can be obtained by Getapplicationcontext () to this Application object. However, whatever method is obtained, the final Application object is the same.

"Translator Note: This single-instance context object is used in the post-application context reference"

Activity/service

Activity/service inherits from the same base class Context--contextwrapper, so both have the same Context API, but the task is done by delegating the calling delegate to the actual internal object. Whenever you create a new Activity or Service, you create a new Contextimpl,contextimpl that is the internal object that eventually processes all the Context API methods. Different activity or Service Context is not the same.

Broadcastreceiver

Broadcastreceiver itself is not a context, but the Android framework transmits a context to the corresponding Broadcastreceiver onreceive () when each broadcast event occurs. This receiverrestrictedcontext has a two method not available: Registerreceiver () and Bindservice (). Broadcastreceiver each time the broadcast is processed, the Context passed to it is a new instance.

ContentProvider

ContentProvider itself is not a context, but calling GetContext () can get a context. If the caller and ContentProvider are running in the same process, then this returned context is the application context above. If the caller and ContentProvider are not running within the same process, then this method returns a new Context instance that refers to the package that the provider is located in.

Save Context Reference

The first question: when we save a context reference to an object that survives longer than the context itself, the problem comes. For example, we have a singleton object that requires a Context to perform a resource load or access ContentProvider, and an Activity or Service object is passed in:

Singleton implementation of the error:

public class CustomManager {    private static CustomManager sInstance;    public static CustomManager getInstance(Context context) {        if (sInstance == null) {            sInstance = new CustomManager(context);        }        return sInstance;    }    private Context mContext;    private CustomManager(Context context) {        mContext = context;    }}

We know that a singleton object is a static variable that is controlled by the life cycle of the class in which it resides. This means that the Singleton object (reference) will not be garbage collected during the lifetime of the Singleton.
So the problem with this implementation is that you don't know where the context is coming from, and if the context is an activity or Service, it becomes unsafe: the activity that is held, and all of its internal View or other memory-consuming objects, cannot be Is recycled, causing a memory leak.

To prevent this, we have instead let the singleton hold the application context:

An improved implementation:

public class CustomManager {    private static CustomManager sInstance;    public static CustomManager getInstance(Context context) {        if (sInstance == null) {            //Always pass in the Application Context            sInstance = new CustomManager(context.getApplicationContext());        }        return sInstance;    }    private Context mContext;    private CustomManager(Context context) {        mContext = context;    }}

So we don't have to worry about where the context comes from or what kind of context it is, because it will eventually hold the application context, thus avoiding the problem of memory leaks. This processing technique works equally well in the background thread or Handler processing.

In that case, does that mean that we can use application context to deal with it under any circumstances? So you never have to worry about memory leaks. The answer is obviously no, as stated above, and the context varies from one situation to another. This is like the gourd baby, although all are gourd baby, but each kid's skills are different.

Context Features

What functions the context can achieve depends largely on where the context comes from, and the following table lists some of the different points of the context:

Application Activity Service ContentProvider Broadcastreceiver
Show a Dialog NO YES NO NO NO
Start an Activity NO1 YES NO1 NO1 NO1
Layout inflation NO2 YES NO2 NO2 NO2
Start a Service YES YES YES YES YES
Bind to a Service YES YES YES YES NO
Send a broadcast YES YES YES YES YES
Register Broadcastreceiver YES YES YES YES NO3
Load Resource Values YES YES YES YES YES
    1. Application context can initiate Activity, but only if a new task needs to be created. In some cases, we can use this approach to achieve a particular purpose, which creates a non-standard fallback stack, which is generally not recommended, at least not a good practice.
    2. This is a legitimate call, but the View obtained by inflation only applies the system theme, not the custom theme of the current app.
    3. In the 4.2 and later system versions, a broadcast listener that registers receiver Null is allowed, primarily to obtain the current value of the sticky broadcast.
User Interface

As you can see from the list above, application context is not competent for many scenarios, and it is all UI-related. In fact, only Activity has the ability to handle the UI, and other types of context are similar in this respect.

The three actions above, except the activity, other Context can not be processed, so as to avoid misuse. Trying to show a Dialog created using application context, or starting an activity from application context, will cause the app to crash and tell you in this way: you're using the wrong one.

Another problem is inflating layout. If you've read layout inflation, you'll know that inflating layout has some confusing places, and how to use the context correctly is one of them. If you use application context for inflating layout, no errors will occur, but the themes and styles defined by the current app are ignored. The reason, as you define in manifest, is that only Activity is the only component that responds to the themes definition. The Context of any other component will apply the theme of the Android system itself, so the final UI performance may surprise you.

Rule violation

One might suggest a scenario in which the current design of the app requires long-term holding of a reference to the activity because it involves manipulating the UI. If this is the case, I can only say: please reconsider your design.

Rule of thumb

In short, you can use your own context directly within the lifecycle of a component, and once you need to use context in objects beyond the lifecycle of the component, you should use only application context, even if it is a temporary reference.

Android Share Q Group: 315658668

"Android" context, what context

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.