"42" Android Context depth anatomy

Source: Internet
Author: User

Differences between Android programs and Java programs

Android program does not like Java programs, casually create a class, write a main () method can run, but to have a complete Android engineering environment, in this environment, we have like activity, Service, Broadcastreceiver and other system components, which do not create instances like a normal Java object new, but rather have their own context, which is what we are discussing here. As you can tell, the context is a core feature class that maintains the functionality of the components in your Android program.

What is the context?

The context of the Chinese translation is: contextual; Context Background Environment, in development we often call it "context", so what does this "context" mean? In the language, we can understand the context, in the program, we can understand the current object in the program in an environment, a process of interaction with the system. such as chatting, the "environment" refers to the chat interface and related data requests and transmission, context in the loading of resources, start activity, access to system services, create view and other operations to participate.

What is the context exactly? An activity is a context, a service is a context. Android programmers Abstract "scenes" into the context class, they think that every interaction between the user and the operating system is a scene, such as phone calls, text messages, these are an interface of the scene, there are no interface scenes, such as the background running Services (service). An application can be thought of as a working environment in which the user switches to a different scene, which is like a receptionist secretary who may need to receive a guest, may print a file, and may have to answer a customer call, which is called a different scenario, and the receptionist Secretary can call it an application.

Sub-class structure of context

The

Context provides an interface for global information about the application environment. It is an abstract class, and its execution is provided by the Android system. It allows for the use of resources and types that are characteristic of the application, and is a context that governs some resources (application environment variables, etc.). That is, it describes the information of an application environment (that is, the context); It is an abstract class, and Android provides the concrete implementation class of the abstract class, through which we can obtain the application's resources and classes (including application-level operations such as initiating activity, broadcasting, accepting intent, etc.). The

Context class itself is a pure abstract class, which has two specific implementations of subclasses: Contextimpl and Contextwrapper. Where the Contextwrapper class, as its name suggests, is just a wrapper, and the Contextwrapper constructor must contain a true context reference, Attachbasecontext () is also provided in Contextwrapper to specify a true context object in the Contextwrapper object. The method that invokes Contextwrapper is shifted to the real context object it contains. The Contextthemewrapper class, as its name suggests, contains the interfaces associated with the topic (Theme). The topic referred to here refers to the theme that is specified in Androidmanifest.xml by Android:theme for the application element or activity element. Of course, only the activity needs a theme, service is not subject, because the service is a background scene without interface, so the service directly inherits from Contextwrapper,application. The Contextimpl class actually implements the function in the context, and the methods of the various context classes called in the application are derived from the class. A sentence summary: the context of the two sub-categories of clear division, wherein Contextimpl is the context of the specific implementation class, Contextwrapper is the context of the packaging class. Although Activity,application,service is inherited from Contextwrapper (activity inherits from Contextwrapper's subclass Contextthemewrapper), However, Contextimpl objects are created during their initialization, and the methods in the context are implemented by Contextimpl.

A program contains several context:

The context has a total of application, activity, and service three types, so the calculation formula for the number of context in an application can be written like this:

Context数量 = Activity数量 + Service数量 + 1  
Application Context Design:

Basically every application will have its own application, and let it inherit from the application class of the system, and then encapsulate some common operations in its own application class.

Get application
publicclass MainActivity extends Activity {      @Override      protectedvoidonCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          MyApplication myApp = (MyApplication) getApplication();          Log.d("TAG""getApplication is " + myApp);      }  }  
Getapplication () method and Getapplicationcontext () method contact
public   Class  mainactivity  extends  activity  {  @Override  p rotected  void  oncreate  (Bundle Savedinstancestate) {super . OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); MyApplication myApp = (myapplication) getapplication (); LOG.D ( "TAG" ,  "Getapplication is"  + myApp); Context AppContext = Getapplicationcontext (); LOG.D ( "TAG" ,  "Getapplicationcontext is"  + AppContext); } } 

The printed result is the same, and even the memory address behind it is the same, it seems that they are the same object.

Why?

Application itself is a context, so getting getapplicationcontext () results Here is an example of MyApplication itself.
There are big differences between the two methods on the scope. The semantics of the Getapplication () method is very strong, knowing that it is used to get the application instance, but this method can only be called in the activity and service. So maybe in most cases we use application in activity or service, but if we want to get application instances in some other scenario, like Broadcastreceiver, You can then use the Getapplicationcontext () method, as shown below:

publicclass MyReceiver extends BroadcastReceiver {      @Override      publicvoidonReceive(Context context, Intent intent) {          MyApplication myApp = (MyApplication) context.getApplicationContext();          Log.d("TAG""myApp is " + myApp);      }  }  
Getbasecontext () method

In addition to these two methods, there is actually a getbasecontext () method, what is this basecontext?
The Getbasecontext () method gets a Contextimpl object. Does this contextimpl feel a bit familiar? Go back to the context of the inheritance structure diagram, Contextimpl is the implementation of the contextual function class. That is to say, like application, activity such classes actually do not go to the specific implementation of the function of the context, but only to do a layer of interface encapsulation, the specific function of the context is by the Contextimpl class to complete.
The Attachbasecontext () method of the Contextwrapper class, which passes a base parameter and assigns the parameter to the Mbase object. The Attachbasecontext () method is actually called by the system, it will pass the Contextimpl object as a parameter to the Attachbasecontext () method, so as to assign a value to the Mbase object, All the methods in the Contextwrapper are actually implemented by Contextimpl by this mechanism, so it is very accurate to say that Contextimpl is the implementation class of the context function.

Issues to note with application
publicclass MyApplication extends Application {      publicMyApplication() {          String packageName = getPackageName();          Log.d("TAG""package name is " + packageName);      }  }  

Error!

publicclass MyApplication extends Application {      @Override      publicvoidonCreate() {          super.onCreate();          String packageName = getPackageName();          Log.d("TAG""package name is " + packageName);      }  }  


There is a Attachbasecontext () method in Contextwrapper that assigns a context parameter passed to the Mbase object, after which the Mbase object has a value. And we know that all of the context of the method is to invoke the Mbase object of the same name method, so that is, if the Mbase object is not assigned to any of the methods in the context of the call, there will be a null pointer exception, the above code is the case.

What the context can do

Popup toast, start activity, start service, send broadcast, operate database, etc. all need to use the context.

......58;getContext().startActivity(intent);getContext().startService(intent);getContext().sendBroadcast(intent);
Context Scope

Because the specific instance of the context is implemented by the Contextimpl class, the three types of context, Activity, service, and application, are universally available in most scenarios. However, there are several scenarios that are special, such as initiating activity and popping dialog. For security reasons, Android does not allow activity or dialog to appear out of thin air, and an activity's start-up must be based on another activity, which is the return stack. The dialog must pop up on an activity (unless it is a System alert type of dialog), so in this scenario, we can only use the activity type context, otherwise there will be an error.

How to get Context:

1:view.getcontext that returns the context object of the current View object, usually the activity object currently being displayed.
2:activity.getapplicationcontext, (or getapplication ()) Gets the context object of the current Activity's (application) process, usually when we use the context object, Priority is given to this global process context.
3:contextwrapper.getbasecontext (): Used to get a contextwrapper to decorate before the context, you can use this method, this method in the actual development of the use of not much, and is not recommended to use.
4:activity.this returns the current activity instance, if the UI control needs to use Activity as the context object, but the default toast actually uses ApplicationContext.

Context of memory leaks due to: 1. Static UI Controls

Static drawable holds the context of activity

publicclass MainActivity extends Activity {    privatestatic Drawable mDrawable;    @Override    protectedvoidonCreate(Bundle saveInstanceState) {        super.onCreate(saveInstanceState);        setContentView(R.layout.activity_main);        new ImageView(this);        mDrawable = getResources().getDrawable(R.drawable.ic_launcher);        iv.setImageDrawable(mDrawable);    }}
A memory leak caused by a single case

We use the A Hungry man initialization singleton, appsettings we need to hold a context as a member variable,

publicclass AppSettings {        private Context mAppContext;    privatestaticnew AppSettings();    //some other codes    publicstaticgetInstance() {      return sInstance;    }    publicvoidsetup(Context context) {        mAppContext = context;    }}

Sinstance as a static object whose life cycle is longer than the normal object, which also contains activity, when we rotate the screen, by default, the system destroys the current activity, and the current activity is held by a singleton, which prevents the garbage collector from being recycled , which in turn creates a memory leak.

The solution is not to hold a reference to the activity, but to hold the application context reference. The code is modified as follows

publicfinalvoidsetup(Context context) {    mAppContext = context.getApplicationContext(); }
How the context avoids memory leaks:

Do not allow objects with a life cycle longer than the activity to hold references to activity
Try to use the context of application rather than the context of the activity
Try not to use non-static inner classes in the activity, because non-static inner classes implicitly hold references to external class instances (see also Java: The private modifier of "fail" for details). If a static inner class is used, the external instance reference is held as a weak reference.

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference blog:

http://blog.csdn.net/guolin_blog/article/details/47028975
Http://www.jianshu.com/p/94e0f9ab3f1d?utm_campaign=haruki&utm_content=note&utm_medium=reader_share &utm_source=weixin_timeline&from=timeline&isappinstalled=1
http://droidyue.com/blog/2015/04/12/avoid-memory-leaks-on-context-in-android/?hmsr=toutiao.io&utm_medium= Toutiao.io&utm_source=toutiao.io

"42" Android Context depth anatomy

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.