The context is not clear, how to do Android development?

Source: Internet
Author: User

Activity mactivity =new activity ()

As an Android developer, don't know if you've ever thought about this question, can activity be new? Android application development in the Java language, activity is also essentially an object, the above writing what is the problem? It is estimated that many people are unclear. Android program does not like Java programs, casually create a class, write a main () method to run, Android application model is based on the application design pattern of components, components to run a complete Android engineering environment, in this environment, Activity, The service and other system components are not working properly, and these components do not use the normal Java object creation, new can create the instance, but to have their own context, that is, we discussed here. As you can tell, the context is a core feature class that maintains the functionality of the components in your Android program.

What the hell 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.

How vivid the image of the understanding context

The above concept uses a popular understanding of the context as a "contextual" or "scene", if you still feel very abstract, difficult to understand. Here I give a metaphor that may not be very appropriate, hoping to help you understand: an Android app that can be understood as a movie or a TV show, Activity,service,broadcast receiver,content Provider these four components are like the four main characters in this play: Hu song, Huojianhua, poetry, Baby. They were set up by the crew (the system), and the whole play was led by the four starring actors, so the four protagonists were not the only people on the street who were casually pulling a person (new object) to play. With actors, of course, they have to have cameras, and they have to pass the scene to the audience, which corresponds to the four components (four characters) that must work in context (camera lens). That button,textview,linearlayout these controls, it is like the play of the supporting actor or the actors, they obviously not so reuse, a random passers-by can play (can be a new object), But they also have to face the camera (working in context), so Button mButton=new Button(Context) it's possible. Although not very appropriate, but it is very easy to understand, and hope to help.

The context in the source code

/** * 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 as * Up-calls for application-level operations s Uch as launching activities, * broadcasting and receiving intents, etc. * *PublicAbstractClassContext {/** * File creation mode:the default mode, where the created File can only * is accessed by the calling application (or a ll applications sharing the * same user ID). *@see #MODE_WORLD_READABLE * @see #MODE_WORLD_WRITEABLE */public static final int MODE_PRIVATE = Span class= "Hljs-number" >0x0000; public static final int mode_world_writeable = 0x0002; public static final int mode_append = 0x8000; public static final int mode_multi_process = 0x0004; ...}      

The comments in the source code explain the 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.). Since the above context is an abstract class, then there must be his implementation of the class, we in the context of the source through the IDE can be seen in his sub-class can finally get the following diagram:


Context.png

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.

An application has several context

In fact, the problem itself is not meaningful, the key is to understand the context, from the above diagram we can already come to the answer, in the application context of the specific implementation subclass is: Activity,service,application. So Context数量=Activity数量+Service数量+1 . Of course, if you are careful enough, there may be doubts: we often say four components, where only activity,service hold the context, that broadcast receiver,content provider? Broadcast receiver,content provider is not a sub-class of the context, they hold the context is passed elsewhere, so does not count into the total number of the context. The above diagram also tells us from another side how lofty the context class is in the entire Android system, because it is clear that Activity,service,application is its subclass, and its status and role is self-evident.

What the context can do

What functions can the context achieve? This is really too much, pop toast, start activity, start service, send broadcast, operation database, etc. all need to use the context.

TextView TV =NewTextView (GetContext ());ListAdapteradapter =NewSimplecursoradapter (Getapplicationcontext (), ...);AudiomanagerAM = (audiomanager) getcontext (). getsystemservice (context. Audio_service); getapplicationcontext (). getsharedpreferences (name, mode); getapplicationcontext (). getcontentresolver (). query (URI, ...); getcontext (). getresources (). getdisplaymetrics (). widthpixels * 5/8; getcontext (). startactivity (intent); getcontext (). startservice (intent); getcontext (). sendbroadcast (intent);           

Context Scope

Although the context of a well-being, but not just get a context instance can do whatever it is, its use has some rules and restrictions. 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.


Context scope. png


From what we can see, the scope of the context in which the activity is held is the widest and omnipotent. Because activity inherits from Contextthemewrapper, and application and service inherit from Contextwrapper, Obviously contextthemewrapper on the basis of contextwrapper and do some operations to make the activity become more powerful, here I will no longer paste the source code for everyone to analyze, interested in children's shoes can check their own source code. Yes and no I don't have too much to explain, here I say the application and service are not recommended two use cases.
1: If we use ApplicationContext to start an activity with a launchmode as standard, android.util.AndroidRuntimeException: Calling startActivity from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? this is because the non-activity type of context does not have the so-called task stack, So the activity to be started will not find the stack. The solution to this problem is to specify the flag_activity_new_task tag bit for the activity to be started, so that when it is started, a new task stack is created for it, and the activity is started in Singletask mode. All of this is not recommended to start activity with application, service with application.
2: Go to Layout in application and service inflate is also legal, but will use the system default theme style, if you customize some styles may not be used. Therefore, this method is also not recommended for use.
Summary: All UI-related, should use Activity as the context to deal with, and other operations, service,activity,application and other instances can, of course, pay attention to the context reference holding, to prevent memory leaks.

How to get context

Usually we want to get the context object, there are four main methods
1:view.getcontext that returns the context object of the current View object, usually the activity object currently being displayed.
2:activity.getapplicationcontext, gets the context object of the current Activity's (application) process, usually when we use the context object, the global process context is given precedence.
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.

Getapplication () and Getapplicationcontext ()

The above is said to get the current application object with Getapplicationcontext, do not know whether you associate to Getapplication (), what is the difference between these two methods? I believe this problem will overwhelm many developers.


Getapplication () &getapplicationcontext (). png

The program is not deceptive, we print from the above code, the memory address of the two are the same, it appears that they are the same object. In fact, this result is also very good understanding, because the previous has said, application itself is a context, so here to get Getapplicationcontext () The result is application itself instance. So the question is, since both methods get the same results, why should Android provide two ways to repeat the function? In fact, these two methods are quite different in 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.

publicclassMyReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){ApplicationmyApp=(Application)context.getApplicationContext();}}

Memory leaks due to context

However, the context can not be arbitrarily used, the use of the bad may cause a memory leak, the following examples of the two ways to refer to the error.

The wrong singleton mode

public class Singleton {    private static Singleton instance;    private Context mContext;    private Singleton(Context context) {        this.mContext = context;    }    public static Singleton getInstance(Context context) {  if (instance == null) {  instance = new Singleton(context); }  return instance; }}

This is a non-thread-safe singleton mode, instance as a static object whose life cycle is longer than the normal object, which also contains activity, if activity a goes to getinstance to get instance object, pass in this, The resident memory Singleton holds your incoming activity a object and holds it all the time, even if the activity is destroyed, but because its reference exists in a singleton, it is impossible to get a GC off, which results in a memory leak.

View holds activity references

PublicClassMainactivityextends activity {private static Span class= "Hljs-type" >drawable mdrawable;  @Override protected void OnCreate ( Bundle saveinstancestate) {super.oncreate (saveinstancestate); Setcontentview (r.layout.activity_main); imageview IV = new ImageView (this); mdrawable = Getresources (). getdrawable (r.drawable.ic_launcher); Iv.setImageDrawable ( mdrawable); }} 
When drawable is set to ImageView, ImageView will set itself to drawable callback, because view implements the Drawable.callback interface, This can be called when the drawable needs to be refreshed. This callback, and then notifies the view to redraw the drawable. So the correct order of references should be drawable->view->context, that's what caused the leak

There is a static drawable object when ImageView sets this drawable, ImageView saves the mdrawable reference, and ImageView incoming this is mainactivity Mcontext, Because the static modified Mdrawable is the resident memory, Mainactivity is its indirect reference, Mainactivity is destroyed, can not be GC off, so caused by memory leaks.

Use context correctly

The memory leak caused by the general context is almost always when the context is destroyed, but because the reference causes the destruction to fail, and the application context object can be understood as the process exists, so we summarize the correct posture using the context:
1: When the context of the application can be fixed, and the life cycle of the object, priority to use the application context.
2: Do not allow objects with a life cycle longer than the activity to hold references to the activity.
3: Try not to use non-static inner classes in the activity, because non-static inner classes implicitly hold references to external class instances, and if you use static inner classes, the external instance references are held as weak references.

Summarize

In short, the status of the context in the Android system is very important, it is almost omnipotent, but it is not you want to use it casually, beware of improper use of memory problems caused by. If you have questions or want to know more, you can visit my: Video Course

For reference, read this article:
http://blog.csdn.net/guolin_blog/article/details/47028975
http://blog.csdn.net/yanbober/article/details/45967639

The context is not clear, how to do Android development?

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.