1. 程式人生 > >站在巨人的肩上——Android熱更新框架Tinker探索之旅

站在巨人的肩上——Android熱更新框架Tinker探索之旅

參考資料:
1.Tinker
2.Android 熱修復 Tinker接入及原始碼淺析
如果大家對tinker比較陌生,請先去看看tinker的wiki鴻洋_大神的這篇文章

現在比較流行的熱修復框架的優缺點和特色,在Tinker的wiki下都可以看到,這裡就不在贅述了,Tinker只用了這句話來展現自己的優勢:
Tinker已執行在微信的數億Android裝置上,那麼為什麼你不使用Tinker呢?

Tinker分為gradle接入和命令列接入,但是我這種菜鳥玩不轉命令列,所以只能照搬gradle接入Tinker了。但是我感覺,命令列算不上一種接入,僅僅是多了一種編譯差分包的方式而已,當然,這僅僅是個人見解哈,至於我為什麼這麼說,大家往下看就知道了。

首先,在project的build.gradle檔案裡需要新增Tinker的外掛依賴

dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        ...
        //Tinker
        classpath "com.tencent.tinker:tinker-patch-gradle-plugin:1.7.7"
    }

其次就是主module的build.gradle檔案的配置,主要有下面幾個地方

1.引入Tinker依賴

dependencies {
    //tinker必須要引入多dex打包支援
compile 'com.android.support:multidex:1.0.1' //可選,用於註解生成application類 provided("com.tencent.tinker:tinker-android-anno:1.7.7" //tinker依賴版本 compile("com.tencent.tinker:tinker-android-lib:1.7.7") }

2.tinker的一些配置

        //-------------------------tinker config start-------------------------
buildConfigField "String","TINKER_VERSION","\"1.7.7\"" /** * 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\"" //-------------------------tinker config end-------------------------

3.編譯差分包的開關和老版本檔案位置確定

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 {
    def oldPrefixFormat="app_beta1_${appVersionName}_${new Date().format("yyyy_MM_dd")}_%s_build${appVersionCode}_%s"
    def oldApkPath=String.format(oldPrefixFormat,"10_34_38","tinker.apk")
    def applyMappingPath=String.format(oldPrefixFormat,"10_34_38","mapping.txt")
    def resourcePath=String.format(oldPrefixFormat,"10_34_38","R.txt")
    //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}/${oldApkPath}"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/${applyMappingPath}"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/${resourcePath}"

    //only use for build all flavor, if not, just ignore this field
    tinkerBuildFlavorDirectory = "${bakPath}/app-patch-${releaseTime()}"
}

4.tinker編譯差分包的task配置

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 = 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
         */
        useSign = true

        /**
         * optional,default 'true'
         * whether use tinker to build
         */
        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!
             */
            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 = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
            keepDexApply = 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
             */
            dexMode = "jar"

            /**
             * 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 = [
                    //use sample, let BaseBuildInfo unchangeable with tinker
                    "com.simpletour.client.tinker.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/*/*.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"
        }
    }

5.拷貝和自定義apk、mapping、R檔案的別名

   /**
     * bak apk and mapping
     */
    android.applicationVariants.all { variant ->
        /**
         * task type, you want to bak
         */
        def taskName = variant.name
        def date = new Date().format("yyyy_MM_dd_HH_mm_ss")
        def buildTypeName=variant.baseName+""
        def isRelease=buildTypeName=="release"
        tasks.all {
            if ("assemble${taskName.capitalize()}".equalsIgnoreCase(it.name)) {

                it.doLast {
                    copy {
                    //正常情況下生成的apk檔案的檔名字首
                        def fileNamePrefix = "${project.name}-${buildTypeName}"
                        //自定義apk檔案的別名
                        def newFileNamePrefix="app_beta1_${isRelease?"${buildTypeName}_":""}${appVersionName}_${date}_build${appVersionCode}"
                        //自定義apk、mapping、R檔案存放的目錄
                        def destPath = hasFlavors ? file("${bakPath}/${project.name}-${date}/${variant.flavorName}") : bakPath
                        //複製apk檔案和重新命名
                        from variant.outputs.outputFile
                        into destPath
                        rename { String fileName ->
                            fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}_tinker.apk")
                        }
                        //複製和重新命名mapping檔案
                        from "${buildDir}/outputs/mapping/${variant.dirName}/mapping.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("mapping.txt", "${newFileNamePrefix}_mapping.txt")
                        }
                        //複製和重新命名R檔案
                        from "${buildDir}/intermediates/symbols/${variant.dirName}/R.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("R.txt", "${newFileNamePrefix}_R.txt")
                        }
                    }
                }
            }
        }
    }

有了上面這些基本的配置,基本上tinker的引入就算完成了。這裡要說一下引入multidex的目的不僅是解決65536的限制,還有就是因為tinker的修復原理是dex合併,所以必須支援multidex。還有就是編譯差分包的時候,老版本apk、mapping、R檔案的路徑一定要配正確,不然tinkerPatch任務會執行失敗。由於tinker不支援dex加固後的熱修復,所以採用dex加固加密的apk,就不能使用tinker來做熱更新了。最後要注意的就是,tinker補丁安裝完成後,必須重啟你的應用才能生效,在華為手機上甚至需要清除快取的應用程序後重啟才能生效。

下面是完整的app-build.gradle檔案

apply plugin: 'com.android.application'
def appVersionCode
def appVersionName
android {
    lintOptions {
        abortOnError false
    }
    //tinker recommend
    dexOptions{
        jumboMode true;
    }
    signingConfigs {
        release {
            keyAlias '你的簽名key的別名'
            keyPassword '你的簽名key的密碼'
            storeFile file('你的簽名檔案')
            storePassword '你的簽名檔案的密碼'
        }
        debug {
              keyAlias '你的簽名key的別名'
            keyPassword '你的簽名key的密碼'
            storeFile file('你的簽名檔案')
            storePassword '你的簽名檔案的密碼'
        }
    }
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "你的工程主module包名"
        minSdkVersion 15
        targetSdkVersion 23
        multiDexEnabled = true
        versionCode 68
        versionName "2.4.0"
        signingConfig signingConfigs.release
        //-------------------------tinker config start-------------------------
        appVersionCode=versionCode
        appVersionName="v".concat(versionName)
        buildConfigField "String","TINKER_VERSION","\"1.7.7\""
        /**
         * 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\""
        //-------------------------tinker config end-------------------------

    }
    buildTypes {
        debug {
            // 不顯示log
            buildConfigField "boolean", "ENABLE_DEBUG", "true"
            //不啟用混淆編譯
            minifyEnabled false
            //移除無用的資原始檔
            shrinkResources true
            //Zipalign優化
            zipAlignEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
        release {
            // 不顯示log
            buildConfigField "boolean", "ENABLE_DEBUG", "false"
            //不啟用混淆編譯
            minifyEnabled false
            //移除無用的資原始檔
            shrinkResources true
            //Zipalign優化
            zipAlignEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
    //解決編譯時as記憶體溢位
    dexOptions {
        preDexLibraries = false
        javaMaxHeapSize "4g"   //這個改大
    }
}

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}

def releaseTime() {
    return new Date().format("yyyy_MM_dd")
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    //tinker recommend options ,可選,用於生成application類
    provided("com.tencent.tinker:tinker-android-anno:1.7.7"
}
//-------------------------tinker build start-------------------------
//生成tinker_id,在app/build/intermediates/manifests/full/debug(或release)下的Manifest.xml
//檔案裡可以看到
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'")
    }
}
//自定義重新命名apk包和R.txt以及mapping.txt的存放目錄
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 {
    //這個是我自定義打包apk的名字的格式化字串(關於自定義輸出apk檔案的名字那些,參考後面的"bak apk and     //mapping"註釋那裡),這裡找到上次編譯的apk、mapping、R檔案,用來和本次新編譯的檔案做diff生成補丁包
    def oldPrefixFormat="app_beta1_${appVersionName}_${new Date().format("yyyy_MM_dd")}_%s_build${appVersionCode}_%s"
    def oldApkPath=String.format(oldPrefixFormat,"10_34_38","tinker.apk")
    def applyMappingPath=String.format(oldPrefixFormat,"10_34_38","mapping.txt")
    def resourcePath=String.format(oldPrefixFormat,"10_34_38","R.txt")
    //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}/${oldApkPath}"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/${applyMappingPath}"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/${resourcePath}"

    //only use for build all flavor, if not, just ignore this field
    //這個是你自定義的差分包相關檔案的輸出路徑
    tinkerBuildFlavorDirectory = "${bakPath}/app-patch-${releaseTime()}"
}

//下面這些是一些自定義的方法,用來獲取old apk的路徑、old mapping的路徑、生成tinker_id等
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
}
//重點來了,這裡是使用tinker編譯的許多配置資訊
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 = 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
         */
        useSign = true

        /**
         * optional,default 'true'
         * whether use tinker to build
         */
        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!
             */
            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 = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             */
            keepDexApply = 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
             */
            dexMode = "jar"

            /**
             * 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 = [
                    //use sample, let BaseBuildInfo unchangeable with tinker
                    "com.simpletour.client.tinker.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/*/*.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
    //自定義apk輸出別名請看這裡
    /**
     * bak apk and mapping
     */
    android.applicationVariants.all { variant ->
        /**
         * task type, you want to bak
         */
        def taskName = variant.name
        def date = new Date().format("yyyy_MM_dd_HH_mm_ss")
        def buildTypeName=variant.baseName+""
        def isRelease=buildTypeName=="release"
        tasks.all {
            if ("assemble${taskName.capitalize()}".equalsIgnoreCase(it.name)) {

                it.doLast {
                    copy {
                    //正常情況下生成的apk檔案的檔名字首
                        def fileNamePrefix = "${project.name}-${buildTypeName}"
                        //自定義apk檔案的別名
                        def newFileNamePrefix="app_beta1_${isRelease?"${buildTypeName}_":""}${appVersionName}_${date}_build${appVersionCode}"
                        //自定義apk、mapping、R檔案存放的目錄
                        def destPath = hasFlavors ? file("${bakPath}/${project.name}-${date}/${variant.flavorName}") : bakPath
                        //複製apk檔案和重新命名
                        from variant.outputs.outputFile
                        into destPath
                        rename { String fileName ->
                            fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}_tinker.apk")
                        }
                        //複製和重新命名mapping檔案
                        from "${buildDir}/outputs/mapping/${variant.dirName}/mapping.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("mapping.txt", "${newFileNamePrefix}_mapping.txt")
                        }
                        //複製和重新命名R檔案
                        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"
                    }

                }
            }
        }
    }
}
//-------------------------tinker build end-------------------------

額。。。是不是看起來好亂的樣子。。。但是不要擔心,一般都能編譯過的。

開始的時候我說:命令列算不上一種接入,僅僅是多了一種編譯差分包的方式而已。這裡就來解釋這個問題。
生成差分包的方式有兩種:一種是剛才我們在build檔案裡配的tinkerpatch任務,配置好老版本的apk、mapping(release版才需要)、R檔案,直接在build.gradle任務列表裡執行tinkerpatchdebug或tinkerpatchrelease任務即可生成對應的差分包;還有一種,要先clone tinker原始碼,編譯tinker-build/tinker-patch-cli專案,得到tinker-patch-cli-***jar,然後,每次把老版本的apk、mapping(release版才需要)、R檔案拷貝下來儲存好,apk檔案命名為old.apk ,然後編譯新版apk,新apk命名為new.apk,把old.apk和new.apk拷貝到tinker-build/tinker-patch-cli/tool_output目錄下,修改一下tinker_config檔案裡的幾個地方:

value的值必須用英文引號包起來

1.簽名檔案配置,

   <issue id="sign">
        <!--the signature file path, in window use \, in linux use /, and the default path is the running location-->
        <path value="你的簽名檔案的路徑"/>
        <!--storepass-->
        <storepass value="簽名檔案密碼"/>
        <!--keypass-->
        <keypass value="簽名key密碼"/>
        <!--alias-->
        <alias value="簽名檔案別名"/>
    </issue>

2.自定義繼承自TinkeApplication的你的apiilication類

    <issue id="dex">
        <!--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 value="jar"/>

        <!--what dexes in apk are expected to deal with tinkerPatch-->
        <!--it support * or ? pattern.-->
        <pattern value="classes*.dex"/>
        <pattern value="assets/secondary-dex-?.jar"/>

        <!--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 {@code SampleTinkerLoader}, and the classes you use in them-->
        <loader value="com.tencent.tinker.loader.*"/>
        **<loader value="包名.繼承自TinkeApplication的你的apiilication類"/>**
    </issue>

然後執行下面的命令:

java -jar tinker-patch-cli-1.7.7.jar -old old.apk -new new.apk -config tinker_config.xml -out output

這樣會在tinker-build/tinker-patch-cli/tool_output生成一個out_put資料夾,裡面包含一些檔案,主要的就是patch_signed.apk和patch_signed_7zip.apk(優化過後的差分包),一般不建議直接用apk檔案做補丁字尾名。

生成檔案如下
這裡寫圖片描述

到這裡,是否感覺到命令列方式有點小麻煩?所以我一般都是備份好上次釋出版本的apk等檔案,然後拷貝回工程的bak資料夾下,用gradle task編譯。

在來講講程式碼吧,我沒有使用tinker推薦的註解方式來生成application類,因為我們的專案已經迭代了很多版本,我們的Application裡面有很多自定義的東西,所以只能繼承自TinkerApplication關聯對應的DefaultApplicationLike來實現了

application檔案

/**
 * 包名:com.simpletour.client.app
 * 描述:主Application
 * 建立者:yankebin
 * 日期:2015/12/3
 * MApplication繼承自TinkerApplication
 */
public class SimpletourApp extends MApplication {
    private static volatile SimpletourApp app;
    private DisplayImageOptions avatarOptions;
    private DisplayImageOptions assistantOptions;
    //無參構造
    public SimpletourApp() {
    //這幾個引數的含義請參考[接入指南](https://github.com/Tencent/tinker/wiki/Tinker-接入指南)
        this(ShareConstants.TINKER_ENABLE_ALL, "com.simpletour.client.app.SimpleTourAppLike",//這個是自定義的DefaultApplicationLike
                "com.tencent.tinker.loader.TinkerLoader", false);
    }
    //TinkerApplication的構造方法
    protected SimpletourApp(int tinkerFlags, String delegateClassName, String loaderClassName, boolean tinkerLoadVerifyFlag){
        super(tinkerFlags,delegateClassName,loaderClassName,tinkerLoadVerifyFlag);
    }
    public DisplayImageOptions getAvatarOptions() {
        return avatarOptions;
    }

    public DisplayImageOptions getAssistantOptions() {
        return assistantOptions;
    }

    public static synchronized SimpletourApp getInstance() {
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        //初始化伺服器URL,測試環境才需要
        if (SDKConfig.DEVELOP_MODE) {
            Constant.initUrlConfig(this);
        }
        //服務端介面請求api初始化
        RetrofitApi.RetrofitConfig config = new RetrofitApi.RetrofitConfig.RequestBuilder()
                .defaultConfig(Constant.URL.URL_BASE_URL_).build();
        RetrofitApi.getInstance().init(config);
        //圖片載入器
        ToolImage.init(this, Constant.BASE_CACHE_DIR_NAME.concat("/cache/img"),
                R.drawable.default_img_retange);
        //日誌工具
        SLog.init(BuildConfig.ENABLE_DEBUG, Constant.BASE_CACHE_DIR_NAME.concat("/cache/log"));
        //友盟統計
        MobclickAgent.openActivityDurationTrack(false);
        //友盟推送
        PushAgent.getInstance(this).setDebugMode(BuildConfig.ENABLE_DEBUG);
        //啟動主服務
        startMainService();
        //初始化又拍雲上傳圖片sdk
        initUpLoadSdk();
        //初始化友盟分享sdk
        initShareSdk();
        //崩潰日誌
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
        //初始化百度地圖sdk
        SDKInitializer.initialize(this);
        //初始化美洽sdk
        initMeiQiaSdk();
        //初始化頭像顯示配置
        initAvatarOptions();
        //清除快取
        checkCache();
    }

    /**
     * 初始化頭像顯示的配置
     */
    private void initAvatarOptions() {
        avatarOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.header_login)
                .showImageForEmptyUri(R.drawable.header_login)// 空uri時的預設圖片
                .showImageOnFail(R.drawable.header_login)// 載入失敗時的預設圖片
                .cacheInMemory(true)// 是否快取到記憶體
                .cacheOnDisk(true)// 是否快取到磁碟
                .bitmapConfig(Bitmap.Config.RGB_565)// 圖片格式比RGB888少消耗2倍記憶體
                .imageScaleType(ImageScaleType.EXACTLY)// 圖片縮放方式
                .resetViewBeforeLoading(true)//有效避免oom的方式之一
                .build();

        assistantOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.assistant_gray_avatar)
                .showImageForEmptyUri(R.drawable.assistant_gray_avatar)// 空uri時的預設圖片
                .showImageOnFail(R.drawable.assistant_gray_avatar)// 載入失敗時的預設圖片
                .cacheInMemory(true)// 是否快取到記憶體
                .cacheOnDisk(true)// 是否快取到磁碟
                .bitmapConfig(Bitmap.Config.RGB_565)// 圖片格式比RGB888少消耗2倍記憶體
                .imageScaleType(ImageScaleType.EXACTLY)// 圖片縮放方式
                .resetViewBeforeLoading(true)//有效避免oom的方式之一
                .build();
    }

    /**
     * 初始化美洽sdk
     */
    private void initMeiQiaSdk() {
        MQConfig.init(this, Constant.KEY.MEI_QIA_SDK_APP_KEY, new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {
                SLog.d("meiqia init success");
            }

            @Override
            public void onFailure(int code, String message) {
                SLog.d("meiqia init failure");
            }
        });
    }

    /**
     * 初始化上傳圖片sdk
     */
    private void initUpLoadSdk() {
        UpConfig.BUCKET = "simpletour-image";
    }

    /**
     * 初始化分享sdk
     */
    private void initShareSdk() {
        ShareConfig.config();
    }

    /**
     * 檢測快取是否超過100M
     */
    private void checkCache() {
        long fileSize = 0;
        try {
            fileSize = GetFileSizeUtil.getInstance().getFileSize(StorageUtils.getOwnCacheDirectory(
                    this, Constant.BASE_CACHE_DIR_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        SLog.d("fileSize : " + fileSize);
        if (fileSize >= 1024 * 1024 * 100) {
            clearCache();
        }
    }

    /**
     * 獲取本地快取大小
     */
    public String getCacheSize() {
        return GetFileSizeUtil.getInstance().FormetFileSize(StorageUtils.getOwnCacheDirectory(this,
                Constant.BASE_CACHE_DIR_NAME));
    }

    /**
     * 清除快取
     */
    public void clearCache() {
        ToolFile.deleteFolder(StorageUtils.getOwnCacheDirectory(this,
                Constant.BASE_CACHE_DIR_NAME));
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(bas