Android_Context: androidcontext

Source: Internet
Author: User

Android_Context: androidcontext

Context may be the most commonly used element in Android applications, and it may also be the most misuse.

Context objects are so common and pass-and-use. They may easily generate situations that are not as expected. Loading resources, starting a new Activity, obtaining system services, obtaining internal file paths, and creating views (in fact, more than that) all require Context objects. What I (author of the original article) want to do is to provide you with some insights on how Context works, and to enable you to use Context more effectively in applications.

Context type

Not all context instances are equivalent. Depending on the components of the Android application, the context you access is slightly different.

Application-is a singleton running in your Application process. In Activity or Service, it can be obtained through the getApplication () function, or in the object inherited from context by the getApplicationContext () method. No matter what method you get, you always get the same instance in a process.


Activity/Service-inherits from ContextWrapper, which implements the same API as context, but calls these methods to the hidden Context instance, that is, the basic context we know. At any time, when the system creates a new Activity or Service instance, it also creates a new ContextImpl instance for all the heavy work. Each Activity and Service and their corresponding BASIC context are unique to each instance. ThereforeThis. getApplicationContext () and this. getApplcation () are the sameApplication singleton object


BroadcastReciver-it is neither context nor context in itself, but whenever a new broadcast arrives, the Framework transmits a context object to onReceive (). This context is a ReceiverRestrictedContext instance. It has two main functions: registerReceiver () and bindService (). The two functions are not allowed to be called in BroadcastReceiver. onReceive. Each time the Receiver processes a broadcast, the passed context is a new instance.


ContentProvider-it is not a Context, but it can give you a Context object through the getContext () function.If ContentProvider is in the caller's local location (for example, in the same Application process), getContext () will return the Application Singleton.. However,If you call this ContentProvider in different processes, it will return a newly created instance representing the package that this Provider runs.


Save reference

First, we need to solve the problem by saving a context reference within an object or class, but its lifecycle exceeds the lifecycle of the object it saves the reference. For example, to create a custom Singleton, you need a context to load resources or obtain ContentProvider to save a reference pointing to the current Activiy or Service in the singleton.

Bad Singleton

[Java]View plaincopy
  1. Public class CustomManager {
  2. Private static CustomManager sInstance;
  3. Public static CustomManager getInstance (Context context ){
  4. If (sInstance = null ){
  5. SInstance = new CustomManager (context );
  6. }
  7. Return sInstance;
  8. }
  9. Private Context mContext;
  10. Private CustomManager (Context context ){
  11. MContext = context;
  12. }
  13. }

The problem here is that we do not know where the context comes from, and it is not safe to save a reference that ultimately points to Activity or Servece. This is a problem because a singleton maintains a unique static reference within the class, which means our object and all other objects it references, it will never be recycled. If the Context is an Activity, we will save all views related to the Activity and other large objects, resulting in Memory leakage.

To solve this problem, we modify the singleton to always save the Application context:

Improved singleton:

[Java]View plaincopy
  1. Public class CustomManager {
  2. Private static CustomManager sInstance;
  3. Public static CustomManager getInstance (Context context ){
  4. If (sInstance = null ){
  5. // Always pass in the Application Context
  6. SInstance = new CustomManager (context. getApplicationContext ());
  7. }
  8. Return sInstance;
  9. }
  10. Private Context mContext;
  11. Private CustomManager (Context context ){
  12. MContext = context;
  13. }
  14. }

In this example, there is no relation between Context and Context, because it is safe to store references here. Application Context itself is a Singleton, So we create another static reference without causing any memory leakage. Another good example is to save the reference of Context in the background thread or a waiting Handler. You can also use this method.


Why can't we always reference Application context? As mentioned above, referencing Application context never worries about memory leakage. The answer to the question, as I mentioned in my first introduction, is that different contexts are not equivalent.


Context capabilities

The general operation that Conext can do depends on the source of the context. The following table lists the common scenarios in which context objects are received in an application, and the applicable scenarios:

  Application Activity Service ContentProvider BroadcastReceiver
Show a Dialog NO YES NO NO NO
Start an Activity NO1 YES NO1 NO1 NO1
Layout Inflation NO2 YES NO2 NO2 NO2
Start a Service YES YES YES YES YES
Bind to a Service YES YES YES YES NO
Send a Broadcast YES YES YES YES YES
Register BroadcastReceiver YES YES YES YES NO3
Load Resource Values YES YES YES YES YES


Note: NO1 indicates that Application context can indeed start an Activity, but it needs to create a new task. This may meet some specific requirements, but an unstandard back stack will be created in your application. This is generally not recommended or is not a good practice.

NO2 indicates that this is illegal, but this filling (inflation) can indeed be completed, but it uses the default theme of the running system, rather than the theme defined by your app.

Above Android4.2, if the ipver is null (this is used to obtain the current value of sticky broadcast), this is allowed.

User Interface UI

From the preceding table, we can see that application context has many functions that are not suitable for implementation, and these functions are related to the UI. In fact, only the Activity can process all UI-related tasks. The functions of context instances in other categories are similar.

Fortunately, the three operations in the application do not need to be performed outside the Activity scope. This is probably because the android framework was designed in this way. Try to display a Dialog created using Aplication context, or start an Activity using Application context. The system will throw an exception and cause your application to crash, it is very strong to tell you that something is wrong.


An obvious problem is the inflating layout ). If you have read Layout inflation from my previous article, you know that it may be a very mysterious process, along with some hidden behaviors. Using the correct context is related to one of the actions. When you use Application context to inflate a layout, the Framework does not report errors and returns a perfect view created using the default system topic, instead of considering your applicaiton custom theme and style. This is because Acitivity is the only Context bound to the topic defined in the manifast file. Other Context instances use the default system topic to inflater your view. The result is not what you want.


Rule Intersection

Some readers may have come to the conclusion that two rules conflict with each other. In some cases, in some Application designs, we may have to save a reference for a long time and save an Activity to complete the work related to the UI. If this happens, I strongly recommend that you reconsider your design. It will be a good "anti-framework" teaching material.


Rule of thumb

In most cases, Context can be directly obtained within the organization you work on. As long as the reference does not exceed the lifecycle of the component, you can safely Save the reference. Once you want to save a context reference that exceeds the lifecycle of your Activity or Service, or even temporarily, You need to convert your reference to Application context.

If a new process is specified for the component, the Application will be instantiated again.


In Android development, how can Context concepts, functions, and usage be obtained in common classes?

Package com. jq. sort;
Import com. ui. entity. User;
Public class UserItem extends LinearLayout implements OnClickListener {

Private Context context;
Private LinearLayout;
Public UserItem (Context context, AttributeSet attrs ){
Super (context, attrs );
This. context = context;
}
Public void setUsers (User u ){
This. u = u;
}
Public void initView (){
FillView ();
}
Public void fillView (){
If (u = null ){
Return;
}
Discount. setText (DistanceUtil. getDistanceDesc (
Double. parseDouble (SessionManager. getInstance (). getLng ()),
Double. parseDouble (SessionManager. getInstance (). getLat ()),
Double. parseDouble (u. getLng (), Double. parseDouble (u. getLat ())));
}
@ Override
Public void onClick (View v ){
If (v. getId () = R. id. LinearLayout ){
Intent intent = new Intent (context, FriendsInfoUI. class );
Intent. putExtra ("User", u );
Intent. putExtra ("distance", discount. getText (). toString ());
Context. startActivity (intent );
}
}
}
 
What is the role of context in android?

Context literally refers to the Context, which is located in the android. content. Context of the framework package. In fact, this class is of the LONG type, similar to the Handle in Win32. Many methods need to use Context to identify the caller's instance. For example, the first parameter of Toast is Context. Generally, this is directly used in the Activity to represent that the caller's instance is Activity, when the onClick (View view) method of a button is used, an error is reported when this method is used. Therefore, ActivityName may be used. this is mainly because the classes that implement Context mainly have several models unique to Android, Activity and Service.

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 you to obtain resources and types characterized by applications. Start application-level operations at the same time, such as starting Activity, broadcasting, and receiving intents.

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.