12月 022019
转载请注明原文地址:http://bcoder.com/java/android-plugin-develop-start-load-apk-and-invoke-method-by-reflecting
一、整体试验步骤
1.建立子apk,新建一个android应用项目,叫firstplugin
2.在java根目录下新建一个类,叫LoginImpl
3.在LoginImpl.java中实现一个静态方法, login(),此方法只输出一个Log
1 2 3 4 5 6 7 8 9 10 |
package com.zht.car.firstplugin; import android.util.Log; import android.widget.Toast; public class LoginImpl { public static void login(){ Log.i("LoginImpl", "login"); } } |
4.编译生成apk,push到手机的/sdcard目录,此处生成的文件名为firstplugin-debug.apk
5.开始建宿主apk,新建另外一个Android应用项目PlugInHostApp
6.在MainActivity的onCreate中增加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String dexOutputDir = getApplicationInfo().dataDir; String apkpath = "/sdcard/firstplugin-debug.apk"; DexClassLoader loader = new DexClassLoader(apkpath, dexOutputDir, null,getClass().getClassLoader()); try { Class<?> aClass = loader.loadClass("com.zht.car.firstplugin.LoginImpl"); Object aClassInstance = aClass.newInstance(); Method method = aClass.getMethod("login"); method.invoke(null, null); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } |
7.编译运行,看log中是否输出了login这个字符串
二、遇到的问题和解决方法
1.java.lang.ClassNotFoundException: Didn’t find class “com.zht.car.firstplugin.LoginImpl” on path错误
解决方法:
- 查看是否有访问外部存储目录的权限(笔者遇到的就是这个问题,程序不会在new DexClassLoader时报无权限访问或者找不到文件的错误,而会在loadClass时报找不到类的错误)
- 关闭Android Studio的Instant run选项,在菜单Settings->Build, Execution, Deployment中(笔者是在Ubuntu中使用Android Studio,没找到此选项)
Sorry, the comment form is closed at this time.