Context in Android

Source: Internet
Author: User

I recently learned about Android. I have seen few articles on context, so I can check it online.

Context literally indicates the context, which is located in the android. content. in context, this type is actually long, 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, we directly use this instead of activity, which indicates that the caller's instance is activity. When a method such as onclick (view) of a button is used, an error is reported when this is used, so we may use activityname. this is mainly because the classes that implement context mainly have several models unique to Android, such as activity, service, and broadcastreceiver.

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.

  Two types of ContextIn Android, context can perform many operations, but the main function is to load and access resources. There are two types of context in Android: application context and activity context. Generally, activity context is transmitted between different types and methods. For example, the oncreate

protected void onCreate(Bundle state) {
super.onCreate(state);
 
TextView label = new TextView(this);
// Pass context to view Control

label.setText("Leaks are bad");
 
setContentView(label);
}

Passing the activity context to the view means that the view has a reference pointing to the activity and then referencing the resources occupied by the activity: View hierachy and resource. Memory leakageIn this way, if the context memory leaks, a lot of memory will be leaked. This vulnerability indicates that GC cannot recycle activity memory. Note: Why does GC fail to recycle the corresponding memory? I personally think it is because passing context increases the reference count of object pointers, so GC Based on smart pointer technology cannot release the corresponding memory. When the screen rotates, the system destroys the current activity, saves the status information, and creates a new one. For example, if we write an application that needs to load a large image, we do not want to destroy the image and reload it every time we rotate the screen. The simple idea of implementing this requirement is to define a static drawable, so that the activity class creation and destruction is always stored in the memory. Implementation is similar:

 

public class myactivity extends Activity {
private static Drawable sBackground;
protected void onCreate(Bundle state) {
super.onCreate(state);
 
TextView label = new TextView(this);
label.setText("Leaks are bad");
 
if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);//drawable attached to a view

setContentView(label);
}
}

 

This program looks very simple, but it has a big problem. When the screen is rotated, there will be a leak (that is, the GC cannot destroy the activity ). As we said earlier, when the screen is rotated, the system will destroy the current activity. However, when drawable is associated with the view, drawable saves the view reference, that is, sbackground saves the label reference, while the label stores the reference of the activity. Since drawable cannot be destroyed and neither referenced nor indirectly referenced by it can be destroyed, the system cannot destroy the current activity, resulting in Memory leakage. GC is powerless for this type of Memory leakage. To avoid Memory leakage, you can avoid the lifetime of any object in the activity from being longer than that of the activity.
The reference of the activity causes the activity to fail to be destroyed normally. To prevent memory leakage, pay attention to the following points:
  1. Do not reference an object with a long life cycle to the activity context, that is, ensure that the object that references the activity must have the same life cycle as the activity itself.
  2. For objects with a long life cycle, you can use the application context
  3. Avoid non-static internal classes and try to use static classes to avoid lifecycle issues. Pay attention to the lifecycle changes caused by internal class references to external objects.
Application ContextWe can use application context. Application context is associated with the life cycle of the application and has nothing to do with the life cycle of the activity. Application context can be obtained through context. getapplicationcontext or activity. getapplication. The method of making application context can be found here in the http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables/708317#708317 Java, usually using a static variable (such as Singleton) To synchronize the state between activities (between classes in the program. In Android, application context is used to associate these states. Every activity is context, which contains the running status. Similarly, the application also has a context. Android will ensure that this context is a unique instance. To create your own application context, You Need To Inherit Android. App. application, and then describe this class in the manifest of the app. Android will automatically help you create an instance of your class. Then you can use context. getapplicationcontext () to obtain the application context in each activity.

 class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }

The following describes some get methods of context. These get methods can be used to obtain the global information of the application environment:

1. Public abstract context getapplicationcontext ()

Return the context of the single, global application object of the current process.

2. Public abstract applicationinfo getapplicationinfo ()

Return the full application info for this context's package.

3. Public abstract contentresolver getcontentresolver ()

Return a contentresolver instance for your application's package.

4. Public abstract packagemanager getpackagemanager ()

Return packagemanager instance to find global package information.

5. Public abstract string getpackagename ()

Return the name of this application's package.

6. Public abstract resources getresources ()

Return a resources instance for your application's package.

7. Public abstract sharedpreferences getsharedpreferences (string name, int Mode)

Retrieve and hold the contents of the preferences file 'name', returning a sharedpreferences through which you can retrieve and modify its values. only one instance of the sharedpreferences object is returned to any callers for the same name, meaning they
Will see each other's edits as soon as they are made.

8. Public final string getstring (INT resid)

Return a localized string from the application's package's default string table.

9. Public abstract object getsystemservice (string name)

Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:

 

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.