Explanation of context in Android -- context you do not know

Source: Internet
Author: User

This article is original and must be reproduced with the following source:Http://blog.csdn.net/qinjuning

 

 

This article is the Reading Notes generated after I read chapter 7th of "android Kernel Analysis". I recommend this book to books that want to know about the android framework.

 

 

 

 

Hello everyone, today we will introduce to you the most familiar and unfamiliar friend in Application Development ----- context class, which should be in development for us.

It is always dealing with it. For example, service, broadcastreceiver, and activity all use context-related methods.

Because we really don't understand the principle and class structure of context. A simple question is, how many context instance objects exist in an app?

One or two? Here, I 'd like to sell a token first. After reading this article, I believe you will be enlightened.

 

Context:


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

 

 

Therefore, we can use this context object to Construct application-level operations ).

 

1. Inheritance relationships of context-related classes

 

 

Related Classes:

 

Context classPath:/frameworks/base/CORE/Java/Android/content/context. Java

Description: abstract class, which provides a set of common APIs.

The source code (Part) is as follows:

Public abstract class context {... public abstract object getsystemservice (string name); // obtain the system-level service public abstract void startactivity (intent); // start activity public abstract componentname startservice (intent Service) through an intent ); // start service // obtain the sharedpreferences object public abstract sharedpreferences getsharedpreferences (string name, int mode) according to the file name );...}

 

 Contextiml. Java classPath:/frameworks/base/CORE/Java/Android/APP/contextimpl. Java

Description: contextiml is the implementation class of the context class, which implements the functions of the context class. Note that most functions of this function are called directly.

Its Attribute mpackageinfo is completed, which will be discussed later.

The source code (Part) is as follows:

/*** Common Implementation of context API, which provides the base * context object for activity and other application components. */class contextimpl extends context {// all applications share an mpackageinfo object/* package */activitythread. packageinfo mpackageinfo; @ override public object getsystemservice (string name ){... else if (activity_service.equals (name) {return getactivitymanager ();} else if (input_method_service.equals (name) {return inputmethodmanager. getinstance (this) ;}@ override public void startactivity (intent ){... // start an activity mmainthread.getinstrumentation(cmd.exe cstartactivity (getoutercontext (), mmainthread. getapplicationthread (), null, null, intent,-1 );}}

 

 

Contextwrapper classPath: \ frameworks \ base \ core \ Java \ Android \ content \ contextwrapper. Java

Note: like its name, this class is only a packaging of the context class. The contextiml contains a real context reference.

Object. The source code (Part) is as follows:

Public class contextwrapper extends context {context mbase; // This attribute points to a contextiml instance. Generally, values are assigned when application, service, and activity are created. // application, service, and activity are created, this method is called to assign the value protected void attachbasecontext (context base) {If (mbase! = NULL) {Throw new illegalstateexception ("base context already set");} mbase = base ;}@ override public void startactivity (intent) {mbase. startactivity (intent); // call the mbase instance method }}

 

 


Contextthemewrapper classPath:/frameworks/base/CORE/Java/Android/View/contextthemewrapper. Java

Note: This class contains theme-related interfaces, that is, the Android: Theme attribute is specified. Only the activity requires a topic, and the service does not,

Therefore, the service directly inherits from the contextwrapper class.

The source code (Part) is as follows:

Public class contextthemewrapper extends contextwrapper {// This attribute points to a contextiml instance. Generally, private context mbase is assigned when application, service, and activity are created; // The mbase assignment method also has two public contextthemewrapper (context base, int themeres) {super (base); mbase = base; mthemeresource = themeres ;} @ override protected void attachbasecontext (context newbase) {super. attachbasecontext (newbase); mbase = newbase ;}}

 

 

Activity, service, and application classes are essentially context subclasses. For more information, see the source code for your understanding.

 

 

Ii. When to create a context instance

 

After familiarizing ourselves with the inheritance relationship of context, let's analyze the situation in which the application needs to create the context object? The application creates

There are several 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. This function is located in the activitythread. Java class, as shown below:

// Contextiml instance private final void handlebindapplication (appbinddata data ){... /// create the application object application APP = data.info. makeapplication (data. restrictedbackupmode, null );...} public Application makeapplication (Boolean forcedefaultappclass, instrumentation Instrumentation ){... try {Java. lang. classloader Cl = getclassloader (); contextimpl appcontext = new contextimpl (); // create a contextimpl object instance appcontext. init (this, null, mactivitythread); // initialize the attributes of the contextiml instance. // create an Application Object APP = mactivitythread. minstrumentation. newapplication (CL, appclass, appcontext); appcontext. setoutercontext (APP); // pass the application instance to the contextimpl instance }...}

 

 

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 (), onstart () method, etc. All functions are located in the activitythread. Java class, as shown below:

// Create a contextiml instance private final void handlelaunchactivity (activityrecord R, intent customintent ){... activity A = launch mlaunchactivity (R, customintent); // start an activity} private final activity launch mlaunchactivity (activityrecord R, intent customintent ){... activity activity = NULL; try {// create an activity object instance Java. lang. classloader Cl = R. packageinfo. getclassloader (); Activity = minstrum Entation. newactivity (CL, component. getclassname (), R. Intent);} If (activity! = NULL) {contextimpl appcontext = new contextimpl (); // create an activity instance appcontext. init (R. packageinfo, R. token, this); // initialize the appcontext of the contextiml instance. setoutercontext (activity); // pass the activity information to the contextimpl instance ...}...}

 

 


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. The handlecreateservice () function is located in the activitythread. Java class, as follows:

// Create a contextiml instance private final void handlecreateservice (createservicedata data ){... // create a service instance service = NULL; try {Java. lang. classloader Cl = packageinfo. getclassloader (); service = (service) Cl. loadclass (data.info. name ). newinstance ();} catch (exception e ){}... contextimpl context = new contextimpl (); // create a contextimpl object instance context. init (packageinfo, null, this); // initialize the attributes of the contextiml instance // obtain the information of the previously created application object application APP = packageinfo. makeapplication (false, minstrumentation); // pass the service information to the contextimpl instance context. setoutercontext (service );...}

 


In addition, it should be emphasized that, according to the analysis of contexqp, most of the operations of its method call its attribute mpackageinfo directly (this attribute class

Type is packageinfo. This descriptionContexibd is a lightweight class, while packageinfo is a truly heavyweight class.. In an app

All contextiml instances correspond to the same packageinfo object.

 

Finally, we will analyze how to use context to obtain the sharedpreferences class. The sharedpreferences class must have been used by all users.

The getsharedpreferences () method is called to obtain the sharedpreferences object based on relevant information. The specific process is as follows:

 

1. Call getsharedpreferences () to obtain the corresponding file. The function provides the following functions:

 

// The context class static data set, which saves all the data sets formed after reading the XML file with key-value pairs Private Static final hashmap <file, sharedpreferencesimpl> ssharedprefs = new hashmap <file, sharedpreferencesimpl> (); @ overridepublic sharedpreferences getsharedpreferences (string name, int mode) {// the corresponding sharedpreferencesimpl object, this object already has a hashmap set that saves the sharedpreferencesimpl sp; file F = getsharedprefsfile (name); // whether the corresponding file exists under this package, create a new synchronized (S Sharedprefs) {// if the file has been read, The sharedpreferences object sp = ssharedprefs. Get (f); If (SP! = NULL &&! SP. hasfilechanged () {// log. I (TAG, "returning existing prefs" + name + ":" + SP); Return SP ;}// serialize the XML file, at the same time, the data is written to the map set map = NULL; If (F. exists () & F. canread () {try {STR = new fileinputstream (f); map = xmlutils. readmapxml (STR); Str. close ();}...} synchronized (ssharedprefs) {If (SP! = NULL) {// log. I (TAG, "updating existing prefs" + name + "" + SP + ":" + map); SP. replace (MAP); // update the data set} else {sp = ssharedprefs. get (f); If (sp = NULL) {// create a sharedpreferencesimpl object and set its attributes sp = new sharedpreferencesimpl (F, mode, MAP); ssharedprefs. put (F, SP) ;}} return SP ;}}

 

2. sharedpreferences is just an interface. It defines some methods for operating XML files. Its real implementation class is sharedpreferencesimpl, which is

Contextiml internal class, which is as follows:

 

// Soga, which we have touched when analyzing context contextiml // sharedpreferences is just an interface, the real implementation class is sharedpreferencesimpl class Private Static final class sharedpreferencesimpl implements sharedpreferences {private map MMAP; // The operation after saving the serialization result of the file, key-Value Pair form // obtain the corresponding value through the key value Public String getstring (string key, string defvalue) {synchronized (this) {string v = (string) MMAP. get (key); Return V! = NULL? V: defvalue ;}}... // obtain the edito class corresponding to the sharedpreferencesimpl object and operate the public final class editorimpl implements editor {private final map <string, Object> mmodified = maps. newhashmap (); // saves the set of key-value changes }}

 

Basically, this is the way to get the sharedpreferences object. For more information about the context, refer to the source code to learn it carefully.

 

 

 

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