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:
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);
- }
- }
This package calls the code block of Main's print method as follows:
Java code
- Context C = createpackagecontext ("Chroya.demo", Context.context_include_code | context.context_ignore_security);
- Loaded in this class
- Class clazz = C.getclassloader (). LoadClass ("Chroya.demo.Main");
- Create a new instance
- Object owner = clazz.newinstance ();
- Get the Print method, pass in the parameters 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.
Android--------Create a context for another package from avtivity in one package