热修复Tinker

                                          热修复Tinker

   为什么要使用热修复:线上程序出现BUG,在不想重新发布包让用户更新安装的情况下,可以使用热修复,让用户在不知不觉就修复了程序的问题。

  当一个App发布之后,突然发现了一个严重Bug需要进行紧急修复,这时候公司各个方就会忙的焦头烂额:重新打包App,测试,向各个应用市场和渠道换包、提示用户升级、用户下载、覆盖安装。有时候仅仅是为了修改一行代码,也要付出巨大的成本进行换包和重新发布。

这时候就提出一个问题:有没有办法以补丁的方式动态修复紧急Bug,不再需要重新发布App,不再需要用户重新下载,覆盖安装?

虽然Android系统并没有提供这个技术,但是很幸运的告诉大家,答案是:可以,热修复

注意:使用Tinker,要对gradle进行配置: http://blog.csdn.net/guiying712/article/details/53129961

                                                                                                       

                                                                           Tinker的已知问题

          由于原理与系统限制,Tinker有以下已知问题:

  1. Tinker不支持修改AndroidManifest.xml,Tinker不支持新增四大组件;
  2. 由于Google Play的开发者条款限制,不建议在GP渠道动态更新代码;
  3. 在Android N上,补丁对应用启动时间有轻微的影响;
  4. 不支持部分三星android-21机型,加载补丁时会主动抛出"TinkerRuntimeException:checkDexInstall failed"
  5. 由于各个厂商的加固实现并不一致,在1.7.6以及之后的版本,tinker不再支持加固的动态更新;
  6. 对于资源替换,不支持修改remoteView。例如transition动画,notification icon以及桌面图标。                                                                                                                                                                                                                                                                                  Tinker的环境搭建                                                                                                                                                         1.整个项目工作空间的build.gradle的配置                                           
    //注意:这里用的是双引号 ",否则${TINKER_VERSION}无法正确的使用,在gradle.properties下加入版本TINKER_VERSION=1.7.5
    classpath "com.tencent.tinker:tinker-patch-gradle-plugin:${TINKER_VERSION}"
    
                           
          gradle.properties文件中结尾处,添加此代码
    
    # 指定Tinker的版本信息,如果要用最新版本,在这个地方进行修改即可
    
    TINKER_VERSION=1.7.5
                             2.整个项目module的build.gradle的配置               
                      
    defaultConfig {
    ......
    // 热修复所需要的开启设置
    multiDexEnabled true
    }
     
    dependencies {
        .....
    //热修复所需要的依赖,注意凡是引用${TINKER_VERSION},都要用双引号 "
    provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}")
    compile("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}")
    compile('com.android.support:multidex:1.0.1')
    }
    //提示:修改ignoreWarning = true和 tinkerId = '1.0'(这里不是固定,而是versionName的值,要和上面的一致)
    //注意:搜索tinkerOldApkPath,然后把这里的apk名字修改的和bakApk一致,这样打出的补丁包才有效(每一次代码运行程序,都会得到不同的apk版本,如此以前的补丁就没有办法使用)
    def bakPath = file("${buildDir}/bakApk/")
    /**
     * you can use assembleRelease to build you base apk
     * use tinkerPatchRelease -POLD_APK=  -PAPPLY_MAPPING=  -PAPPLY_RESOURCE= to build patch
     * add apk from the build/bakApk
     */
    ext {
        //for some reason, you may want to ignore tinkerBuild, such as instant run debug build?
        tinkerEnabled = true
        //for normal build
        //old apk file to build patch apk
        tinkerOldApkPath = "${bakPath}/app-debug-0619-15-12-50.apk"
        //proguard mapping file to build patch apk
        tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
        //resource R.txt to build patch apk, must input if there is resource changed
        tinkerApplyResourcePath = "${bakPath}/app-debug-1018-17-32-47-R.txt"
        //only use for build all flavor, if not, just ignore this field
        tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
    }
    def getOldApkPath() {
        return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
    }
    def getApplyMappingPath() {
        return hasProperty("APPLY_MAPPING") ? APPLY_MAPPING : ext.tinkerApplyMappingPath
    }
    def getApplyResourceMappingPath() {
        return hasProperty("APPLY_RESOURCE") ? APPLY_RESOURCE : ext.tinkerApplyResourcePath
    }
    def buildWithTinker() {
        return hasProperty("TINKER_ENABLE") ? TINKER_ENABLE : ext.tinkerEnabled
    }
    def getTinkerBuildFlavorDirectory() {
        return ext.tinkerBuildFlavorDirectory
    }
    if (buildWithTinker()) {
        apply plugin: 'com.tencent.tinker.patch'
        tinkerPatch {
            /**
             * necessary,default 'null'
             * the old apk path, use to diff with the new apk to build
             * add apk from the build/bakApk
             */
            oldApk = getOldApkPath()
            /**
             * optional,default 'false'
             * there are some cases we may get some warnings
             * if ignoreWarning is true, we would just assert the patch process
             * case 1: minSdkVersion is below 14, but you are using dexMode with raw.
             *         it must be crash when load.
             * case 2: newly added Android Component in AndroidManifest.xml,
             *         it must be crash when load.
             * case 3: loader classes in dex.loader{} are not keep in the main dex,
             *         it must be let tinker not work.
    
             * case 4: loader classes in dex.loader{} changes,
    
             *         loader classes is ues to load patch dex. it is useless to change them.
    
             *         it won't crash, but these changes can't effect. you may ignore it
    
             * case 5: resources.arsc has changed, but we don't use applyResourceMapping to build
             */
    
            ignoreWarning = true
            /**
             * optional,default 'true'
             * whether sign the patch file
             * if not, you must do yourself. otherwise it can't check success during the patch loading
             * we will use the sign config with your build type
             */
            useSign = true
            /**
             * Warning, applyMapping will affect the normal android build!
             */
            buildConfig {
                /**
                 * optional,default 'null'
                 * if we use tinkerPatch to build the patch apk, you'd better to apply the old
                 * apk mapping file if minifyEnabled is enable!
                 * Warning:
                 * you must be careful that it will affect the normal assemble build!
                 */
                applyMapping = getApplyMappingPath()
                /**
                 * optional,default 'null'
                 * It is nice to keep the resource id from R.txt file to reduce java changes
                 */
                applyResourceMapping = getApplyResourceMappingPath()
                /**
                 * necessary,default 'null'
                 * because we don't want to check the base apk with md5 in the runtime(it is slow)
                 * tinkerId is use to identify the unique base apk when the patch is tried to apply.
                 * we can use git rev, svn rev or simply versionCode.
                 * we will gen the tinkerId in your manifest automatic
                 */
                tinkerId = '1.0'
            }
            dex {
                /**
                 * optional,default 'jar'
                 * only can be 'raw' or 'jar'. for raw, we would keep its original format
                 * for jar, we would repack dexes with zip format.
                 * if you want to support below 14, you must use jar
                 * or you want to save rom or check quicker, you can use raw mode also
                 */
                dexMode = "jar"
                /**
                 * optional,default 'false'
                 * if usePreGeneratedPatchDex is true, tinker framework will generate auxiliary class
                 * and insert auxiliary instruction when compiling base package using
                 * assemble{Debug/Release} task to prevent class pre-verified issue in dvm.
                 * Besides, a real dex file contains necessary class will be generated and packed into
                 * patch package instead of any patch info files.
                 *
                 * Use this mode if you have to use any dex encryption solutions.
                 *
                 * Notice: If you change this value, please trigger clean task
                 * and regenerate base package.
                 */
                usePreGeneratedPatchDex = false
                /**
                 * necessary,default '[]'
                 * what dexes in apk are expected to deal with tinkerPatch
                 * it support * or ? pattern.
                 */
                pattern = ["classes*.dex", "assets/secondary-dex-?.jar"]
                /**
                 * necessary,default '[]'
                 * Warning, it is very very important, loader classes can't change with patch.
                 * thus, they will be removed from patch dexes.
                 * you must put the following class into main dex.
                 * Simply, you should add your own application {@code tinker.sample.android.SampleApplication}
                 * own tinkerLoader, and the classes you use in them
                 *
                 */
                loader = ["com.tencent.tinker.loader.*",
                          //warning, you must change it with your application
                          "tinker.sample.android.app.SampleApplication",
                          //use sample, let BaseBuildInfo unchangeable with tinker
                          "tinker.sample.android.app.BaseBuildInfo"
                ]
            }
            lib {
                /**
                 * optional,default '[]'
                 * what library in apk are expected to deal with tinkerPatch
                 * it support * or ? pattern.
                 * for library in assets, we would just recover them in the patch directory
                 * you can get them in TinkerLoadResult with Tinker
                 */
                pattern = ["lib/armeabi/*.so"]
            }
            res {
                /**
                 * optional,default '[]'
                 * what resource in apk are expected to deal with tinkerPatch
                 * it support * or ? pattern.
                 * you must include all your resources in apk here,
                 * otherwise, they won't repack in the new apk resources.
                 */
                pattern = ["res/*", "assets/*", "resources.arsc", "AndroidManifest.xml"]
                /**
                 * optional,default '[]'
                 * the resource file exclude patterns, ignore add, delete or modify resource change
                 * it support * or ? pattern.
                 * Warning, we can only use for files no relative with resources.arsc
                 */
                ignoreChange = ["assets/sample_meta.txt"]
                /**
                 * default 100kb
                 * for modify resource, if it is larger than 'largeModSize'
                 * we would like to use bsdiff algorithm to reduce patch file size
                 */
                largeModSize = 100
            }
            packageConfig {
                /**
                 * optional,default 'TINKER_ID, TINKER_ID_VALUE' 'NEW_TINKER_ID, NEW_TINKER_ID_VALUE'
                 * package meta file gen. path is assets/package_meta.txt in patch file
                 * you can use securityCheck.getPackageProperties() in your ownPackageCheck method
                 * or TinkerLoadResult.getPackageConfigByName
                 * we will get the TINKER_ID from the old apk manifest for you automatic,
                 * other config files (such as patchMessage below)is not necessary
                 */
                configField("patchMessage", "tinker is sample to use")
                /**
                 * just a sample case, you can use such as sdkVersion, brand, channel...
                 * you can parse it in the SamplePatchListener.
                 * Then you can use patch conditional!
                 */
                configField("platform", "all")
                /**
                 * patch version via packageConfig
                 */
                configField("patchVersion", "1.0")
            }
            //or you can add config filed outside, or get meta value from old apk
            //project.tinkerPatch.packageConfig.configField("test1", project.tinkerPatch.packageConfig.getMetaDataFromOldApk("Test"))
            //project.tinkerPatch.packageConfig.configField("test2", "sample")
            /**
             * if you don't use zipArtifact or path, we just use 7za to try
             */
            sevenZip {
                /**
                 * optional,default '7za'
                 * the 7zip artifact path, it will use the right 7za with your platform
                 */
                zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
                /**
                 * optional,default '7za'
                 * you can specify the 7za path yourself, it will overwrite the zipArtifact value
                 */
    //        path = "/usr/local/bin/7za"
            }
        }
        List<String> flavors = new ArrayList<>();
        project.android.productFlavors.each {flavor ->
            flavors.add(flavor.name)
        }
        boolean hasFlavors = flavors.size() > 0
        /**
         * bak apk and mapping
         */
        android.applicationVariants.all { variant ->
            /**
             * task type, you want to bak
             */
            def taskName = variant.name
            def date = new Date().format("MMdd-HH-mm-ss")
            tasks.all {
                if ("assemble${taskName.capitalize()}".equalsIgnoreCase(it.name)) {
                    it.doLast {
                        copy {
                            def fileNamePrefix = "${project.name}-${variant.baseName}"
                            def newFileNamePrefix = hasFlavors ? "${fileNamePrefix}" : "${fileNamePrefix}-${date}"
                            def destPath = hasFlavors ? file("${bakPath}/${project.name}-${date}/${variant.flavorName}") : bakPath
                            from variant.outputs.outputFile
                            into destPath
                            rename { String fileName ->
                                fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}.apk")
                            }
                            from "${buildDir}/outputs/mapping/${variant.dirName}/mapping.txt"
                            into destPath
                            rename { String fileName ->
                                fileName.replace("mapping.txt", "${newFileNamePrefix}-mapping.txt")
                            }
                            from "${buildDir}/intermediates/symbols/${variant.dirName}/R.txt"
                            into destPath
                            rename { String fileName ->
                                fileName.replace("R.txt", "${newFileNamePrefix}-R.txt")
                            }
                        }
                    }
                }
            }
        }
        project.afterEvaluate {
            //sample use for build all flavor for one time
            if (hasFlavors) {
                task(tinkerPatchAllFlavorRelease) {
                    group = 'tinker'
                    def originOldPath = getTinkerBuildFlavorDirectory()
                    for (String flavor : flavors) {
                        def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Release")
                        dependsOn tinkerTask
                        def preAssembleTask = tasks.getByName("process${flavor.capitalize()}ReleaseManifest")
                        preAssembleTask.doFirst {
                            String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 15)
                            project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release.apk"
                            project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-mapping.txt"
                            project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-R.txt"
                        }
                    }
                }
                task(tinkerPatchAllFlavorDebug) {
                    group = 'tinker'
                    def originOldPath = getTinkerBuildFlavorDirectory()
                    for (String flavor : flavors) {
                        def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Debug")
                        dependsOn tinkerTask
                        def preAssembleTask = tasks.getByName("process${flavor.capitalize()}DebugManifest")
                        preAssembleTask.doFirst {
                            String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 13)
                            project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug.apk"
                            project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-mapping.txt"
                            project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-R.txt"
                        }
                    }
                }
            }
        }
    }
            3.项目中要自定义一个类继承DefaultApplicationLike替换原有的自定义Applicatio   
         
    / 用于配置生成的MyApplication类,使用时改成自己的包名的前缀即可,然后加个自定义类名,不要和下面的类名一致.
    // 提示:在清单文件里配置这里的MyApplication
    @DefaultLifeCycle(application = "com.sn.MyApplication",
            flags = ShareConstants.TINKER_ENABLE_ALL,
            loadVerifyFlag = false)
    // 只有使用tinker,就必须继承DefaultApplicationLike,进行环境的搭建
    public class MyApplicationLike extends DefaultApplicationLike {
    //这段代码直接从官方demo拷贝过来即可
        public MyApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag,
                                 long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent,
                                 Resources[] resources, ClassLoader[] classLoader, AssetManager[] assetManager) {
            super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent, resources, classLoader, assetManager);
        }
        public static Context context;
    // 该方法可以看成MyApplication中的onCreate方法,比如上下文的使用
        @Override
        public void onBaseContextAttached(Context base) {
            super.onBaseContextAttached(base);
            MultiDex.install(base);
            TinkerInstaller.install(this);
            context=base;
        }

                       全部搭建完成以后我们需要到AndroidManifest.XML里注册一下
                      以上我们的Tinker环境就搭建完成了,接下来写我们的逻辑代码
1.在项目中编写这段代码
//模拟效果:就是项目布局的textView为1,通过热修复改为2
public class  MainActivity  extends  AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//在布局里写一个错误,模拟有一个bug,然后通过热修复进行修改为ok
setContentView(R.layout.activity_main);
// 通过TextView的点击完成修复工作(官方demo是在Service进行更新的操作,为了不复杂就)
findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 加载补丁包:指定补丁包的位置,读取补丁包信息。
// 注意:要加读取SD卡的权限 < uses-permission  android :name= "android.permission.WRITE_EXTERNAL_STORAGE"  />
TinkerInstaller.onReceiveUpgradePatch(  
   // test:补丁包名称(可以自定义)
getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/test");
    }
});

//在写这段代码前,先运行项目,或者打一个有问题apk,这样下面修复问题打的apk,就有了差异包
//这段代码就模拟问题已经修复了,然后通过到这个demo,运行命令行,执行gradle tinkerPatchDebug,生成热修复的文件
//注意:'gradle' 不是内部或外部命令,也不是可运行的程序,那么还要在电脑上配置一下
((TextView)findViewById(R.id.tv)).setText("OK");
}
}

2.编写红色代码前,运行项目,会报一个错误,clean一下,在运行就没有问题了,此时会生成一个APK包,其APK包名字要配置到build文件里


 
3.编写红色代码后,代表项目进行了修改完成,接下来就是打补丁的操作
 
     cd /d module所在路径    
      gradle tinkerPatchDebug

 
4.生成的补丁包,名字+后缀名要进行修改,符合代码中的设置
  

5. 真实开发中要把补丁包放到服务器中,我们这里没有服务器,就直接放到了SD卡中
注意:客户端APP程序设计之初,就在应用启动的Activity中添加一段业务逻辑,去请求服务器有没有最新的补丁,有就下载到用户的SD卡中,然后执行修复的逻辑

1.把有问题的APK,安装到程序中
2.把补丁放到手机的SD卡中
3.点击文本,会自动加载补丁,完成修复后,自动删除sd卡中的补丁

注意:APK包对应有效补丁,重新打的包和以前的补丁没有办法一起用,新的apk包要打对应的补丁



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值