安卓动态加载jar实现类似热更新功能

2019-10-15  本文已影响0人  justcodeit

1.将类转换成jar包,具体见  AndroidStudio 将类打包成jar

2.将打包好的jar转换成可以被Dalvik虚拟机识别的dex文件

拷贝jar文件到 build-tools下面

shift + 鼠标右键打开命令行,输入dx --dex --output=qula_dex.jar qula.jar

执行成功后

qula_dex.jar就是我们要动态加载的dex

3.创建assets目录将我们的qula_dex.jar文件放到此目录下面

4.创建一个FileUtils工具类用来将assets目录下的qula_dex.jar copy到app/data/cache目录下 源码如下

public class FileUtils {

public static void copyFiles(Context context, String fileName, File desFile) {

InputStream in =null;

OutputStream out =null;

try {

in = context.getApplicationContext().getAssets().open(fileName);

out =new FileOutputStream(desFile.getAbsolutePath());

byte[] bytes =new byte[1024];

int i;

while ((i = in.read(bytes)) != -1){

out.write(bytes,0, i);

}

}catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (in !=null)

in.close();

if (out !=null)

out.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

public static boolean hasExternalStorage() {

return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

}

/**

    * 获取缓存路径

    * @param context

    * @return 返回缓存文件路径

    */

    public static File getCacheDir(Context context) {

File cache;

if (hasExternalStorage()) {

cache = context.getExternalCacheDir();

}else {

cache = context.getCacheDir();

}

if (!cache.exists()){

cache.mkdirs();

}

return cache;

}

}

5.执行测试

/**

* 加载dex文件中的class,并调用其中的sayHello方法

*/

private void loadDexClass() {

File cacheFile = FileUtils.getCacheDir(context);

String internalPath = cacheFile.getAbsolutePath() + File.separator +"qula_dex.jar";

File desFile =new File(internalPath);

try {

if (!desFile.exists()) {

desFile.createNewFile();

FileUtils.copyFiles(context,"qula_dex.jar", desFile);

}

}catch (IOException e) {

e.printStackTrace();

}

//下面开始加载dex class

    DexClassLoader dexClassLoader =new DexClassLoader(internalPath,

cacheFile.getAbsolutePath(),null,context.getClassLoader());

try {

//加载的类名为jar文件里面完整类名,写错会找不到此类hh

        Class libClazz = dexClassLoader.loadClass("com.justcodeit.xiaoshuo.netbook.BookFactory_qula");

loadBook = (IBookLoadFactory) libClazz.newInstance();

if (loadBook !=null)

Toast.makeText(context,"版本号" +loadBook.getVersion(), Toast.LENGTH_LONG).show();

}catch (Exception e) {

e.printStackTrace();

}

}

上一篇下一篇

猜你喜欢

热点阅读