我正在尝试构建一个允许用户为应用安装其他插件的应用。我正在构建插件模块作为apk并尝试使用DexClassLoader在运行时加载这些类。
当我打电话给非活动课时,它运作正常。当我尝试启动一个活动时,它会给我一个错误,说找不到活动。您是否在AndroidManifest.xml中声明了活动?
有没有办法我可以从我的插件apk中包含资源才能正常工作?
public class MainActivity extends AppCompatActivity {
private DexClassLoader mDexClassLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadApk();
Button launchBtn = (Button) findViewById(R.id.launch_btn);
launchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mDexClassLoader != null) {
try {
//Works Fine
Class<?> clazz = mDexClassLoader.loadClass("com.dexplugintest.ToastTest");
Object object = clazz.newInstance();
Method toastMethod = clazz.getMethod("showToast", Context.class, String.class);
toastMethod.invoke(object, MainActivity.this, "Hello from test app!");
//Gives Error
Class calledClass = mDexClassLoader.loadClass("com.dexplugintest.PluginLaunchActivity");
Intent intent = new Intent(MainActivity.this, calledClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception exception) {
// Handle exception gracefully here.
exception.printStackTrace();
}
}
}
});
}
private void loadApk() {
File file = DexUtil.copyFileToInternal(this, "app-debug.apk");
if (file != null) {
File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);
mDexClassLoader = new DexClassLoader(file.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(),
null,
getClassLoader());
}
}
}