Android热修复

Android热修复笔记
java--->class---jar--->dex
使用方法:1、运行修复的程序,
2、在build-->intermediates-->javac-->debug--->classes 在这个文件夹打开终端窗口运行 jar cvf fix.jar qzone/Fix.class
(javac -encoding UTF-8 qzone/Fix.java
或者
studio编译之后在build-intermediates-javac-debug-classes文件中查找)
3、得到jar之后,把classes的jar复制到sdk->build-tools->版本 中(dx)
使用 dx --dex --output=fix.dex fix.jar 命令 得到dex

image.png

image.png
image.png

image.png

FixUtil工具类

public class FixUtil {

    static String TAG="hotfix";

    public static void installPatch(Context context, String patchPath) {
        PsyP();
        File patchFile = new File(patchPath);
        if (!patchFile.exists()) {
            Log.e(TAG, "installPatch: " + patchPath + "无文件,无需修复");
            return;
        }
        File optDir = context.getCacheDir();
        try {
            // 1.得到当前程序的classLoader
            ClassLoader classLoader = context.getClassLoader();
            // 2.反射获取类加载器的pathList属性
            Field pathListField = getField(Class.forName("dalvik.system.BaseDexClassLoader"), "pathList");
            Object pathList = pathListField.get(classLoader);
            // 3.反射获取DexPathList中的dexElements
            Field dexElementsField = getField(pathList.getClass(), "dexElements");
            Object[] dexElements = (Object[]) dexElementsField.get(pathList);
            // 4.加载自己的dex,并转化为Element[]
            // 通过反射DexPathList 中的makeDexElements() 方法来实现
            // 4.1 反射获取makeDexElements方法
            Object[] patchElements = null;
            // 版本适配
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0+ 使用makeDexElements(List,File,List,ClassLoader)
                Method makeDexElementsMethod = getMethod(pathList.getClass(), "makeDexElements", List.class, File.class, List.class, ClassLoader.class);
                List dexFileList = new ArrayList<>();
                dexFileList.add(patchFile);
                ArrayList suppressedExceptions = new ArrayList();
                patchElements = (Object[]) makeDexElementsMethod.invoke(null, dexFileList, optDir, suppressedExceptions, classLoader);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Android 6.0-7.0 使用makePathElements(List,File,List)
                Method makePathElements = getMethod(pathList.getClass(), "makePathElements", List.class, File.class, List.class);
                List dexFileList = new ArrayList<>();
                dexFileList.add(patchFile);
                ArrayList suppressedExceptions = new ArrayList();
                patchElements = (Object[]) makePathElements.invoke(null, dexFileList, optDir, suppressedExceptions);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Android 5.0-6.0 使用makeDexElements(ArrayList,File,ArrayList)  注意这里参数编程ArrayList类型
                Method makeDexElementsMethod = getMethod(pathList.getClass(), "makeDexElements", ArrayList.class, File.class, ArrayList.class);
                List dexFileList = new ArrayList<>();
                dexFileList.add(patchFile);
                ArrayList suppressedExceptions = new ArrayList();
                patchElements = (Object[]) makeDexElementsMethod.invoke(null, dexFileList, optDir, suppressedExceptions);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // Android 4.4-5.0 使用makeDexElements(ArrayList,File,ArrayList)  注意这里参数编程ArrayList类型
                // 和5.0一样的方法,注意4.4 会报错 Class ref in pre-verified class resolved to unexpected implementation
                Log.e(TAG, "installPatch: 当前版本:" + Build.VERSION.SDK_INT + "此版本暂未解决 Class ref in pre-verified class resolved to unexpected implementation 的问题");
                return;
            } else {
                Log.e(TAG, "installPatch: 当前版本:" + Build.VERSION.SDK_INT + "不支持热更新");
                return;
            }
            // 5.合并两个Element[] patchElements要放在前面
            Object[] newElements = (Object[]) Array.newInstance(dexElements.getClass().getComponentType(), dexElements.length + patchElements.length);
            System.arraycopy(patchElements, 0, newElements, 0, patchElements.length);
            System.arraycopy(dexElements, 0, newElements, patchElements.length, dexElements.length);
            // 6.反射替换原来的dexElements
            dexElementsField.set(pathList, newElements);
            Log.e(TAG, "installPatch: 修复成功");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "installPatch: 修复失败!!" + e.getMessage());
        }
    }

    /**
     * 10.0以上反射调用隐蔽方法
     */
    static void PsyP() {
        if (SDK_INT < Build.VERSION_CODES.P) {
            return;
        }
        try {
            //设置豁免所有hide api  https://developer.android.google.cn/about/versions/10/non-sdk-q
            Method forName = Class.class.getDeclaredMethod("forName", String.class);
            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
            Class vmRuntimeClass = (Class) forName.invoke(null, "dalvik.system.VMRuntime");
            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
            Object sVmRuntime = getRuntime.invoke(null);
            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
        } catch (
                Throwable e) {
            Log.e("[error]", "reflect bootstrap failed:", e);
        }
    }

    /**
     * 反射获取属性 会从所有父类中找,不区分private
     */
    public static Field getField(Class cls, String fieldName) {
        // 如果自己类中找不到 就去父类中递归查找
        Field declaredField = null;
        while (cls != null) {
            Log.e(TAG, "getField: 当前类" + cls.getName());
            try {
                declaredField = cls.getDeclaredField(fieldName);
                if (declaredField != null) {
                    declaredField.setAccessible(true);
                    return declaredField;
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            cls = cls.getSuperclass();
        }
        // 没有找到
        return null;
    }

    /**
     * 反射获取方法 会从所有父类中找,不区分private  注意方法需要传入参数
     */
    public static Method getMethod(Class cls, String methodName, Class... paramTypes) {

        // 如果自己类中找不到 就去父类中递归查找
        Method declaredMethod = null;
        while (cls != null) {
            try {
                declaredMethod = cls.getDeclaredMethod(methodName, paramTypes);
                if (declaredMethod != null) {
                    declaredMethod.setAccessible(true);
                    return declaredMethod;
                }
                cls = cls.getSuperclass();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        // 没有找到
        return null;
    }
}

Fix修复类(要修复的类)

public class Fix {
    public static String getMessage() {
//        return "程序出bug了,赶紧叫人来修补!!!";
        return "程序的问题已经修复完成(这是修复之后的类文件及方法)";
    }
}

AppLication

public class App extends Application {

  @Override
  public void onCreate() {
      super.onCreate();
      Log.e("Application", "----------path:" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/fix.dex");
      FixUtil.installPatch(this, Environment.getExternalStorageDirectory().getAbsolutePath() + "/fix.dex");
//            FixUtil.installPatch(this, getFilesDir()+ File.separator+"patch.dex");
  }
}

你可能感兴趣的:(Android热修复)