天天看點

站在巨人的肩上——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 = 
        }

        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 
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "你的工程主module包名"
        minSdkVersion 
        targetSdkVersion 
        multiDexEnabled = true
        versionCode 
        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 = 
        }

        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() > 
    //自定義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(, ).toLowerCase() + preAssembleTask.name.substring(, preAssembleTask.name.length() - )
                        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(, ).toLowerCase() + preAssembleTask.name.substring(, preAssembleTask.name.length() - )
                        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-.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檔案做更新檔字尾名。

生成檔案如下

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

到這裡,是否感覺到指令行方式有點小麻煩?是以我一般都是備份好上次釋出版本的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 = ;
        try {
            fileSize = GetFileSizeUtil.getInstance().getFileSize(StorageUtils.getOwnCacheDirectory(
                    this, Constant.BASE_CACHE_DIR_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        SLog.d("fileSize : " + fileSize);
        if (fileSize >=  *  * ) {
            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(base);//多jar包
    }

     * 開啟上傳devicetoken的服務
     */
    public void startMainService() {
        Intent intent = new Intent(this, SimpletourService.class);
        intent.setAction(SimpletourService.ACTION_UPLOAD_DEVICE_TOKE);
        startService(intent);
    }

    /**
     * 崩潰日志抓取
     */
    private Thread.UncaughtExceptionHandler exceptionHandler = (thread, ex) -> {
        //友盟統計錯誤
        MobclickAgent.reportError(getApplicationContext(), ex);
        SLog.a(ex);
        ex.printStackTrace();
    };
}
           

SimpleTourAppLike檔案

**
 * 包名:com.simpletour.client.app
 * 描述:tinker applicatio依賴類
 * 建立者:yankebin
 * 日期://
 */
public class SimpleTourAppLike extends DefaultApplicationLike {
    public SimpleTourAppLike(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)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        //必須在初始化tinker之前調用
        MultiDex.install(base);

        //下面這些代碼在tinker-sample-android項目下都可以找到
        TinkerManager.setTinkerApplicationLike(this);
        TinkerManager.initFastCrashProtect();
        //should set before tinker is installed
        TinkerManager.setUpgradeRetryEnable(true);

        //optional set logIml, or you can use default debug log
        TinkerInstaller.setLogIml(new MyLogImp());

        //installTinker after load multiDex
        //or you can put com.tencent.tinker.** to main dex
        TinkerManager.installTinker(this);
        Tinker.with(getApplication());
    }
}
           

最後,把你的差分包patch_signed.apk或patch_signed_7zip.apk檔案push到你的sd卡或其他位置,在activity或則其他任何你可以操作的地方調用

//cacheFilePath就是你放置差分包的路徑
TinkerInstaller.onReceiveUpgradePatch(getContext(),cacheFilePath);
           

然後安裝時需要時間的,稍等一下關閉并重新開機你的應用,如果不行,就先用手機自帶的記憶體清理清除你的應用在背景的緩存再重新開機即可。

到此,tinker的接入和實作基本上介紹完了。關于在安裝的時候你可以用tinker的api去檢測是否安裝了更新檔,然後在代碼裡退出應用并重新開機應用,這樣就可以實作自動更新更新檔了。

最後,如果你覺得每次推送更新檔到手機比較麻煩,你可以用tomcat或nginx搭建一個簡單的下載下傳伺服器,把更新檔放到下載下傳目錄,然後在用戶端去下載下傳然後安裝進行測試。

繼續閱讀