跳到主要内容

调用dex

package top.arick.stage;


import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;
import top.arick.test.R;

public class Load {

public static boolean moveDex(Context context){

try {
// 获取应用的内部存储目录
Log.i("arick Load", "moveDex: 开始移动");
File dexInternalStoragePath = new File(context.getDir("dex", 0), "stage.dex");
// 打开应用资源中的 DEX 文件
InputStream inputStream = context.getResources().openRawResource(R.raw.stage);
FileOutputStream outputStream = new FileOutputStream(dexInternalStoragePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
Log.i("arick Load", "moveDex: " + dexInternalStoragePath.getAbsolutePath());

} catch (IOException e) {
Log.e("arick Load", "moveDex: " + e.getMessage());
return false;
}
return true;

}

public static void loadDex(Context context){
Log.i("arick Load", "loadDex: 开始加载");
File dexFile = new File(context.getDir("dex", 0), "stage.dex");
boolean isFileExist = false ;
// 检查文件是否存在
if (!dexFile.exists()) {

isFileExist = Load.moveDex(context);
}else{
isFileExist = true;
}
if (!isFileExist) {
return;
}
Log.i("arick Load", "start: DexClassLoader");
DexClassLoader dexClassLoader = new DexClassLoader(
dexFile.getAbsolutePath(),
context.getDir("dex", 0).getAbsolutePath(),
null,
context.getClassLoader()
);

try {
// 例如,目标类为 com.example.MyClass
Class<?> clazz = dexClassLoader.loadClass("top.arick.stage.MainService");

Object instance = clazz.newInstance();
Method method = clazz.getMethod("startService",Context.class);
//method.invoke(instance,context);

// 获取静态方法(方法名:startService)
Method method2 = clazz.getMethod("startService",Context.class);
// 调用静态方法
method.invoke(null,context);
Log.i("arick Load", "loadDex: 加载成功");
} catch (Exception e) {
e.printStackTrace();
Log.i("arick Load", "loadDex: 加载失败");
}
}
}

DexClassLoader dexClassLoader = new DexClassLoader(optimizedDexOutputPath.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null, getClassLoader());
Class libProviderClazz = null;
try{
libProviderClazz=dexClassLoader.loadClass("com.dexclassloader.MyLoader");
// 遍历类里所有方法
Method[]methods=libProviderClazz.getDeclaredMethods();
for(int i=0;i<methods.length;i++){
Log.e(TAG,methods[i].toString());
}
Method start=libProviderClazz.getDeclaredMethod("func");// 获取方法
start.setAccessible(true);// 把方法设为public,让外部可以调用
String string=(String)start.invoke(libProviderClazz.newInstance());// 调用方法并获取返回值
Toast.makeText(this,string,Toast.LENGTH_LONG).show();
}catch(Exception exception){
// Handle exception gracefully here.
exception.printStackTrace();
}