AndFix,。是阿里开源的一个Android热补丁框架,允许APP在不重新发布版本的情况下修复线上的bug
1、导入依赖包
compile 'com.alipay.euler:andfix:0.5.0@aar'
2、Application 的OnCreate中
private PatchManager mPatchManager; private String PATH = "andfix.apatch"; //热更新文件 @Override public void onCreate() { super.onCreate(); mPatchManager = new PatchManager(this); mPatchManager.init(Utils.getVersionName(this)); //APP版本号(版本号不同将会移除更Apatch文件) mPatchManager.loadPatch();
String apatchPath = Utils.getApplicationCachePath(this) + File.separatorChar + PATH; try { //加载热更新文件 mPatchManager.addPatch(apatchPath); mPatchManager.removeAllPatch();//移除更新 } catch (Exception e) { } getApath(apatchPath); //网络下载,此处在Application中开启网络请求 }
/** * 下载apatch文件 *通过Retrofit进行下载 * @param apathPath */ public void getApath(final String apathPath) { ApiService apiService = ApiRetrofit.getInstance().getApiService(); Call<ResponseBody> call = apiService.getApath("url"); //服务器上apatch文件地址 call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { boolean isSucess = Utils.writeToApplicationCache(response.body(), apathPath);//获取到文件之后保存到本地SD卡 } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { }
/** * 保存热更新文件到SD卡根目录下 * @param body * @param filePath * @return */ public static boolean writeToApplicationCache(ResponseBody body,String filePath) { try { // todo change the file location/name according to your needs File apatchFile = new File(filePath); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; inputStream = body.byteStream(); outputStream = new FileOutputStream(apatchFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; } }});}
3、生成apatch文件
1)下载生成工具 https://raw.githubusercontent.com/alibaba/AndFix/master/tools/apkpatch-1.0.3.zip2)两个APK文件 一个线上带有BUG的,一个修复后的
3)生成补丁
下载完生成工具后解压,打开cmd命令行,cd到apkpatch.bat所在的目录:
具体命令可以参考github上,这里我引用下来:
apkpatch -f ‘新apk路径’ -t‘ 旧apk的路径’ -o ‘生成的补丁包的输出目录’ -k‘ 打包签名的keystore文件路径’ -p ‘签名文件密码’ -a‘ keystore别名’ -e ’keyStore entry的密码‘
如:apkpatch -o E:\ -k E:\liujks -p liu -a liu -e liu -f app-release.apk -t app-debug.apk
回车就会生成对应的 apatch文件,将其放到对应的网络或者手机打开APP即可替换
4)如果本地有多个apatch文件则根据生成时间来加载