专栏首页ppjun专栏Android 热更新 Tinker 集成配置【详细】

Android 热更新 Tinker 集成配置【详细】

Tinker简单接入

Tinker 是微信官方的 Android 热补丁解决方案,它支持动态下发代码、So 库以及资源,让应用能够在不需要重新安装的情况下实现更新。

不足之处

  1. Tinker 不支持修改 AndroidManifest.xml,Tinker 不支持新增四大组件 (1.9.0 支持新增非 export 的 Activity);
  2. 由于 Google Play 的开发者条款限制,不建议在 GP 渠道动态更新代码;
  3. 在 Android N 上,补丁对应用启动时间有轻微的影响;
  4. 不支持部分三星 android-21 机型,加载补丁时会主动抛出"TinkerRuntimeException:checkDexInstall failed";
  5. 对于资源替换,不支持修改 remoteView。例如 transition 动画,notification icon 以及桌面图标。

优点

  1. 开源,免费;
  2. Tinker 已运行在微信的数亿 Android 设备上使用了

1. 添加Tinker插件和库

在root项目根目录的build.gradle下

 classpath 'com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1'

在app项目的build.gradle下,从Tinkerdemo中看出以gradle插件版本分别用了implementation和compile,还要记得dex分包

 dependencies {
 if (is_gradle_3()) {
     implementation("com.tencent.tinker:tinker-android-lib:1.9.1") { changing = true }
     annotationProcessor("com.tencent.tinker:tinker-android-anno:1.9.1") { changing = true }
     compileOnly("com.tencent.tinker:tinker-android-anno:1.9.1") { changing = true }
     compile "com.android.support:multidex:1.0.1"

 }else{
     compile "com.android.support:multidex:1.0.1"
     provided('com.tencent.tinker:tinker-android-anno:1.9.1')
     compile('com.tencent.tinker:tinker-android-lib:1.9.1') 
     
 }

2. 开启dex分包和大项目模式

defaultConfig {
      multiDexEnabled true
}

dexOptions {
        jumboMode = true
        maxProcessCount 4
        javaMaxHeapSize "2g"
    }

3. 添加任务

这时候需要定义tinkerid(这里你可以用到gitSha或者版本号.补丁号来定义)oldapkname,mapping,resourse.arsc等变量,把下面这一段复制到app/build.gradle

//定义一个存放oldapk的文件夹
def bakPath = file("${buildDir}/bakApk/")


ext {
    //开放项目阶段设置为false,等项目要上架了再设置为true
    tinkerEnabled = true

    //for normal build
    //就是基础包,就是你要修复上架的应用的apk,tinker会根据这个apk名字去打补丁包
    tinkerOldApkPath = "${bakPath}/app-debug-1018-17-32-47.apk"
    //基础包的混淆文件
    tinkerApplyMappingPath = "${bakPath}/app-debug-1018-17-32-47-mapping.txt"
    //基础包的R.txt资源索引文件
    tinkerApplyResourcePath = "${bakPath}/app-debug-1018-17-32-47-R.txt"
    //如果你要编译多个不同版本的apk,否则忽略它
    //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 getTinkerIdValue() {
    return hasProperty("TINKER_ID") ? TINKER_ID : gitSha()
}

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
         */
         //默认不忽略警告,当设置为true,注意以下情况时会退出打补丁包或者打补丁失败
            //1.最小sdk版本小于14,你用了raw就gg了
            //2.加了新的四大组件(1.9.0可以加入非export的Activity)到Android配置文件
            //3.tinker的dex没打包进main.dex,tinker就不工作了
            //4.tinker类是用来加载补丁dex的,改变他们是没用的,虽然不会崩溃,但是改变是无效的,可以忽略它
            //5.资源修改了,没用新的mapping.txt去编译
        ignoreWarning = false

        /**
         * 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
         */
            //签名补丁apk,否则会检验补丁apk失败,要和基础包apk签名一样
        useSign = true

        /**
         * optional,default 'true'
         * whether use tinker to build
         */
            //tinker开关
        tinkerEnable = buildWithTinker()

        /**
         * 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!
             */
            //让补丁apk和基础包apkproguard混淆文件保持一致,可以减少补丁包体积
            applyMapping = getApplyMappingPath()
            /**
             * optional,default 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             */
                //让补丁包apk和基础包的资源R文件保持一致,维持资源id的分配,
            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一样,才能打入补丁,我们会把tinkerid编译到androidmanifest文件
            tinkerId = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
                //会用diff加工补丁包dex减少dex体积
            keepDexApply = false

            /**
             * optional, default 'false'
             * Whether tinker should treat the base apk as the one being protected by app
             * protection tools.
             * If this attribute is true, the generated patch package will contain a
             * dex including all changed classes instead of any dexdiff patch-info files.
             */
                //是否加固apk,用于360,乐固加固后的apk才开启
            isProtectedApp = false

            /**
             * optional, default 'false'
             * Whether tinker should support component hotplug (add new component dynamically).
             * If this attribute is true, the component added in new apk will be available after
             * patch is successfully loaded. Otherwise an error would be announced when generating patch
             * on compile-time.
             *
             * <b>Notice that currently this feature is incubating and only support NON-EXPORTED Activity</b>
             */
                //要不要更新activity,tinker1.9.+才有的
            supportHotplugComponent = false
        }

        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
             */
            //这里有jar和raw模式给你选,raw模式就是保持dex格式,jar就是重新把多个dex打包进jar
           //你想支持14-就一定要用jar,raw省略了md5验证和减少体积。但是我们还是用jar吧不检查md5
            dexMode = "jar"

            /**
             * necessary,default '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             */
                //apk哪些要用tinkerpatch处理
            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
             *
             */
                //保持哪些类不会被修改,比如让basebuildinfo打补丁的时候不会被改变,
            loader = [
                    //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
             */
            //要处理so文件
            pattern = ["lib/*/*.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
             */
                //如果资源大于100就用bsdiff资源来减小补丁包体积
            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
             */
            //定义一些变量可以用tinker.tinkerLoadResultIfPresent.getPackageConfigByName来获取
            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
             */
            //7zip来压缩你的补丁apk
            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
    def date = new Date().format("MMdd-HH-mm-ss")

    /**
     * bak apk and mapping
     */
    android.applicationVariants.all { variant ->
        /**
         * task type, you want to bak
         */
        def taskName = variant.name

        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.first().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"
                    }

                }
            }
        }
    }
}

加入TinkerDemo里面的类

image.png

把tinkerdemo中的crash log reporter service 和util复制到你的项目,还要注册sampleresultservice的服务

SampleUncaughtExceptionHandler捕抓全局异常类
MyLogImp控制日志输出类
SamplePatchListener 检测补丁md5的类
SamplePatchReporter 补丁升级,异常,打断的回调
SampleTinkerReport 集中管理状态码
SampleResultService 处理加载补丁结果,开启服务在后台结束进程
TinkerManager 初始化全局异常,安装补丁的类
Utils 工具类判断xposed是否存在 rom空间,是否息屏

替换ApplicationLike

新建一个TinkerApplicationLike 继承DefaultApplicationLike

@SuppressWarnings("unused")
@DefaultLifeCycle(application = "你原来的applciation名字",
                  flags = ShareConstants.TINKER_ENABLE_ALL,
                  loadVerifyFlag = false)
public class SampleApplicationLike extends DefaultApplicationLike {
    private static final String TAG = "Tinker.SampleApplicationLike";

    public SampleApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag,
                                 long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    /**
     * install multiDex before install tinker
     * so we don't need to put the tinker lib classes in the main dex
     *
     * @param base
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        //you must install multiDex whatever tinker is installed!
        //开启dex分包
        MultiDex.install(base);

        SampleApplicationContext.application = getApplication();
        SampleApplicationContext.context = getApplication();
        TinkerManager.setTinkerApplicationLike(this);

        TinkerManager.initFastCrashProtect();
        //should set before tinker is installed
        TinkerManager.setUpgradeRetryEnable(true);

        //optional set logIml, or you can use default debug log
        //debug的时候可以输出log,发release版本去掉这句
        TinkerInstaller.setLogIml(new MyLogImp());

        //installTinker after load multiDex
        //or you can put com.tencent.tinker.** to main dex
        //安装tinker dex到主dex
        TinkerManager.installTinker(this);
        Tinker tinker = Tinker.with(getApplication());
        
        //把你原来Application的attachbasecontext搬运到这里
    }
 @Override
    public void onCreate() {
        super.onCreate();
     //把你原来Application的oncreate搬运到这里
    }
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
        getApplication().registerActivityLifecycleCallbacks(callback);
    }

}

TinkerInstaller方法

打上补丁

TinkerInstaller.onReceiveUpgradePatch(this@TestUI, outFile.absolutePath)
//outFile这里是sd卡patch.apk的路径
Tinker.with(getApplicationContext()).cleanPatch();
//删除全部补丁
Tinker.with(getApplicationContext()).cleanPatchByVersion(版本号)
//删除某个版本号的补丁
ShareTinkerInternals.killAllOtherProcess(getApplicationContext());
//终止其他进程
android.os.Process.killProcess(android.os.Process.myPid());
//终止主进程,打上补丁后,重启app才生效

流程是在闪屏界面开启服务去请求补丁包,然后保存到sd卡,调用onReceiveUpgradePatch加载补丁。

打一个debug基准包。

调用build-build apks或者./gradlew assemblesDebug在app/build/bakApk/生成以打包时间为名称的apk,然后我们重命名为app-debug-1018-17-32-47.apk,用手机安装这个apk包

修改内容比如把输出内容改变一下。

print.setOnClickListener {
    ToastUtil.showTipMessage(this@TestUI, "hello world by tinker by tinker")
}

在终端执行./gradlew tinkerPatchDebug,执行成功后会在app/build/outputs/apk/tinkerPatch/debug/看到以下补丁包,我们选择patch_sign_7zip.apk.来加载。

patch_signed.apk 签名补丁包

patch_signed_7zip.apk 签名压缩后的补丁包

Patch_unsigned.apk 未签名的补丁包

问题

在执行tinkerPatchDebug的时候,报出warnning manifest is changed . 错误说manifest文件被修改了。然后在tinker的issue里面找到 用三角形的run的apk的androidmanifest。xml里面的application标签会加入 android:testOnly="true"属性。 而tinkerPatchDebug打的包没有这个属性 所以manifest文件不一致。

后话

因为tinker要用到后台管理补丁,发放补丁。下一篇文章会介绍集成bugly管理发放补丁。

备注

http://blog.csdn.net/pigwithbadguy/article/details/53536408 这篇文章介绍了tinkerid app的版本号和补丁的版本号。 就是基准包和补丁包的tinkerid要保持一致。tinkerid一般与apk版本号一致。一个基准包可以加载多个补丁包。(就是说基准包可以不用安装旧的补丁包,直接安装最新的补丁包),当应用发布第二版本要升级tinkerid。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Mac下安装配置Android Studio并让多版本共存以及配置使用adb

    SeanDepp
  • Android绘制(三):Path结合属性动画, 让图标动起来!

    SeanDepp
  • 一个util带你解决动态申请权限问题(2018.8重编版)

    SeanDepp
  • Android小知识10则(下)

    SeanDepp
  • Android弹窗二则: PopupWindow和AlertDialog

    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app....

    SeanDepp
  • Android绘制(一):来用shape绘出想要的图形吧!

    SeanDepp
  • Android绘制(二):来用Path绘出想要的图形吧!

    之前有一篇用shape进行绘制的, 但是那个偏向静态, path结合属性动画可以动起来哦~ path是什么? 来看看官方的介绍:

    SeanDepp
  • Android手势操作耍起来!

    SeanDepp
  • Android小知识10则(上)(2018.8重编版)

    SeanDepp
  • 快速上手ndk开发! Mac/Win下配置和使用!(2018.4重编版)

    SeanDepp

扫码关注云+社区

领取腾讯云代金券