Android -------- create the Context of another package from avti.pdf in one 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, obtaining classLoader, and obtaining 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 that the code in this package can be executed. CONTEXT_IGNORE_SECURITY indicates that the security warning is ignored. If this flag is not added, some functions cannot 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
- Package chroya. demo;
- Import android. app. Activity;
- Import android. OS. Bundle;
- Import android. util. Log;
- Class Main extends Activity {
- @ Override
- Public 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
- Context c = createPackageContext ("chroya. demo", Context. CONTEXT_INCLUDE_CODE | Context. CONTEXT_IGNORE_SECURITY );
- // Load this class
- 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.
Other brilliant articles
Android learning notes (38) create a skin import dialog box using ProgressDialog
Large-scale website architecture design-Solr
Android learning notes (39) Message tips use Toast tips to show tips
Android learning notes (32) grid view (GridView) and graphics switcher (ImageSwi...
Android learning notes (31) List component (ExpandableListView)