Context comprehension and usage skills in Android

Source: Internet
Author: User

Context comprehension and usage skills in Android

Context class, always dealing with it, such as: Service, BroadcastReceiver, Activity, etc. will use the Context method.

However, they do not understand the principle and class structure of Context. A simple question is, how many Context instance objects exist in an App?


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-CILS

For application-level operations such as launching activities, broadcasting and processing intents, etc

The following three points are shown:

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

2. This class is an abstract class. Android provides the concrete implementation class of this abstract class (we will talk about the ContextIml class later ).

3. We can use it to obtain application resources and classes, as well as some application-level operations, such as starting an Activity, sending broadcasts, and accepting Intent

Information ..


The application creates a Context instance in the following situations:

1. When creating an Application object, and the entire App has a total of Application objects

2. When creating a Service object

3. When creating an Activity object

Therefore, the formula for the total number of Context values in an App is as follows:


Total number of Context instances = Service count + Activity count + 1 (Context instance corresponding to Application)



Time to create the Context


1. Creation Time of Application object


Each Application will first create an Application object when it is started for the first time. If you start a startActivity process comparison for the application

Clearly, the Application creation time is in the handleBindApplication () method.

2. Time to create an Activity object


When you use startActivity () or startActivityForResult () to start an Activity, if the system detects that you want to create a new Activity object

Callback handleLaunchActivity () method. This method then calls the initiate mlaunchactivity () method to create an Activity instance and calls back

OnCreate () and onStart () methods.

3. Time to create a Service object


When startService or bindService is used, if the system detects that a new Service instance is required, the handleCreateService () method is called back,

Complete related data operations.


In Android, context can perform many operations, but the main function is to load and access resources. In android, two kinds of context are commonly used. One is application context and the other is activity context. Generally, activity context is transmitted between different types and methods.
Inheritance relationship:

Public class MyActivity extends Activity {
Public void method (){
MContext = this; // since Activity extends Context
MContext = getApplicationContext ();
MContext = getBaseContext ();
This is an instance of Activity, extended Context, and its lifecycle is from Activity creation to destruction. GetApplicationContext () returns the context of the application. The life cycle is the whole application, and the application is destroyed only when it is destroyed. The context of Activity. this returns the context of the current activity, which belongs to the activity. If the activity is destroyed, it is destroyed.
GetBaseContext () returns the context specified by the constructor or set by setBaseContext (). The SDK documentation is rare and is not recommended.
It is clear that the lifecycle will make mistakes during use. For example, if a global data operation class uses context, getApplicationContext is required instead of ACtivity, this ensures that database operations are irrelevant to the activity (the Activity resources are not always referenced to prevent memory leakage)
Application scenarios:
For example, onCreate of an activity:
Protected void onCreate (Bundle state ){
Super. onCreate (state );
TextView label = new TextView (this );//?? Context? View c
Label. setText ("Leaks are bad ");
SetContentView (label );
Passing the activity context to the view means that the view has a reference pointing to the activity and then referencing the resources occupied by the activity: view hierachy and resource. In this way, if the context memory leaks, a lot of memory will be leaked. This vulnerability indicates that gc cannot recycle activity memory.
Leaking an entire activity is an easy task. When the screen rotates, the system destroys the current activity, saves the status information, and creates a new activity.
For example, if we write an application that needs to load a large image, we do not want to destroy the image and reload it every time we rotate the screen.
The simple idea of implementing this requirement is to define a static Drawable, so that the Activity class creation and destruction is always stored in the memory.
Implementation example:
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 are bad ");
If (sBackground = null ){
P 2/3
Android Context
SBackground = getDrawable (R. drawable
. Large_bitmap );
Label. setBackgroundDrawable (sBackground); // dra
Wable attached to a view
SetContentView (label );
This program looks very simple, but it has a big problem. When the screen is rotated, there will be a leak (that is, the gc cannot destroy the activity ). As we said earlier, when the screen is rotated, the system will destroy the current activity. However, when drawable is associated with the view, drawable saves the view reference, that is, sBackground saves the label reference, while the label stores the reference of the activity. Since drawable cannot be destroyed and neither referenced nor indirectly referenced by it can be destroyed, the system cannot destroy the current activity, resulting in Memory leakage. Gc is powerless for this type of Memory leakage. To avoid Memory leakage, you can avoid any activity whose lifecycle is longer than that of the activity, and prevent the activity from being destroyed due to its reference to the activity. We can use application context. Application context is associated with the life cycle of the application and has nothing to do with the life cycle of the activity. Application context can be obtained through Context. getApplicationContext () or Activity. getApplicationContext.

Create your own Application: first create a MyApplication class inherited from the 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, instead of the default Application class. You can specify it under the tag of the AndroidMainifest. xml file.

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


In this way, a global Context retrieval mechanism has been implemented. To use the Context of Application in a project, you only need to call MyApplication. getContext.

To avoid Memory leakage related to context, remember the following points:
1. Do not make an object with a long life cycle reference the activity context. That is, make sure that the object that references the activity has the same life cycle as the activity itself.
2. For objects with a long life cycle, you can use application context
3. Avoid non-static internal classes and try to use static classes to avoid lifecycle issues. Pay attention to the lifecycle changes caused by internal class references to external objects.

Related Article

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