代码之家  ›  专栏  ›  技术社区  ›  sehugg

Android远程代码加载

  •  16
  • sehugg  · 技术社区  · 17 年前

    我正在为Android开发一个库,该库需要来自中央服务器的频繁更新。我在想,如果我的库可以自我更新,或者我可以发布一个引导库,在安装应用程序时下载目标库,那该有多好。

    我在1.5中看到了这个名为“DexClassLoader”的类,但除了API文档之外,网络上似乎没有什么珍贵的东西。有人成功地将其用于我描述的场景吗?

    3 回复  |  直到 17 年前
        1
  •  13
  •   Chris Boyle    16 年前

    DexClassLoader dexOutputDir 这实际上是你的应用程序可以写的,所以 不 /data/dalvik-cache ClassNotFoundException .

    cl = new DexClassLoader("/full/path/com.example.apk",
                            getFilesDir().getAbsolutePath(),// /data/data/foo/files
                            null,  // native lib path, I haven't used this
                            MyClass.class.getClassLoader());
    // This doesn't make Class.forName() work, instead I do this:
    Class<?> foo = cl.loadClass("com.example.foo");
    

    作出 Class.forName() 工作,你可以试试 Thread.setContextClassLoader()

        2
  •  3
  •   Lucas S.    17 年前

    事实上,你想要的是支持和工作。 对我来说,它没有按预期工作,但以下代码工作正常。

    DexFile df = new DexFile(new File("/data/app/my_downloaded_lib.apk"));
    ClassLoader cl = getClassLoader();
    Class clazz = df.loadClass("com/my/lib/MyClass", cl);
    

        3
  •  2
  •   fadden    13 年前

    DexClassLoader 这是正确的答案。应用程序永远不应该使用 DexFile

    您可以使用外部存储( /sdcard ),或应用程序的私人数据区域,用于 dexOutputDir 参数。外部存储通常更大,但如果卡被弹出,你的应用程序将被终止,并且由于缺乏文件权限执行,第三方很容易替换你的代码。这可能会让恶意应用程序导致您的应用程序执行任意操作。(如果你想这样做,请通过以下路径 Environment.getExternalStorageDirectory() WRITE_EXTERNAL_STORAGE 许可)

    Context.getFilesDir() )更安全,如果卸载应用程序,也有自动清理的优点。这是推荐的方法。

    推荐文章