Understanding and using the context in Android

Source: Internet
Author: User

Context class, The time to deal with it, for example: Service, broadcastreceiver, activity, etc. will use the relevant methods of the context.

But do not understand the principle of the context, class structure relationship. A simple question is, how many context instance objects exist in an app app?

In the context, the Chinese literal is "contextual", which is described in the SDK as follows:

Interface to global information on an application environment. This was 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

From the last three points, namely:

1, it describes the information of an application environment, that is, the context.

2. The class is an abstract class, and Android provides a concrete implementation class for that abstract class (we'll talk about the Contextiml class later).

3, through it we can get the resources and classes of the application, also include some application-level operations, such as: Start an activity, send a broadcast, accept intent

Information, etc...

application to create a context instance of the There are several situations where:

1. When creating application objects, and the entire app has a application object

2. When creating service objects

3. When you create an Activity object

So the number of context formulas common to the app app is:

Total number of context instances = Number of Service + activity + 1 (application corresponding context instance)


The opportunity to create a context specifically

1. Time to create application objects

The first time each application starts, the Application object is created first. If an activity (startactivity) process comparison is initiated on the application

Clear words, the time to create application in the Create Handlebindapplication () method

2. Time to create Activity objects

When an activity is started by startactivity () or Startactivityforresult () request, if the system detects that a new activity object needs to be created, it

Callback Handlelaunchactivity () method, which then calls the Performlaunchactivity () method to create an activity instance, and callback

OnCreate (), OnStart () method and so on.

3. Time to create service objects

With StartService or Bindservice, if the system detects that a new service instance needs to be created, it will callback the Handlecreateservice () method,

Complete the relevant data operation.

The context in Android can do many things, but the main function is to load and access resources. In Android, there are two kinds of context, one is application context, the other is activity context, usually we pass the activity context between various classes and methods.
Inheritance Relationship:


Difference of Contact:
public class MyActivity extends Activity {
public void Method () {
Mcontext = this; Since Activity extends Context
Mcontext = Getapplicationcontext ();
Mcontext = Getbasecontext ();
}
}
This is an instance of activity that expands the context whose life cycle is activity creation to destruction. Getapplicationcontext () Returns the context of the application, the life cycle is the entire application, and the application destroys it before it is destroyed. The context of the Activity.this returns the current activity, belonging to the activity, destroying the activity and destroying it.
Getbasecontext () returns the context specified by the constructor or Setbasecontext (), with few SDK documentation and deprecated
Figuring out the life cycle will make mistakes in the process, such as having a global data manipulation class used in the context, this time to getapplicationcontext instead of using activity, This ensures that the operation of the database is not related to activity (does not always reference activity resources to prevent memory leaks)
Application Scenarios:
For example, an activity oncreate:
protected void OnCreate (Bundle state) {
Super.oncreate (state);
TextView label = new TextView (this); //?? Context?view C
Ontrol
Label.settext ("Leaks is bad");
Setcontentview (label);
}
Passing the activity context to view means that view has a reference to activity that references the resources that the activity occupies: view hierachy, Resource, and so on. This will leak a lot of memory if the context has a memory leak. The leak here means that the GC has no way to reclaim the activity's memory.
Leaking an entire activity is a very easy thing to do. When the screen rotates, the system destroys the current activity, saves the state information, and creates a new activity.
For example we have written an application that needs to load a large picture, and we do not want to destroy the image reload every time we rotate the screen.
The simple idea to implement this requirement is to define a static drawable so that the activity class is created and destroyed it is always stored in memory.
Implementation examples:
public class MyActivity extends Activity {
private static drawable Sbackground;
protected void OnCreate (Bundle state) {
Super.oncreate (state);
TextView label = new TextView (this);
Label.settext ("Leaks is bad");
if (Sbackground = = null) {
P 2/3
Android Context Detailed
Sbackground = getdrawable (r.drawable
. Large_bitmap);
}
Label.setbackgrounddrawable (sbackground);//dra
Wable attached to a view
Setcontentview (label);
}
}
The program looks simple, but it's a big problem. There is a leak when the screen rotates (that is, the GC cannot destroy the activity). As we have just said, the system destroys the current activity when the screen is rotated. However, when drawable is associated with a view, Drawable saves the view's reference, that is, Sbackground holds a reference to the label, and the label holds the activity's reference. Since drawable cannot be destroyed, neither the reference nor the indirect reference can be destroyed, so that the system has no way to destroy the current activity, resulting in a memory leak. The GC is powerless against this type of memory leak. The way to avoid this kind of memory leak is to avoid the life cycle of any object in the activity and avoid the activity being destroyed by the object's reference to activity. We can use application context. Application context accompanies application's lifetime, irrespective of the life cycle of the activity. Application context can be obtained through the Context.getapplicationcontext () or Activity.getapplicationcontext () method.

Customizing one's own application: first create a MyApplication class that inherits from application

public class MyApplication extends application

{

private static context context;

public void OnCreate ()

{

Context=getapplicationcontext ();

}

public static Context GetContext ()

{

return context;

}

}

Note: The MyApplication class should be initialized when the program starts, rather than the default application class. You can do this by specifying it under the <application> tab of the Androidmainifest.xml file.

<application

Android:name= "Com.example.hl.MyApplication"

</application>

This has achieved a global access to the context of the mechanism, after you want to use the application context in the project, just call Myapplication.getcontext ().

To avoid context-related memory leaks, keep the following points in mind:
1. Do not allow objects with long life cycles to refer to the activity context, which guarantees that the object referencing the activity is the same as the activity itself life cycle
2. For objects with long life cycles, you can use the application context
3. Avoid non-static internal classes, use static classes as much as possible, avoid life cycle problems, and note the life cycle changes caused by internal classes to external object references

Understanding and using the context in Android

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.