Android gets the Context instance code for other packages

  • 2020-05-19 05:53:17
  • OfStack

Android has the concept of Context, which I think you all know. Context can do many things, such as open activity, send broadcasts, open folders and databases under this package, get classLoader, get resources, and so on. If we get a package of Context objects, then we can basically do most of the things that the package itself can do.
Can we get it? I'm glad to tell you, yes!
Context has an createPackageContext method that creates a context for another package, which is different from its own Context instance, but has the same functionality.

This method takes two parameters:
1. packageName package name, get the Context package name
2. The flags flag bit has two options: CONTEXT_INCLUDE_CODE and CONTEXT_IGNORE_SECURITY. CONTEXT_INCLUDE_CODE means to include code, which means you can execute the code in the package. CONTEXT_IGNORE_SECURITY means ignore the security warning. Without this flag, some functions will not be used, and a security warning will appear.

For a small example, execute the methods of a class in another package.
The package name of the other 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 Main's print method 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");
// new 1 An instance 
Object owner = clazz.newInstance();
// To obtain 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 about, this is just an example of code that calls other packages, we get Context, we can do a lot of things, of course, the bad thing that they say, don't do it.


Related articles: