Get application context in any location

Source: Internet
Author: User

The context is required to access resources in the Android program, generally only in various component (Activity, provider, etc.) to easily use the API to get the context, and in some tool classes to get it is very troublesome. To do this, we can customize a application class to implement this functionality.

Import android.app.Application;

public class MyApplication extends application {
private static MyApplication instance;

public static MyApplication getinstance () {
return instance;
}

@Override
public void OnCreate () {
TODO auto-generated Method Stub
Super.oncreate ();
instance = this;
}
}

Then add Name= "MyPackage in the manifest <application>. MyApplication "You can use Myapplication.getinstance () in any class to get the application context.

(ii) Context considerations:

The context can do a lot of things in Android, but the mainfunction isLoad and AccessResources. There are two kinds of context in Android, one is application context, the other is activity context, and usually we pass the activity context between various classes and methods.
For example, an activity oncreate:
protected void OnCreate (Bundle state) {
Super.oncreate (state);

TextView label = new TextView (this); Pass context to view control
Label.settext ("Leaks is bad");

Setcontentview (label);
}
Passing the activity context to view means that view has a reference to activity that references the resources that the activity occupies: view hierachy, Resource, and so on.
So if the context happensMemory leaks, it will leak a lot of memory.
The leak here means that the GC has no way to reclaim the activity's memory.

Leaking an entire activity is a very easy thing to do.

WhenWhen the screen rotates,The system destroys the current activity and savesState information, and then create a new one.

For example, we wrote aApplicationprogram, it needs to load a large picture, we don't want to destroy this picture every time we rotate the screen, reload it. The simple idea of fulfilling this requirement isDefine a static drawable so that the activity class is created and destroyed it is always saved in memory.
Implementations similar to:
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 is bad");

if (Sbackground = = null) {
Sbackground = getdrawable (R.drawable.large_bitmap);
}
Label.setbackgrounddrawable (sbackground);//drawable attached to a view

Setcontentview (label);
}
}
The program looks simple, but it's a big problem. There is a leak when the screen rotates (that is, the GC cannot destroy the activity).
As we have just said, the system destroys the current activity when the screen is rotated. However, when drawable is associated with a view, Drawable saves the view's reference, that is, Sbackground holds a reference to the label, and the label holds the activity's reference. Since drawable cannot be destroyed, neither the reference nor the indirect reference can be destroyed, so that the system has no way to destroy the current activity, resulting in a memory leak. The GC is powerless against this type of memory leak.

The way to avoid this kind of memory leak is to avoid anythe life cycle of an object is longer than the activity, and the activity cannot be destroyed properly because of the object's reference to activity. We can use application context. Application context accompanies application's lifetime, irrespective of the life cycle of the activity. Application context can be obtained by Context.getapplicationcontext or Activity.getapplication method .

To avoid context-related memory leaks, keep the following points in mind:
1. Do not allow objects with long life cycles to refer to the activity context, which guarantees that the object referencing the activity is the same as the activity itself life cycle
2. For objects with long life cycles, you can use the application context
3. Avoid non-static internal classes, use static classes as much as possible, avoid life cycle problems, and note the life cycle changes caused by internal classes to external object references

(iii) Obtaining the context of other packages

Android has a context concept that everyone knows. Context can do a lot of things, open activity, send broadcasts, open folders and databases under this package, get classloader, get resources, and so on. If we get a context object for a package, we can basically do most of the things we can do with this package.

So can we get it? I'm glad to tell you, can!
The context has a Createpackagecontext method that can create another package, which is different from its own instance of the context, but the function is the same.


This method has two parameters:
1. PackageName package name, to get the context of the package name
2. Flags flag, with Context_include_code and context_ignore_security two options. Context_include_code means including code, which means that the code inside the package can be executed. Context_ignore_security means ignoring security warnings, and if you do not add this flag, some features are not available and a security warning appears.


Here's a small example of how to execute a class within another package.
The package name of the other package is Chroya.demo, the class name is main, the method name is print, and the code is as follows:

  1. Package Chroya.demo;
  2. Import android.app.Activity;
  3. Import Android.os.Bundle;
  4. Import Android.util.Log;
  5. Class Main extends Activity {
  6. @Override
  7. public void OnCreate (Bundle savedinstancestate) {
  8. super.oncreate (savedinstancestate);
  9. }
  10. public void print (String msg) {
  11. LOG.D ("Main", "msg:" + msg);
  12. }
  13. }
Package Chroya.demo;import Android.app.activity;import Android.os.bundle;import android.util.log;class Main extends Activity {@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);} public void print (String msg) {log.d ("Main", "msg:" + msg);}}

This package calls the code block of Main's print method as follows:

    1. Context c = createpackagecontext ( " Chroya.demo ",  context.context_include_code | context.context_ignore_security);  
    2. //loaded in this class   
    3. class clazz =  C.getclassloader (). LoadClass (
    4. //Create a new instance   
    5. object owner = clazz.newinstance ();  
    6. //get the Print method, pass in parameters and execute   
    7. object obj =  Clazz.getmethod ( Class). Invoke (Owner,  "Hello");   
Context C = createpackagecontext ("Chroya.demo", Context.context_include_code | context.context_ignore_security);//load this class Clazz = C.getclassloader (). LoadClass ("Chroya.demo.Main");// Create a new instance of object owner = Clazz.newinstance ();//Get the Print method, pass in the parameter and execute object obj = Clazz.getmethod ("print", String.class). Invoke (owner, "Hello");

OK, so we call the print method of the main class of the Chroya.demo package, execute the result, and print out hello.

How, this is just a call to other packages of code example, we get to the context, can also do a lot of things, of course, the title of the bad things, or do not do as well.

Get application context in any location

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.