The concept of a context in Android must be known to all. The 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, then we can basically do most of the things that the package can do on its own.
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, but has the same functionality.
This method has two parameters:
1. PackageName package name, to get package name of context
2. Flags flag bit, with Context_include_code and context_ignore_security two options. Context_include_code means to include code, which means you can execute the code inside the package. Context_ignore_security means ignoring security warnings, if you do not add this flag, some features are not used, there will be security warnings.
Here's a small example of how to execute a class in another package.
The package name for another package is Chroya.demo, class name Main, method name print, and the code is as follows:
Java code
Copy Code code as follows:
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 of the call main's print method for this package is as follows:
Java code
Copy Code code as follows:
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 a new instance
Object owner = clazz.newinstance ();
Gets the print method, passes in the parameter, and executes the
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, we can do a lot of things, of course, the title of the bad, or do not do as well.