Android 動態(tài)加載sd卡的jar文件實現(xiàn)更新jar方法

微信圖片_20181030105449.png

如何實現(xiàn)集成的Jar包動態(tài)更新,實現(xiàn)不需要更新Jar打包APK發(fā)布,就能解決線上的問題修復(fù)。
一、介紹
Android在API中給出可動態(tài)加載的有:DexClassLoader 和 PathClassLoader
DexClassLoader:可從SD卡中加載jar、apk和dex.
PathClassLoader:只能加載已經(jīng)安裝搭配Android系統(tǒng)中的apk文件。
這兩個都是集成dalvik.system.BaseDexClassClassLoader,
當類加載請求,首先委派給父類去完成加載,父類加載不了,則自己再去完成加載,我們可以利用這個機制反過來,自定義TestClassLoader去加載本地Jar里接口Impl實現(xiàn)類(修復(fù)問題的class),如果加載不了,再請求到父類即(PathClassLoader)去加載工程里的Jar接口Impl實現(xiàn)類。

二、實現(xiàn)步驟
1、首先我們在Jar中定義好接口及實現(xiàn)類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;
    }
}

生產(chǎn)JAR
task makeJar(type: Copy) {
//刪除存在的
delete 'build/libs'
//設(shè)置拷貝的文件
from('build/intermediates/bundles/default/')
//打進jar包后的文件目錄
into('build/libs/')
//將classes.jar放入build/libs/目錄下
//include ,exclude參數(shù)來設(shè)置過濾
//(我們只關(guān)心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、實現(xiàn)動態(tài)加載

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;
    }
}

實現(xiàn)本地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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容