Android实现热更新功能(基于美团Robust)
关于
最近公司项目比较宽松一些,然后想起之前想实现的app热更新功能(不太清楚的可以自行百度一下,然后关于了解Android实现热更新都有哪些框架技术可用以及优缺点也可以自行百度,我这里简单说一下用美团的原因)本来我打算用阿里的Sophix ,因为看他们说是适配全而且接入啥的都比较方便,但是唯一的就是要计费。。。所以我就转投了美团的开源Robust,项目地址,里面也有详细的教程教我们怎样适配。
效果图
首先是未更新前的第一个版本:
实现热更新之后:
第一步,添加引用
在工程(Project)目录build下添加如下引用:
classpath 'com.meituan.robust:gradle-plugin:0.4.99'
classpath 'com.meituan.robust:auto-patch-plugin:0.4.99'
在项目(Moudle)目录下添加如下:
apply plugin: 'com.android.application' //这行自带的,不用添加
//apply plugin: 'auto-patch-plugin' //这行在生成path.jar的时候开启
apply plugin: 'robust'
在dependencies里面添加如下:
implementation 'com.meituan.robust:robust:0.4.99'
这个时候sync一下会报错,提示缺少robust文件,这个是正常的,我们把如下robust.xml复制到我们的项目中(这个robust.xml你可以在上面的robust仓库中的使用Demo app中找到),与src同级目录。如下图:
其中robust.xml文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<switch>
<!--true代表打开Robust,请注意即使这个值为true,Robust也默认只在Release模式下开启-->
<!--false代表关闭Robust,无论是Debug还是Release模式都不会运行robust-->
<turnOnRobust>true</turnOnRobust>
<!--<turnOnRobust>false</turnOnRobust>-->
<!--是否开启手动模式,手动模式会去寻找配置项patchPackname包名下的所有类,自动的处理混淆,然后把patchPackname包名下的所有类制作成补丁-->
<!--这个开关只是把配置项patchPackname包名下的所有类制作成补丁,适用于特殊情况,一般不会遇到-->
<!--<manual>true</manual>-->
<manual>false</manual>
<!--是否强制插入插入代码,Robust默认在debug模式下是关闭的,开启这个选项为true会在debug下插入代码-->
<!--但是当配置项turnOnRobust是false时,这个配置项不会生效-->
<!--<forceInsert>true</forceInsert>-->
<forceInsert>false</forceInsert>
<!--是否捕获补丁中所有异常,建议上线的时候这个开关的值为true,测试的时候为false-->
<catchReflectException>true</catchReflectException>
<!--<catchReflectException>false</catchReflectException>-->
<!--是否在补丁加上log,建议上线的时候这个开关的值为false,测试的时候为true-->
<!--<patchLog>true</patchLog>-->
<patchLog>false</patchLog>
<!--项目是否支持progaurd-->
<proguard>true</proguard>
<!--<proguard>false</proguard>-->
<!--项目是否支持ASM进行插桩,默认使用ASM,推荐使用ASM,Javaassist在容易和其他字节码工具相互干扰-->
<useAsm>true</useAsm>
<!--<useAsm>false</useAsm>-->
<!--针对Java8级别的Lambda表达式,编译为private级别的javac函数,此时由开发者决定是否进行插桩处理-->
<forceInsertLambda>true</forceInsertLambda>
<!-- <forceInsertLambda>false</forceInsertLambda>-->
</switch>
<!--需要热补的包名或者类名,这些包名下的所有类都被会插入代码-->
<!--这个配置项是各个APP需要自行配置,就是你们App里面你们自己代码的包名,
这些包名下的类会被Robust插入代码,没有被Robust插入代码的类Robust是无法修复的-->
<packname name="hotfixPackage">
<!--这里可以就填到com.example.myapplication,然后就会检测所有添加对应注解的包名下的类-->
<name>com.example.myapplication.Main3Activity</name>
</packname>
<!--不需要Robust插入代码的包名,Robust库不需要插入代码,如下的配置项请保留,还可以根据各个APP的情况执行添加-->
<exceptPackname name="exceptPackage">
</exceptPackname>
<!--补丁的包名,请保持和类PatchManipulateImp中fetchPatchList方法中设置的补丁类名保持一致( setPatchesInfoImplClassFullName("com.meituan.robust.patch.PatchesInfoImpl")),
各个App可以独立定制,需要确保的是setPatchesInfoImplClassFullName设置的包名是如下的配置项,类名必须是:PatchesInfoImpl-->
<patchPackname name="patchPackname">
<name>com.tobey.test</name>
</patchPackname>
<!--自动化补丁中,不需要反射处理的类,这个配置项慎重选择-->
<noNeedReflectClass name="classes no need to reflect">
</noNeedReflectClass>
</resources>
第二步,新增PatchManipulateImp.java文件
这个代码在上面的开源库的demo里面有的,唯一需要注意的是生产的jar的路径需要注意修改。
Created by mivanzhang on 17/2/27.
*
* We recommend you rewrite your own PatchManipulate class ,adding your special patch Strategy,in the demo we just load the patch directly
*
* <br>
* Pay attention to the difference of patch's LocalPath and patch's TempPath
*
* <br>
* We recommend LocalPath store the origin patch.jar which may be encrypted,while TempPath is the true runnable jar
*<br>
*<br>
* 我们推荐继承PatchManipulate实现你们App独特的A补丁加载策略,其中setLocalPath设置补丁的原始路径,这个路径存储的补丁是加密过得,setTempPath存储解密之后的补丁,是可以执行的jar文件
* <br>
* setTempPath设置的补丁加载完毕即刻删除,如果不需要加密和解密补丁,两者没有啥区别
*/
public class PatchManipulateImp extends PatchManipulate {
/***
* connect to the network ,get the latest patches
* l联网获取最新的补丁
* @param context
*
* @return
*/
@Override
protected List<Patch> fetchPatchList(Context context) {
//将app自己的robustApkHash上报给服务端,服务端根据robustApkHash来区分每一次apk build来给app下发补丁
//apkhash is the unique identifier for apk,so you cannnot patch wrong apk.
String robustApkHash = RobustApkHashUtils.readRobustApkHash(context);
Log.w("robust","robustApkHash :" + robustApkHash);
//connect to network to get patch list on servers
//在这里去联网获取补丁列表
Patch patch = new Patch();
patch.setName("123");
StringBuilder path = new StringBuilder();
path.append(Environment.getExternalStorageDirectory()
.getPath());
path.append(File.separator);// '/'
path.append("RoFix");// /mnt/sdcard/RoFix
path.append(File.separator);
path.append("patch");// /mnt/sdcard/RoFix/patch
patch.setLocalPath(path.toString());
//we recommend LocalPath store the origin patch.jar which may be encrypted,while TempPath is the true runnable jar
//LocalPath是存储原始的补丁文件,这个文件应该是加密过的,TempPath是加密之后的,TempPath下的补丁加载完毕就删除,保证安全性
//这里面需要设置一些补丁的信息,主要是联网的获取的补丁信息。重要的如MD5,进行原始补丁文件的简单校验,以及补丁存储的位置,这边推荐把补丁的储存位置放置到应用的私有目录下,保证安全性
// patch.setLocalPath(Environment.getExternalStorageDirectory().getPath()+ File.separator+"robust"+File.separator + "patch");
//setPatchesInfoImplClassFullName 设置项各个App可以独立定制,需要确保的是setPatchesInfoImplClassFullName设置的包名是和xml配置项patchPackname保持一致,而且类名必须是:PatchesInfoImpl
//请注意这里的设置
patch.setPatchesInfoImplClassFullName("com.tobey.test.patch.PatchesInfoImpl");
List patches = new ArrayList<Patch>();
patches.add(patch);
return patches;
}
/**
*
* @param context
* @param patch
* @return
*
* you can verify your patches here
*/
@Override
protected boolean verifyPatch(Context context, Patch patch) {
//do your verification, put the real patch to patch
//放到app的私有目录
StringBuilder path = new StringBuilder();
path.append((Environment.getExternalStorageDirectory()
.getPath()));
// path.append(context.getCacheDir());
path.append(File.separator);// '/'
path.append("Robust");// /mnt/sdcard/Robust
path.append(File.separator);
path.append("patch");// /mnt/sdcard/Robust/patch
patch.setTempPath(path.toString());
//in the sample we just copy the file
try {
copy(patch.getLocalPath(), patch.getTempPath());
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("copy source patch to local patch error, no patch execute in path "+patch.getTempPath());
}
return true;
}
public void copy(String srcPath,String dstPath) throws IOException {
File src=new File(srcPath);
if(!src.exists()){
throw new RuntimeException("source patch does not exist ");
}
File dst=new File(dstPath);
if(!dst.getParentFile().exists()){
dst.getParentFile().mkdirs();
}
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
/**
*
* @param patch
* @return
*
* you may download your patches here, you can check whether patch is in the phone
*/
@Override
protected boolean ensurePatchExist(Patch patch) {
return true;
}
}
第三步,新增RobustCallBackSample.java(这个demo里面也有)
public class RobustCallBackSample implements RobustCallBack {
@Override
public void onPatchListFetched(boolean result, boolean isNet, List<Patch> patches) {
Log.d("RobustCallBack", "onPatchListFetched result: " + result);
Log.d("RobustCallBack", "onPatchListFetched isNet: " + isNet);
for (Patch patch : patches) {
Log.d("RobustCallBack", "onPatchListFetched patch: " + patch.getName());
}
}
@Override
public void onPatchFetched(boolean result, boolean isNet, Patch patch) {
Log.d("RobustCallBack", "onPatchFetched result: " + result);
Log.d("RobustCallBack", "onPatchFetched isNet: " + isNet);
Log.d("RobustCallBack", "onPatchFetched patch: " + patch.getName());
}
@Override
public void onPatchApplied(boolean result, Patch patch) {
Log.d("RobustCallBack", "onPatchApplied result: " + result);
Log.d("RobustCallBack", "onPatchApplied patch: " + patch.getName());
}
@Override
public void logNotify(String log, String where) {
Log.d("RobustCallBack", "logNotify log: " + log);
Log.d("RobustCallBack", "logNotify where: " + where);
}
@Override
public void exceptionNotify(Throwable throwable, String where) {
Log.e("RobustCallBack", "exceptionNotify where: " + where, throwable);
}
}
第四步,修改MainActivity.xml
用于点击更新测试的小demo:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="17dp"
android:layout_marginTop="100dp"
android:textColor="#000"
android:textStyle="bold"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击"/>
</LinearLayout>
在androidManifest.xml配置文件添加存储权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
权限申请类PermissionUtils.java如下:
public class PermissionUtils {
/**
* 是否有权限
*
* @param context
* @return
*/
public static boolean checkSelfPermission(Context context, String permission) {
if (null == context) {
return false;
}
int per = ContextCompat.checkSelfPermission(context, permission);
return per == PackageManager.PERMISSION_GRANTED;
}
/**
* Check that all given permissions have been granted by verifying that each entry in the
* given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
*
* @see Activity#onRequestPermissionsResult(int, String[], int[])
*/
public static boolean verifyPermissions(int[] grantResults) {
// At least one result must be checked.
if (null == grantResults || grantResults.length < 1) {
return false;
}
// Verify that each required permission has been granted, otherwise return false.
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public static boolean isGrantSDCardReadPermission(Context context) {
return checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
}
public static void requestSDCardReadPermission(Activity activity, int requestCode) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
}
}
修改MainActivity.java如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tvShow = (TextView) findViewById(R.id.text_show);
if (isGrantSDCardReadPermission()) {
runRobust();
} else {
requestPermission();
}
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvShow.setText("今天是三月16号");
}
});
}
private void requestPermission() {
PermissionUtils.requestSDCardReadPermission(this, REQUEST_CODE_SDCARD_READ);
}
private void handlePermissionResult() {
if (isGrantSDCardReadPermission()) {
runRobust();
} else {
Toast.makeText(getApplicationContext(),"缺少读取SD卡权限",Toast.LENGTH_SHORT).show();
}
}
private boolean isGrantSDCardReadPermission() {
return PermissionUtils.isGrantSDCardReadPermission(this);
}
private static final int REQUEST_CODE_SDCARD_READ = 1;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_SDCARD_READ:
handlePermissionResult();
break;
default:
break;
}
}
private void runRobust() {
new PatchExecutor(getApplicationContext(), new PatchManipulateImp(), new RobustCallBackSample()).start();
}
}
第五步,打包release
在打包之前需要先将混淆打开,即 minifyEnabled true,然后我们在proguard-rules.pro文件中添加如下混淆:
-keepclassmembers class **{
public static com.meituan.robust.ChangeQuickRedirect *;
}
这个是美团热更新的混淆。然后进行打包,打包的时候会在项目中的build/outputs/下生成两个文件夹,一个是mapping一个是robust文件夹:
我们将生成的mapping.txt和methodsMap.robust文件复制到我们之前新建的robust文件夹内如下:
第六步(这才是开始),更新
修改MainActivity.java代码如下:
//在修改的方法上添加 @Modify,如果是新增的方法则是加上@Add
@Modify
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tvShow = (TextView) findViewById(R.id.text_show);
if (isGrantSDCardReadPermission()) {
runRobust();
} else {
requestPermission();
}
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvShow.setText("点击了按钮之后,实现的热更新");
}
});
}
将build中的patch-plugin放开,robust注释:
apply plugin: 'auto-patch-plugin'
//apply plugin: 'robust'
然后重新打包。这个时候打包会失败,但是会生成一个patch.jar如下图:
这里的path.jar包我们要放到我们的对应的文件夹下才能正确运行jar包实现热更新。
第七步 热更新修复
我们将path.jar放入我们apk中写的sdcard/Robust/文件夹下,然后重启apk,热更新成功!,如果不成功的话,可能是你的jar放置的文件夹不对,建议按照我的来写就好啦。
好啦,本篇到此结束了,有问题欢迎批评指正!
当然了,除了美团的robust还有就是微信的Tinker,有时间我也会弄一篇介绍文章。