DexClassLoader与类间互相调用

 

两个APK,其中一个APK叫做CallmeTest, 其中定义了一个类Callme, 类中定义了一个函数CallmeFunc()

public class CallmeTest {

    public CallmeTest() {

    }

    public int CallmeFunc(int a, int b) {

        return a+b;

    }

}

那么在另外一个APK中如何去调CallmeFunc, 可以使用如下方法

public

        Intent intent = new Intent("com.test.android.callme", null);
        PackageManager pm = getPackageManager();
        final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
        ResolveInfo  rinfo    = list.get(0);
        ActivityInfo  ainfo    = rinfo.activityInfo;
        String div     = System.getProperty("path.separator");
        String packagename  = ainfo.packageName;
        String dexPath       = ainfo.applicationInfo.dataDir;
        String dexOutputDir  = getApplicationInfo().dataDir;
       
        DexClassLoader  loader = new DexClassLoader(dexPath, dexOutputDir,null,this.getClass().getClassLoader());
        {
         Class<?>  clazz = loader.loadClass(packagename + "Callme");
         Object obj = clazz.newInstance();
         Class[] params = new Class[2];
         params[0] = Integer.TYPE;
         params[1] = Integer.TYPE;
         Method action = clazz.getMethod("CallmeFunc", params);
         Integer ret = (Integer)action.invoke(obj, 1,2);
        } cache

 

另外一种方法是用接口去实现。

定义一个接口

public interface Plugin {

   public int CallmeFunc(int a, int b);

}

然后前面CallmeTest改为public class CallmeTest implements Plugin

在调用的APK中改为如下实现

try {

    Class<?>  clazz = loader.loadClass(packagename + "Callme");

    Plugin   plug = (Plugin)clazz.newInstance();

    Integer ret = plug.CallmeFunc(1,2)

查看JAVA class中函数签名

javap -s 类

你可能感兴趣的:(String,null,Integer,Class,action,interface)