Context -- activity, communication messenger between applications

Source: Internet
Author: User

Context, which we often see in Android development, especially the parameter list of some methods. For example, the first parameter in maketext () in toast is context. In this case, context is the basis of Android. Only by mastering the concept and usage of context can we write better information.Code. Now let's take a look at the so-called context.

Context, if it is directly translated from the document, it is really professional: provides an interface for the global information of the application environment, and this interface is implemented by the abstract class, its execution is provided by the Android system, allowing us to obtain resources and types characterized by applications, and start application-level operations at the same time, such as starting activity, broadcasting, and receiving intent.

From this section, we can find that context is an abstract class used as an interface, and this interface provides the global information of the application, because it is provided by the Android system, most of the time, we can get it directly. This will be discussed below. Let's take a look at its usefulness. It allows us to obtain resources and types characterized by applications and start application-level operations at the same time. What does it mean? In general, we can get the resources and classes of other applications. For the next half of the sentence, we can temporarily ignore this because it is not the focus here.

I. Role of Context

The biggest function of context is that we can pass it to obtain resources and methods related to other activities or applications. It is equivalent to their references. We can get object encapsulation through references, this is also the basis of our object-oriented approach, so we mainly use it to load and access resources.

Ii. Context type There are two types of Context: Activity-context and application-activity. The difference between the two types is that their lifecycles are different, one is destroyed with the destruction of the activity, and the other is accompanied by the entire application. Given our previous experiences in learning Java, C ++, we will realize that, different lifecycles may lead to different behaviors and errors, which will be discussed later, because they must be noted when we use context. 1. Application-Context The reason for this is that it is troublesome because it requires some means to obtain it. The life cycle of application-context is the whole application. Therefore, you must be careful when using it. In most cases, avoid using it because it may cause memory leakage. Let's take an example. If we introduce an application-context in an activity, the application-context will not disappear when the activity is closed, because its lifecycle is longer than our activity, if only some data is used for calculation, but if this context is related to the creation of our activity, or it is related to the resources that we want to destroy in the activity, so the problem is big! Because our activity or image cannot be destroyed normally, because it is associated with application-context. If the memory associated with them cannot be released normally, the so-called memory leakage will occur. This problem is sometimes so obscure that we cannot perceive it at all, so we must abide by the relevant usage principles. Now we will use an example to illustrate how to obtain the application-context. To obtain the application-context, we can declare a subclass of the application first.

 
ClassAExtendsApplication {}

Now, we add something in this class to prove that we can use context to obtain related resources and methods of. This time we use a toast.

First, add the following content to Class:

String S = "hello";PublicString getstring (string Str) {s=STR;ReturnS ;}

Then we try to use the data and method of A in Activity B:

 
A A =(A) getapplicationcontext (); string s=A. s; s= A. getstring ("Hello word"); Toast. maketext (This, S, Toast. length_long). Show ();

Then we must register our application in our mainfest file:

 
<Application Android: Name = ". A"> </Application>

Note: There is no name for the open pplication in the at file starting with mainfes, because we generally only start an activity, not an application. Therefore, you can register the application name as a subclass A inherited from the application to display a toast normally. If this is not done, the following error may be reported: Android. App. application cannot be cast to.

In the above example, we can see that the resource and method of an application can be called in our activity through a subclass of application, but in fact it is completely unnecessary to declare a class, then, a new instance can do the same, but here we just want everyone to understand that context can indeed pass references to the relevant class and get the resources and methods of the relevant class through this reference, in addition, this context can even be converted to a specific subclass. Our getapplicationcontext () actually returns a context, which can be converted to a because the context passes the application-context, it is an application type, and Class A is a subclass of application. If the parent class is converted to a subclass, there will be a question here, that is, our parent class cannot be forcibly converted to a subclass, because the subclass may have methods that the parent class does not have. This conversion will cause problems, but we also know that, the sub-class can be converted to the parent class because the reference of the parent class can point to the sub-class So here we want to show that our context is really a reference.

The life cycle of application-context is the whole application, so if it is a resource that needs to exist throughout the application, we can put it into an application-context, then use the context to obtain the context.

2. Activity-Context As mentioned above, the life cycle of the context is as long as the activity that gets its reference. If the activity ends, the context will be released. It does not need to be obtained specially like the application-context above. You can use this in an activity to obtain the context of the current activity. Take the toast in the above example. maketext (this, S, toast. length_long ). show (), where this is the current activity-context. However, it is very dangerous to use this blindly, in an anonymous internal class, an error occurs if you only use this, because the internal class uses this to get the object reference of the internal class, rather than the reference of the external class, therefore, the class name must be used at this time. this method is especially important in button event listening. 3. Use Rules Because application-cntext may cause memory leakage, we generally use activity-context. The following are the rules for using the two: (1) Do not reference an object with a long life cycle to activity-context. Make sure that the reference is the same as the life cycle of ativity. For objects with a long life cycle, use application-context. If you want to display a component, such as toast, on an activity interface, pass the context of your activity as a parameter to toast, in this way, your activity and toast can be associated. However, if you want to set your toast in one activity, and then display it in another activity, remember, you can have two options:

 
Intent intent =NewIntent (activity1.This, Activity2.Class); Startactivity (intent );

This activity1 is the activity we want to display toast, and acticity2 is the activity we set toast.

However, if you want to call toast in activity1. show (). If you accept the toast returned by activity2, it is very simple to use the default style. If you really want to use a custom format, you can customize a layout file toast. XML, then, write the following sentence in your activity1:

Layoutinflater layout =Getlayoutinflater (); view= Layout. Inflate (R. layout. Toast,Null);

Remember, it must be switched after setcontentview (), otherwise an error will be reported, and it must be in the setcontentview () of the activity you want to display. If you put setcontentview () in activity2 () an error occurs, that is, a null pointer, because the layout elements only start to allocate memory after setcontentview (), and we only call the activity2 method and do not start activity2, note This.

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.