我希望能够运行未作为应用程序的一部分安装在内存中的代码。我假设InMemoryDexClassLoader正是为此而创建的,所以我尝试使用它在同一个应用程序(甚至是同一个类)中执行一个方法,但是是从内存执行的。为此,我将APK本身加载到一个缓冲区中,并将该缓冲区提供给InMemoryDexClassLoader。但是,我得到了一个ClassNotFoundException。
public class Test {
public void loadSelf(Context c) {
try {
FileInputStream fis = new FileInputStream(c.getApplicationInfo().publicSourceDir);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, bytesRead);
}
baos.flush();
byte[] dex = baos.toByteArray();
ByteBuffer bb = ByteBuffer.allocate(dex.length);
bb.put(dex);
bb.position(0);
ClassLoader loader = new InMemoryDexClassLoader(bb, null);
Class thisClass = loader.loadClass(this.getClass().getName()); //ClassNotFoundException
Method method = thisClass.getMethod("sayHi", Context.class);
method.invoke(thisClass.newInstance(), c);
bb.clear();
return;
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayHi(Context c) {
Toast.makeText(c, "Hi!", Toast.LENGTH_LONG).show();
}
}对DexClassLoader执行完全相同的操作效果很好!有谁能理解出什么问题了吗?
//This works fine and shows the Toast
public class Test {
public void loadSelf(Context c) {
try {
ClassLoader loader = new DexClassLoader(c.getApplicationInfo().publicSourceDir, null, null, null);
Class thisClass = loader.loadClass(this.getClass().getName());
Method method = thisClass.getMethod("sayHi", Context.class);
method.invoke(thisClass.newInstance(), c);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayHi(Context c) {
Toast.makeText(c, "Hi!", Toast.LENGTH_LONG).show();
}
}发布于 2020-04-21 06:09:45
我也遇到过类似的事情
然后我添加了这一行
minifyEnabled true到app.gradle的这一部分
android {
buildTypes {
debug {
minifyEnabled true
useProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt')
}
}
}此外,您还可以添加下面的依赖项
dependencies {
compile 'com.android.support:multidex:1.0.0'
}希望能对你有所帮助
https://stackoverflow.com/questions/61332498
复制相似问题