Obtain the application context from any location

Source: Internet
Author: User

AndroidProgramTo access resources, you must provide context. Generally, only,
Provider, etc.) in order to conveniently use the API to obtain the context,
In some tool classes, it is very troublesome to obtain them. Therefore, we can customize an application class to implement this function.

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. myapplication" to <Application> in manifest to obtain the application context using myapplication. getinstance () in any class.

(2) Context considerations:

In Android, context can perform many operations, but the most important Function Yes 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, oncreate of an activity:
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.
In this case, if context occursMemory If it is disclosed, a lot of memory will be leaked.
This vulnerability indicates that GC cannot recycle activity memory.

Leaking an entire activity is an easy task.

When Screen When rotating, System Destroys the current activity and saves it. Status Information, and then create a new one.

For example, we write Application Program It needs to load a large image. We don't want to destroy this image every time we rotate the screen and reload it. The simple idea of implementing this requirement is Definition 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 ).
Me
We just said that when the screen is rotated, the system will destroy the current activity. However, when drawable is associated with the view, drawable saves
Reference, that is, sbackground saves the reference of label, while label saves the reference of activity. Since drawable cannot be destroyed
Both references and indirect references cannot be destroyed, so that the system cannot destroy the current activity, resulting in Memory leakage. GC is powerless for this type of Memory leakage.

To avoid Memory leakage, avoid any Object Of
The lifecycle of an activity is longer than that of an activity. We 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 implemented through context. getapplicationcontext or activity. getapplication.Obtain .

To avoid Memory leakage related to context, remember the following points:
1. Do not make an object with a long life cycle reference the activity context. That is, make sure that the object that references the activity has the same life cycle as the activity itself.
2. For objects with a long life cycle, you can use 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.

(3) obtain the context of another package


Android has the concept of context, which must be known to everyone. Context can do many things, such as opening activity, sending broadcast, opening folders and databases under this package,
Obtain classloader and resources. If we get the context object of a package, we can basically do most of what this package can do.

Can we get it? I'm glad to tell you, yes!
Context has a createpackagecontext method to create the context of another package. This instance is different from its own context instance, but has the same function.


This method has two parameters:
1. Packagename package name. Obtain the package name of the context.
2. Flags
Flag, which has two options: context_include_code and context_ignore_security.
Context_include_code indicates to includeCodeIn other words, you can execute the code in this package. Context_ignore_security
Ignore the security warning. If this flag is not added, some functions will not be used and a security warning will appear.


The following is a small example to execute a class method in another package.
The package name of another package is chroya. Demo, the class name is main, and the method name is print. The Code is as follows:

Java code
  1. PackageChroya. Demo;
  2. ImportAndroid. App. activity;
  3. ImportAndroid. OS. Bundle;
  4. ImportAndroid. util. log;
  5. ClassMainExtendsActivity {
  6. @ Override
  7. Public VoidOncreate (bundle savedinstancestate ){
  8. Super. Oncreate (savedinstancestate );
  9. }
  10. Public VoidPrint (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 );}}

The code block for calling the print method of main in this package is as follows:

Java code
  1. Context c = createpackagecontext ("Chroya. Demo", Context. context_include_code | context. context_ignore_security );
  2. // Load this class
  3. Class clazz = C. getclassloader (). loadclass ("Chroya. Demo. Main");
  4. // Create an instance
  5. Object owner = clazz. newinstance ();
  6. // Obtain the print method, input parameters, and execute
  7. Object OBJ = clazz. getmethod ("Print", String.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 an instance object owner = clazz. newinstance (); // obtain the print method, input parameters, and execute object OBJ = clazz. getmethod ("print", String. class ). invoke (owner, "hello ");

OK. In this way, the print method of the main class of the chroya. Demo package is called, and the execution result is hello.

How about it? This is just an example of calling the code of other packages. We can get context and do a lot of things. Of course, the bad things mentioned in the question should not be well done.

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.