0

我正在尝试构建一个允许用户为该应用程序安装其他插件的应用程序。我正在将插件模块构建为 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());
        }
    }
}
4

0 回答 0