美文网首页Android开发Android 开发技术分享安卓开发博客
Android 动态加载sd卡的jar文件实现更新jar方法

Android 动态加载sd卡的jar文件实现更新jar方法

作者: umbrella1 | 来源:发表于2018-10-25 22:17 被阅读16次
微信图片_20181030105449.png

如何实现集成的Jar包动态更新,实现不需要更新Jar打包APK发布,就能解决线上的问题修复。
一、介绍
Android在API中给出可动态加载的有:DexClassLoader 和 PathClassLoader
DexClassLoader:可从SD卡中加载jar、apk和dex.
PathClassLoader:只能加载已经安装搭配Android系统中的apk文件。
这两个都是集成dalvik.system.BaseDexClassClassLoader,
当类加载请求,首先委派给父类去完成加载,父类加载不了,则自己再去完成加载,我们可以利用这个机制反过来,自定义TestClassLoader去加载本地Jar里接口Impl实现类(修复问题的class),如果加载不了,再请求到父类即(PathClassLoader)去加载工程里的Jar接口Impl实现类。

二、实现步骤
1、首先我们在Jar中定义好接口及实现类Impl,

public interface IJarFix {
    void print();
}
public class IJarFixImpl implements IJarFix {
    @Override
    public void print() {
        Log.e("umbrella1","print version 1.0");
    }
}

2、自定义TestClassLoader:

import dalvik.system.BaseDexClassLoader;
public class TestClassLoader extends BaseDexClassLoader {
    private Map<String, String> mExcludes = new ConcurrentHashMap<>();
 public TestClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
        super(dexPath, optimizedDirectory, librarySearchPath, parent);
    }
    public void setExcludedClasses(String[] classNames) {
        mExcludes.clear();
        if (classNames != null && classNames.length > 0) {
            for (String name : classNames) {
                // ConcurrentHashMap doesn't allow null key or value
                if (name != null) {
                    mExcludes.put(name, name);
                }
            }
        }
    }
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        Class<?> c = findLoadedClass(name);
        if(c == null){
            if (!mExcludes.containsKey(name)) {//这边目的是不要去加载接口IJarFix(这个是PatchClassLoader加载)
                try {
                    c = findClass(name);
                } catch (Exception e) {
                    // Not found within the module, continue on
                }
            }
        }
        if(c == null)
            c = getParent().loadClass(name);//父classloader
        return c;
    }
}

TestClassLoader加载本地JAR

package cn.umbrella.mylibrary;
public class Modul {
    public static final String TEMP_DEX_FILE_NAME ="IJarHotDex.jar";
    //------加载是jar包(包含classes.dex)----//
    public static ClassLoader createTestClassLoader(Context cxt){
        ClassLoader parentLoader = cxt.getClassLoader();
        File file = new File(cxt.getDir("dex",Context.MODE_PRIVATE),TEMP_DEX_FILE_NAME);
        File copyFile = getTempDexFile(cxt);
        FileUtil.copy(copyFile,file);
        File dexLib= cxt.getDir("outdex", Context.MODE_PRIVATE);
        FileUtil.ensureDir(dexLib,false);`
        TestClassLoader testClassLoader = new TestClassLoader(file.getPath(),dexLib,null,parentLoader);
        return testClassLoader;
    }
    public static File getTempDexFile(Context cxt) {
        try {
            String tempDexPath = FileUtil.getExternalStoragePath(cxt);
            String tempDexFilePath = tempDexPath + TEMP_DEX_FILE_NAME;
            Log.e("yuguohe", "tempDexFilePath:" + tempDexFilePath);
            File tempDexFileDir = new File(tempDexPath);//存放在SD卡上的临时dex文件的所在目录
            if (!tempDexFileDir.exists() || !tempDexFileDir.isDirectory()) {
                if (!tempDexFileDir.mkdirs()) {
                    return null;
                }
            }
            File tempDexFile = new File(tempDexFilePath);//存放在SD卡上的临时dex文件
            if (!tempDexFile.exists()) {
                if (!tempDexFile.createNewFile()) {
                    return null;
                }
            }
            return tempDexFile;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

生产JAR
task makeJar(type: Copy) {
//删除存在的
delete 'build/libs'
//设置拷贝的文件
from('build/intermediates/bundles/default/')
//打进jar包后的文件目录
into('build/libs/')
//将classes.jar放入build/libs/目录下
//include ,exclude参数来设置过滤
//(我们只关心classes.jar这个文件)
include('classes.jar')
//重命名
rename ('classes.jar', 'IJarHotDex_o.jar')
}
然后在D:\android-sdk\build-tools\23.0.1\目录下使用命令 dx --dex --output=IJarHotDex_o.jar IJarHotDex.jar,IJarHotDex.jar我们所需要的二进制jar包(包含class.dex),放在后台下载下来或SD卡上。
3、实现动态加载

try {
                    JarInfFactory infFactory = JarInfFactory.getInstance();
                    infFactory.init(MainActivity.this);
                    cn.umbrella.mylibrary.IJarFix jarFix = infFactory.getIHotFix();
                    Log.e("umbrella1", "jarFix=" + jarFix + " &classLoader=" + jarFix.getClass().getClassLoader());
                    jarFix.print();
                } catch (Exception e) {
                    e.printStackTrace();
                }

JarInfFactory接口抽象工厂类:

package cn.umbrella.mylibrary;
import android.content.Context;
import android.util.Log;
public class JarInfFactory {
    private static JarInfFactory mInstance = null;
    private IJarFix mIJarFix;
    private Context mContext;
  ModulManager mModulManager;
    public static synchronized JarInfFactory getInstance() {
        if (mInstance == null) {
            mInstance = new JarInfFactory();
        }
        return mInstance;
    }

    public void setExcludedClasses(){
        String ex[] = new String[] {
                "cn.umbrealla.mylibrary.IJarFix",
        };
        if(mModulManager != null)
            mModulManager.setExcludedClasses("ssp", ex);
    }
    public IJarFix getIHotFix(){
        if(mIJarFix == null){
            mIJarFix =mModulManager.getModuleInterface("ssp",IJarFix.class,null,null,null);
        }
        return mIJarFix;
    }
    public void setInvalide(){
        if(mIJarFix != null){
            mIJarFix = null;
        }
        String ex[] = new String[] {
                "cn.umbrealla.mylibrary.IJarFix",//接口
        };
        mModulManager.setExcludedClasses("ssp", ex);
        mModulManager.addClassLoaderModuleName("ssp");
        getIHotFix();
    }
}
package cn.umbrella.mylibrary;
public class ModulManager {
    private ArrayList<ClassLoader>mClassLoaderList = new ArrayList<>();
    private Context mContext;
    public void addClassLoaderList(ClassLoader loader){
        mClassLoaderList.clear();
        mClassLoaderList.add(loader);
    }
    public ModulManager(Context cxt){
        mContext = cxt;
    }
    public <T> T getModuleInterface(String moduleName,Class<T> interfaceType,
                                    String staticMethod,
                                    Class<?>[] paramTypes, Object[] paramObjs){
        Context cxt = mContext;
        ClassLoader c1 = null;
        c1 = getClassLoaderCache();
        if(c1 == null) {
            c1 = ModulManager.class.getClassLoader();
        }
        try {
            return Util.newInstance(c1, interfaceType.getName() + "Impl", null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void addClassLoaderModuleName(String moduleName){
        Context cxt = mContext;
        ClassLoader loader = Modul.createTestClassLoader(cxt);
        updateExcludedClasses(loader,getExcludedClasses(moduleName));
        addClassLoaderList(loader);
    }

    public ClassLoader getClassLoaderCache(){
        if(mClassLoaderList!=null && mClassLoaderList.size() > 0)
            return mClassLoaderList.get(0);
        return null;
    }
    public void updateExcludedClasses(ClassLoader cl, String[] classNames) {
        if (cl instanceof TestClassLoader) {
            ((TestClassLoader) cl).setExcludedClasses(classNames);
        }
    }
}

反射工具类:

package cn.umbrella.mylibrary;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by yuguohe on 2018-8-3.
 */

public class Util {
    public static <T> T newInstance(ClassLoader classLoader,String className,Class<?>[] paramTypes, Object[] paramObjs){
        T clT = null;
        try {
            Class<?> c = classLoader.loadClass(className);
            Constructor constructor = c.getConstructor(paramTypes);
            clT = (T)constructor.newInstance(paramObjs);
            if(clT == null)
                clT = (T)c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return clT;
    }
}

实现本地JAR方法替代工程集成的JAR的方法:

           JarInfFactory infFactory = JarInfFactory.getInstance();
                 infFactory.setInvalide();
                    IJarFix o = infFactory.getIHotFix();
                    Log.e("umbrella1", "jarFix=" + o + " &classLoader=" + o.getClass().getClassLoader());
                    o.print();
                    Log.e("umbrella1", "o=" + o);
微信图片_20181024173206.png

相关文章

网友评论

    本文标题:Android 动态加载sd卡的jar文件实现更新jar方法

    本文链接:https://www.haomeiwen.com/subject/derxtqtx.html