Transferred from: http://blog.csdn.net/qinjuning/article/details/7310620
Hello everyone, today to introduce us in the application development of the most familiar and unfamiliar friends-----context class, said it is familiar with, it should be for us in the development of the moment in dealing with it, for example: Service, Broadcastreceiver, Activity and so will use the relevant methods of the context, said it is unfamiliar, because we really 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? One, two? Let's sell a xiaoguanzi here. Read the article, I believe you will be enlightened.
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 was provided by the Android system. It allows access to application-specific resources and classes, as-well-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 broadcasts, accept intent information, etc...
Thus, we can use this context object to build an application-level operation (Application-level operations).
I. The inheritance relationship of context related classes
Related class Description:
Context class path:/frameworks/base/core/java/android/content/context.java
Description: An abstract class that provides a common set of APIs.
The source code (part) is as follows:
Public abstract class Context { ... Public abstract Object Getsystemservice (String name); Get system-level service public abstract void startactivity (Intent Intent); Start activity public abstract componentname startservice (Intent service) through a Intent; Start service //Get Sharedpreferences object according to filename public abstract sharedpreferences getsharedpreferences (String Name,int mode); ...}
Contextiml.java class path:/frameworks/base/core/java/android/app/contextimpl.java
Description: The implementation class of the context class is CONTEXTIML, which implements the function of the context class. Note that most of the functionality of the function is to call its properties mpackageinfo to complete, as we'll see later.
The source code (part) is as follows:
/** * Common Implementation of the context API, which provides the base * Context object for Activity and other Applicati On the components. */class Contextimpl extends context{//All application programs common one Mpackageinfo object/*package*/ activitythread.pack Ageinfo Mpackageinfo; @Override public Object getsystemservice (String name) {... else if (Activity_service.equals (n AME) {return getactivitymanager (); } else if (input_method_service.equals (name)) {return inputmethodmanager.getinstance (this );}} @Over Ride public void startactivity (Intent Intent) {...//start an Activity mmainthread.getinstrumentation (). Execstartactivity (Getoutercontext (), mmainthread.getapplicationthread (), NULL, NULL, intent,-1 );}}
Contextwrapper class path: \frameworks\base\core\java\android\content\contextwrapper.java
Description: Like its name, this class is just a wrapper for the context class whose constructor contains a true context reference, the Contextim object.
The source code (part) is as follows:
public class Contextwrapper extends context { context mbase; This attribute points to an CONTEXTIML instance, which is typically assigned when creating application, service, activity,/ /create application, service, activity, This method is called to assign a value to the Mbase property protected void Attachbasecontext (Context base) { if (mbase! = null) { throw new IllegalStateException ("Base context already set"); } Mbase = base; } @Override public void startactivity (Intent Intent) {mbase.startactivity (Intent);//Call Mbase instance method }}
Contextthemewrapper class path:/frameworks/base/core/java/android/view/contextthemewrapper.java
Description: The class internally contains a topic (THEME)-related interface, which is specified by the Android:theme property. Only the activity requires a theme, and the service does not need a theme, so the service inherits directly from the Contextwrapper class.
The source code (part) is as follows:
public class Contextthemewrapper extends contextwrapper { //This attribute points to a CONTEXTIML instance, typically creating application, Service, Assign value to private Context mbase when activity; Mbase assignment The same way there are 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 class, service class, application class are essentially context subclasses, more information you can refer to the source code to understand.
Ii. when to create a context instance
Having become familiar with the context's inheritance, we then analyze what situations the application needs to create a context object for? 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 it is clear that an activity (startactivity) process is started for an application, the time to create the application is in the Create Handlebindapplication () method, which is located in the The Activitythread.java class, as follows:
CONTEXTIML instance created at the same time when creating application private final void handlebindapplication (appbinddata data) { ... Create 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 related properties of the CONTEXTIML instance/// Create a new Application object app = } ...}
2. Time to create Activity objects
Create a CONTEXTIML instance when creating an activity instance private final void handlelaunchactivity (Activityrecord R, Intent customintent) { ... Activity a = performlaunchactivity (R, customintent); Start an activity}private final activity performlaunchactivity (Activityrecord R, Intent customintent) { ... activity activity = NULL; Try { //Create an Activity object instance java.lang.ClassLoader cl = r.packageinfo.getclassloader (); activity = minstrumentation.newactivity (cl, Component.getclassname (), r.intent);} if (activity! = null) {Contextimpl appContext = new Contextimpl ();//Create an Activity instance Appcontext.init (R.packageinfo, R . token, this); Initializes the associated property of the CONTEXTIML instance Appcontext.setoutercontext (activity); Pass the activity information to the Contextimpl instance ...}
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 and complete the relevant data operation. The Handlecreateservice () function is located in the Activitythread.java class, as follows:
Create a CONTEXTIML instance when creating a service instance private final void Handlecreateservice (createservicedata data) { ... Create a service instance service 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 relevant properties of the CONTEXTIML instance//Get the Application object information we created earlier application app = Packageinfo.makeapplication (False, Minstrumentation); Pass the service information to the Contextimpl instance context.setoutercontext (service); ...}
In addition, it is important to emphasize that, through the analysis of Contextimp, most of the operations of its methods are directly calling its property mpackageinfo (the attribute class
Type PackageInfo). This shows that Contextimp is a lightweight class, and PackageInfo is the real heavyweight class . And the one in the app
All CONTEXTIML instances correspond to the same PackageInfo object.
Context in Android----The context you don't know