Android热修复Tinker的集成与使用步骤

前言:tinker官方文档地址 https://github.com/Tencent/tinker/wiki

一、Tinker的集成步骤

1.设置tinker版本,在gradle.properties文件中 添加tinker版本号,方便以后升级时修改:

TINKER_VERSION=1.9.8  

2.在项目的build.gradle文件中添加依赖:

dependencies {
    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            // TinkerPatch 插件
             classpath'com.tencent.tinker:tinker-patch-gradle-plugin:${TINKER_VERSION}’
        }
} 

3.配置app的build.gradle文件

(1)添加tinker的库依赖
//Gradle版本小于2.3的这么写:
dependencies {
    compile "com.android.support:multidex:1.0.1"
     //可选,用于生成application类
    provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}")
    //tinker的核心库
    compile("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}")
}

//Gradle版本大等于2.3的这么写:   
dependencies {
    implementation "com.android.support:multidex:1.0.1"
    //tinker的核心库
    implementation("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}") { changing = true }
    //可选,用于生成application类
    annotationProcessor("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") { changing = true }
    compileOnly("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") { changing = true }
}
(2)开启支持大工程模式,Tinker文档中推荐将jumboMode设置为true
defaultConfig {
    ......

    //需要注意一点,Tinker需要使用到MulitDex,开启multiDex
    multiDexEnabled true
    /**
     * buildConfig can change during patch!
     * we can use the newly value when patch
     */
    buildConfigField "String", "MESSAGE", "\"I am the base apk\""
    /**
     * client version would update with patch
     * so we can get the newly git version easily!
     */
    buildConfigField "String", "TINKER_ID", "\"${getTinkerIdValue()}\""
    buildConfigField "String", "PLATFORM", "\"all\""
}
dexOptions {
    // 支持大工程模式
    jumboMode = true
}
(3)配置Tinker与任务

将下面的配置全部复制粘贴到app的gradle文件(app/build.gradle)末尾,内容很多,但现在只需要看懂bakPath与ext括号内的就好。

def gitSha() {
    try {
        String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
        if (gitRev == null) {
            throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
        }
        return gitRev
    } catch (Exception e) {
        throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
    }
}

//保存打包old 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 {
    // 是否使用Tinker(当你的项目处于开发调试阶段时,可以改为false)
    tinkerEnabled = true
    // 基础包文件路径(名字这里写死为old-app.apk。用于比较新旧app以生成补丁包,不管是debug还是release编译)
    tinkerOldApkPath = "${bakPath}/app-release-1025-15-47-09.apk"
    // 基础包的mapping.txt文件路径(用于辅助混淆补丁包的生成,一般在生成release版app时会使用到混淆,所以这个mapping.txt文件一般只是用于release安装包补丁的生成)
    tinkerApplyMappingPath = "${bakPath}/app-release-1025-15-47-09-mapping.txt"
    // 基础包的R.txt文件路径(如果你的安装包中资源文件有改动,则需要使用该R.txt文件来辅助生成补丁包)
    tinkerApplyResourcePath = "${bakPath}/app-release-1025-15-47-09-R.txt"
    //多渠道打包相关
    tinkerBuildFlavorDirectory = "${bakPath}/app-release-1025-15-47-09"
}

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") ? Boolean.parseBoolean(TINKER_ENABLE) : ext.tinkerEnabled
}

def getTinkerBuildFlavorDirectory() {
    return ext.tinkerBuildFlavorDirectory
}

if (buildWithTinker()) {
    //apply tinker插件
    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         *
         */
        //基准apk包的路径,必须输入,否则会报错
        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 = 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包与补丁包的签名是否一致,我们是否需要为你签名。
        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使用旧的Map文件,减少补丁包大小
            applyMapping = getApplyMappingPath()
            /**
             * optional,default 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             */
            //可选参数;在编译新的apk时候,我们希望通过保持旧apk的proguard混淆方式,从而减少补丁包的大小。这个只是推荐设置,不设置applyMapping也不会影响任何的assemble编译。
            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
             */
            //可选参数;在编译新的apk时候,我们希望通过旧apk的R.txt文件保持ResId的分配,这样不仅可以减少补丁包的大小,同时也避免由于ResId改变导致remote view异常。
            tinkerId = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
            //在运行过程中,我们需要验证基准apk包的tinkerId是否等于补丁包的tinkerId。这个是决定补丁包能运行在哪些基准包上面,一般来说我们可以使用git版本号、versionName等等。
            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.
             */
            //如果我们有多个dex,编译补丁时可能会由于类的移动导致变更增多。若打开keepDexApply模式,补丁包将根据基准包的类分布来编译。
            //是否使用加固模式,仅仅将变更的类合成补丁。注意,这种模式仅仅可以用于加固应用中。
            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.
             *
             * Notice that currently this feature is incubating and only support NON-EXPORTED Activity
             */
            //是否支持新增非export的Activity(1.9.0版本开始才有的新功能)
            supportHotplugComponent = false
        }
        // dex相关的配置项
        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"

            /**
             * necessary,default '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             */
            //只能是'raw'或者'jar'。 对于'raw'模式,我们将会保持输入dex的格式。对于'jar'模式,我们将会把输入dex重新压缩封装到jar。
            // 如果你的minSdkVersion小于14,你必须选择‘jar’模式,而且它更省存储空间,但是验证md5时比'raw'模式耗时。
            // 默认我们并不会去校验md5,一般情况下选择jar模式即可。
            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
             */
            //需要处理dex路径,支持*、?通配符,必须使用'/'分割。路径是相对安装包的,例如assets/...
            loader = [
                    // 定义哪些类在加载补丁包的时候会用到。这些类是通过Tinker无法修改的类,也是一定要放在main dex的类。
                    // 如果你自定义了TinkerLoader,需要将它以及它引用的所有类也加入loader中;
                    // 其他一些你不希望被更改的类,例如Sample中的BaseBuildInfo类。这里需要注意的是,这些类的直接引用类也需要加入到loader中。或者你需要将这个类变成非preverify。
                    "tinker.sample.android.app.BaseBuildInfo"
            ]
        }
        // lib相关的配置项
        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
             */
            //需要处理lib路径,支持*、?通配符,必须使用'/'分割。与dex.pattern一致, 路径是相对安装包的,例如assets/...
            pattern = ["lib/*/*.so"]
        }
        // res相关的配置项
        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
             */
            //需要处理res路径,支持*、?通配符,必须使用'/'分割。与dex.pattern一致, 路径是相对安装包的,例如assets/...,务必注意的是,只有满足pattern的资源才会放到合成后的资源包。
            //支持*、?通配符,必须使用'/'分割。若满足ignoreChange的pattern,在编译时会忽略该文件的新增、删除与修改。 最极端的情况,ignoreChange与上面的pattern一致,即会完全忽略所有资源的修改。
            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,我们将使用bsdiff算法。这可以降低补丁包的大小,但是会增加合成时的复杂度。默认大小为100kb
            largeModSize = 100
        }
        // 用于生成补丁包中的'package_meta.txt'文件
        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("key", "value"), 默认我们自动从基准安装包与新安装包的Manifest中读取tinkerId,并自动写入configField。
            //在这里,你可以定义其他的信息,在运行时可以通过TinkerLoadResult.getPackageConfigByName得到相应的数值。但是建议直接通过修改代码来实现,例如BuildConfig。
            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
         */
        //7zip路径配置项,执行前提是useSign为true
        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 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

                        if (variant.metaClass.hasProperty(variant, 'packageApplicationProvider')) {
                            def packageAndroidArtifact = variant.packageApplicationProvider.get()
                            if (packageAndroidArtifact != null) {
                                try {
                                    from new File(packageAndroidArtifact.outputDirectory.getAsFile().get(), variant.outputs.first().apkData.outputFileName)
                                } catch (Exception e) {
                                    from new File(packageAndroidArtifact.outputDirectory, variant.outputs.first().apkData.outputFileName)
                                }
                            } else {
                                from variant.outputs.first().mainOutputFile.outputFile
                            }
                        } else {
                            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"
                        from "${buildDir}/intermediates/symbol_list/${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"
                    }

                }
            }
        }
    }
}

task sortPublicTxt() {
    doLast {
        File originalFile = project.file("public.txt")
        File sortedFile = project.file("public_sort.txt")
        List sortedLines = new ArrayList<>()
        originalFile.eachLine {
            sortedLines.add(it)
        }
        Collections.sort(sortedLines)
        sortedFile.delete()
        sortedLines.each {
            sortedFile.append("${it}\n")
        }
    }
}  
注意:在运行demo时可能出现tinkerId未设置问题,这是由于demo中tinkerId为git的版本,当你本地无法获取git的版本时,会报错,可以将thinkerId设置为应用的versionName,tinkerId保证其唯一性即可,每次升级app tinkerId也需要更新,继续与versionName保持一致。如下当前App的版本号是1.0
def gitSha() {
    try {
//        String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
//        if (gitRev == null) {
//            throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
//        }
        //设置tinkerId,与versionName一致即可
        return '1.0'
//        return gitRev
    } catch (Exception e) {
        throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
    }
}  

4.添加sd的读写权限,这里要注意针对Android6.0以上版本需要动态获取权限



5.将tinker Demo中提供的tinker包下的所有文件及文件夹都拷贝到自己项目中。 简单说明下,这几个文件的作用:

  • SampleUncaughtExceptionHandler:Tinker的全局异常捕获器。
  • MyLogImp:Tinker的日志输出实现类。
  • SampleLoadReporter:加载补丁时的一些回调。
  • SamplePatchListener:过滤Tinker收到的补丁包的修复、升级请求。
  • SamplePatchReporter:修复或者升级补丁时的一些回调。
  • SampleTinkerReport:修复结果(成功、冲突、失败等)。
  • SampleResultService::patch补丁合成进程将合成结果返回给主进程的类。
  • TinkerManager:Tinker管理器(安装、初始化Tinker)。
  • TinkerUtils:拓展补丁条件判定、锁屏或后台时应用重启功能的工具类。

这些是对Tinker功能的拓展和封装,都是可选的,但这些文件对项目的功能完善会有所帮助,建议加入到自己的项目中。
如果仅仅只是为了修复bug,而不做过多的工作(如:上传打补丁信息到服务器等),则无须理会这些文件的作用,当然也可以自己封装。

6.清单文件中添加服务

SampleResultService文件是四大组件之一,所以必须在清单文件中声明。


7.改造Application

Tinker表示,Application无法动态修复,所以有两种选择:

  1. 使用「继承TinkerApplication + DefaultApplicationLike」。
  2. 使用「DefaultLifeCycle注解 + DefaultApplicationLike」。

如果自定义的Application不会用到热修复,可无视这部分;但下方代码中的initTinker()方法记得要拷贝到你项目中,用于初始化Tinker。

Tinker官方推荐的方式使用第2种(Tinker官方推荐的方式):「DefaultLifeCycle注解 + TinkerApplicationLike」,DefaultLifeCycle注解生成Application,下面就来编写Application的代理类:

@SuppressWarnings("unused")
@DefaultLifeCycle(application = "com.example.ml.tinkertest.MyApplication",// application类名。只能用字符串,这个MyApplication文件是不存在的,但可以在AndroidManifest.xml的application标签上使用(name)
        flags = ShareConstants.TINKER_ENABLE_ALL,// tinkerFlags
        loaderClass = "com.tencent.tinker.loader.TinkerLoader",//loaderClassName, 我们这里使用默认即可!(可不写)
        loadVerifyFlag = false)//tinkerLoadVerifyFlag
public class TinkerApplicationLike extends DefaultApplicationLike {

    private Application mApplication;
    private Context mContext;
    private Tinker mTinker;

    // 固定写法
    public TinkerApplicationLike(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    // 固定写法
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
        getApplication().registerActivityLifecycleCallbacks(callback);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        mApplication = getApplication();
        mContext = getApplication();
        initTinker(base);
        // 可以将之前自定义的Application中onCreate()方法所执行的操作搬到这里(或者重写onCreate()里)...
    }

    private void initTinker(Context base) {
        // tinker需要你开启MultiDex
        MultiDex.install(base);

        TinkerManager.setTinkerApplicationLike(this);
        // 设置全局异常捕获
        TinkerManager.initFastCrashProtect();
        //开启升级重试功能(在安装Tinker之前设置)
        TinkerManager.setUpgradeRetryEnable(true);
        //设置Tinker日志输出类
        TinkerInstaller.setLogIml(new MyLogImp());
        //安装Tinker(在加载完multiDex之后,否则你需要将com.tencent.tinker.**手动放到main dex中)
        TinkerManager.installTinker(this);
        mTinker = Tinker.with(getApplication());
    }

}

8.最后在清单文件中注册application

将@DefaultLifeCycle中application对应的值,即"com.example.ml.tinkertest.MyApplication",赋值给清单文件的application标签的name属性,如下:


    ...

注意:application此时name属性会报红,因为项目源码中根本不存在MyApplication.java文件,但不必担心,因为它是动态生成的,Build一下项目就好了,不管它也无所谓。

二、Tinker的使用步骤

1.生成保存基准包

特别注意:基准包将作为正式服务器版本发布出去。需要保管妥当,将bakApk中对应的版本复制一份保存在本地,以免执行AS中Clean Project任务时删掉。如下图,将app-release-1101-10-31-24整个文件夹复制保存于本地。如果在构建补丁包的时候没有找到的话,就把本地的copy进去。

方法一:在AS Terminal 命令窗口 执行gradlew assemblerelease 命令
方法二:在AS gradle执行assembleRelease,如下图

Android热修复Tinker的集成与使用步骤_第1张图片
tinker打基准包.png

基准包将位于 build/bakApk下

2..把基准包信息填入app下build.gradle的ext中

tinkerOldApkPath = "${bakPath}/app-release-1101-10-31-24.apk"
tinkerApplyMappingPath = "${bakPath}/app-release-1101-10-31-24-mapping.txt"
tinkerApplyResourcePath = "${bakPath}/app-release-1101-10-31-24-R.txt"
tinkerBuildFlavorDirectory = "${bakPath}/app-release-1101-10-31-24"

3.构建补丁包

在线上的APP出现bug或者需要进行资源替换,就要生产补丁包,方法和构建基准包方法一样,有两种:
方法一:在AS Terminal 命令窗口 执行gradlew tinkerPatchRelease 命令
方法二:在AS gradle执行tinkerPatchRelease命令行,如下图

Android热修复Tinker的集成与使用步骤_第2张图片
tinker打补丁包.png

补丁包将位于 build/outputs/tinkerPatch下
注意:
1.tinkerPatch和基础包必须要保持一致都是release或者debug包
2.线上版本不变第二次发布补丁包时app下build.gradle的ext中信息不变,只需要重新打补丁包即可

4.更新补丁包

注意:正常情况下需要将补丁包放在后台,然后前端进入程序时执行代码下载补丁包并更新,退出App第二次进入即可看到更新补丁成功。
这里进行测试,直接将基准包和补丁包放到手机根目录,安装基准包然后进入主页面点击更新补丁按钮,退出App第二次进入即可看到更新补丁成功

三、Demo附件地址

https://github.com/zyx670618/tinkerTest.git

你可能感兴趣的:(Android热修复Tinker的集成与使用步骤)