自建服务端实现Tinker热修复

前言:

      最近工作不是很忙寻思着学习学习一些新技术or热门技术,热修复,听着好高大上啊,安卓高级程序员必会技能(高逼格技能~~)。热修复这一两年确实很火,技术文章满天飞,BAT等大公司都有一套自己的热修复框架,TinkerDexposedAndFixHotFixNuwa等等,热修复有两大流派:

  • Native,代表有阿里的Dexposed、AndFix与腾讯的内部方案KKFix;

  • Java,代表有Qzone的超级补丁、大众点评的nuwa、百度金融的rocooFix, 饿了么的amigo以及美团的robust。

Native流派与Java流派都有着自己的优缺点,它们具体差异可以参考这里~~,这些框架GitHub上都有实现原理和踩坑方法~~大家可以根据需求选择最适合自己的热修复框架。好了我们直奔主题!!

一、为什么使用Tinker?

     出至腾讯是微信官方的Android热补丁解决方案,我们每使用一个开源框架需要考虑的是性能、兼容性成功率、后期维护等。首先性能和兼容性大家看这里,作为一个拥有9亿用户的超级app,Tinker能够作为微信热修复支撑,极致的性能和兼容性是必须的,也是Tinker开发的初衷,经过了一系列的版本迭代到最新的1.9.2已经越发稳定成熟,然后再是维护,从16年9月第一次发布版本到目前为止更新了17个版本,2178次commit。。。可见微信团队一直在致力维护这个项目,而AndFix已经两年没更新了,issue也是一大堆问题没人解决。。看来阿里爸爸是放弃这个框架了~~~,dexposed也是一个样。。。贴个图各个热修复框架优势对比:

二、开始采坑之旅

1、安卓Tinker集成

     新建项目配置project的gradle:ps因为Tinker支持gradle配置,配置属性比较多最好直接拷贝过来再把你原有的gradle属性配置上去(要看懂这些配置属性是什么意思,需要有一定的gradle知识~~~)

buildscript {
    repositories {
        mavenLocal()
        google()
        jcenter()
    }

    dependencies {
        if (project.hasProperty('GRADLE_3') && GRADLE_3.equalsIgnoreCase('TRUE')) {
            classpath 'com.android.tools.build:gradle:3.0.0'
        } else {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        classpath "com.tencent.tinker:tinker-patch-gradle-plugin:${TINKER_VERSION}"
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
    }
}

def is_gradle_3() {
    return hasProperty('GRADLE_3') && GRADLE_3.equalsIgnoreCase('TRUE')
}复制代码

这个会报错:

别急,打开gradle.properties在最后面加入:

TINKER_VERSION=1.9.2
GRADLE_3=true复制代码

然后配置app的gradle(我把整个放放出来):

apply plugin: 'com.android.application'

dependencies {
    if (is_gradle_3()) {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        testImplementation 'junit:junit:4.12'
        implementation "com.android.support:appcompat-v7:23.1.1"
        implementation("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}") { changing = true }
        annotationProcessor("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") { changing = true }
        compileOnly("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") { changing = true }

        implementation "com.android.support:multidex:1.0.1"
        //use to test multiDex
//    implementation group: 'com.google.guava', name: 'guava', version: '19.0'
//    implementation "org.scala-lang:scala-library:2.11.7"

        //use for local maven test
//        implementation("com.tencent.tinker:tinker-android-loader:${TINKER_VERSION}") { changing = true }
//        implementation("com.tencent.tinker:aosp-dexutils:${TINKER_VERSION}") { changing = true }
//        implementation("com.tencent.tinker:bsdiff-util:${TINKER_VERSION}") { changing = true }
//        implementation("com.tencent.tinker:tinker-ziputils:${TINKER_VERSION}") { changing = true }
//        implementation("com.tencent.tinker:tinker-commons:${TINKER_VERSION}") { changing = true }
    } else {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile "com.android.support:appcompat-v7:23.1.1"
        compile("com.tencent.tinker:tinker-android-lib:${TINKER_VERSION}") { changing = true }
        provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") { changing = true }

        compile "com.android.support:multidex:1.0.1"

        //use to test multiDex
//    compile group: 'com.google.guava', name: 'guava', version: '19.0'
//    compile "org.scala-lang:scala-library:2.11.7"

        //use for local maven test
//        compile("com.tencent.tinker:tinker-android-loader:${TINKER_VERSION}") { changing = true }
//        compile("com.tencent.tinker:aosp-dexutils:${TINKER_VERSION}") { changing = true }
//        compile("com.tencent.tinker:bsdiff-util:${TINKER_VERSION}") { changing = true }
//        compile("com.tencent.tinker:tinker-ziputils:${TINKER_VERSION}") { changing = true }
//        compile("com.tencent.tinker:tinker-commons:${TINKER_VERSION}") { changing = true }
    }

    compile 'com.dx168.patchsdk:patchsdk:1.2.7'
}


def javaVersion = JavaVersion.VERSION_1_7

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    compileOptions {
        sourceCompatibility javaVersion
        targetCompatibility javaVersion
    }
    //recommend
    dexOptions {
        jumboMode = true
    }

//    signingConfigs {
//        release {
//            try {
//                storeFile file("./keystore/release.keystore")
//                storePassword "testres"
//                keyAlias "testres"
//                keyPassword "testres"
//            } catch (ex) {
//                throw new InvalidUserDataException(ex.toString())
//            }
//        }
//
//        debug {
//            storeFile file("./keystore/debug.keystore")
//        }
//    }

    defaultConfig {
        applicationId "com.oking.mytinker"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.0"
        /**
         * you can use multiDex and install it in your ApplicationLifeCycle implement
         */
        multiDexEnabled true
        /**
         * buildConfig can change during patch!
         * we can use the newly value when patch
         */
        buildConfigField "String", "MESSAGE", "\"I am the base apk\""
//        buildConfigField "String", "MESSAGE", "\"I am the patch 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\""
    }

//    aaptOptions{
//        cruncherEnabled false
//    }

//    //use to test flavors support
//    productFlavors {
//        flavor1 {
//            applicationId 'tinker.sample.android.flavor1'
//        }
//
//        flavor2 {
//            applicationId 'tinker.sample.android.flavor2'
//        }
//    }

    buildTypes {
        release {
            minifyEnabled true
//            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), project.file('proguard-rules.pro')
        }
        debug {
            debuggable true
            minifyEnabled false
//            signingConfig signingConfigs.debug
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}

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}/old-app.apk"
    // 基础包的mapping.txt文件路径(用于辅助混淆补丁包的生成,一般在生成release版app时会使用到混淆,所以这个mapping.txt文件一般只是用于release安装包补丁的生成)
    tinkerApplyMappingPath = "${bakPath}/old-app-mapping.txt"
    // 基础包的R.txt文件路径(如果你的安装包中资源文件有改动,则需要使用该R.txt文件来辅助生成补丁包)
    tinkerApplyResourcePath = "${bakPath}/old-app-R.txt"
    //only use for build all flavor, if not, just ignore this field
    tinkerBuildFlavorDirectory = "${bakPath}/flavor"
}


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 : android.defaultConfig.versionName
}

def buildWithTinker() {
    return hasProperty("TINKER_ENABLE") ? TINKER_ENABLE : ext.tinkerEnabled
}

def getTinkerBuildFlavorDirectory() {
    return ext.tinkerBuildFlavorDirectory
}

if (buildWithTinker()) {
    apply plugin: 'com.tencent.tinker.patch'

    tinkerPatch {
        /**
         * necessary,default 'null'
         * the old apk path, use to diff with the new apk to build
         * add apk from the build/bakApk
         */
        oldApk = getOldApkPath()
        /**
         * optional,default 'false'
         * there are some cases we may get some warnings
         * if ignoreWarning is true, we would just assert the patch process
         * case 1: minSdkVersion is below 14, but you are using dexMode with raw.
         *         it must be crash when load.
         * case 2: newly added Android Component in AndroidManifest.xml,
         *         it must be crash when load.
         * case 3: loader classes in dex.loader{} are not keep in the main dex,
         *         it must be let tinker not work.
         * case 4: loader classes in dex.loader{} changes,
         *         loader classes is ues to load patch dex. it is useless to change them.
         *         it won't crash, but these changes can't effect. you may ignore it
         * case 5: resources.arsc has changed, but we don't use applyResourceMapping to build
         */
        ignoreWarning = true    // 是否忽略有风险的补丁包。这里选择忽略,当补丁包风险时不会中断编译。

        /**
         * optional,default 'true'
         * whether sign the patch file
         * if not, you must do yourself. otherwise it can't check success during the patch loading
         * we will use the sign config with your build type
         */
        useSign = true

        /**
         * 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

            /**
             * 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.
             */
            isProtectedApp = false

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

        dex {
            /**
             * optional,default 'jar'
             * only can be 'raw' or 'jar'. for raw, we would keep its original format
             * for jar, we would repack dexes with zip format.
             * if you want to support below 14, you must use jar
             * or you want to save rom or check quicker, you can use raw mode also
             */
            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
                    "tinker.sample.android.app.BaseBuildInfo"
            ]
        }

        lib {
            /**
             * optional,default '[]'
             * what library in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             * for library in assets, we would just recover them in the patch directory
             * you can get them in TinkerLoadResult with Tinker
             */
            pattern = ["lib/*/*.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
    def date = new Date().format("MMdd-HH-mm-ss")

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

        tasks.all {
            if ("assemble${taskName.capitalize()}".equalsIgnoreCase(it.name)) {

                it.doLast {
                    copy {
                        def fileNamePrefix = "${project.name}-${variant.baseName}"
                        def newFileNamePrefix = hasFlavors ? "${fileNamePrefix}" : "${fileNamePrefix}-${date}"

                        def destPath = hasFlavors ? file("${bakPath}/${project.name}-${date}/${variant.flavorName}") : bakPath
                        from variant.outputs.first().outputFile
                        into destPath
                        rename { String fileName ->
                            fileName.replace("${fileNamePrefix}.apk", "${newFileNamePrefix}.apk")
                        }

                        from "${buildDir}/outputs/mapping/${variant.dirName}/mapping.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("mapping.txt", "${newFileNamePrefix}-mapping.txt")
                        }

                        from "${buildDir}/intermediates/symbols/${variant.dirName}/R.txt"
                        into destPath
                        rename { String fileName ->
                            fileName.replace("R.txt", "${newFileNamePrefix}-R.txt")
                        }
                    }
                }
            }
        }
    }
    project.afterEvaluate {
        //sample use for build all flavor for one time
        if (hasFlavors) {
            task(tinkerPatchAllFlavorRelease) {
                group = 'tinker'
                def originOldPath = getTinkerBuildFlavorDirectory()
                for (String flavor : flavors) {
                    def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Release")
                    dependsOn tinkerTask
                    def preAssembleTask = tasks.getByName("process${flavor.capitalize()}ReleaseManifest")
                    preAssembleTask.doFirst {
                        String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 15)
                        project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release.apk"
                        project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-mapping.txt"
                        project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-release-R.txt"

                    }

                }
            }

            task(tinkerPatchAllFlavorDebug) {
                group = 'tinker'
                def originOldPath = getTinkerBuildFlavorDirectory()
                for (String flavor : flavors) {
                    def tinkerTask = tasks.getByName("tinkerPatch${flavor.capitalize()}Debug")
                    dependsOn tinkerTask
                    def preAssembleTask = tasks.getByName("process${flavor.capitalize()}DebugManifest")
                    preAssembleTask.doFirst {
                        String flavorName = preAssembleTask.name.substring(7, 8).toLowerCase() + preAssembleTask.name.substring(8, preAssembleTask.name.length() - 13)
                        project.tinkerPatch.oldApk = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug.apk"
                        project.tinkerPatch.buildConfig.applyMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-mapping.txt"
                        project.tinkerPatch.buildConfig.applyResourceMapping = "${originOldPath}/${flavorName}/${project.name}-${flavorName}-debug-R.txt"
                    }

                }
            }
        }
    }
}

复制代码

在这里特别需要注意的几点:

    1)、如果出现这个错误

请检查这个是否配置正确

def getTinkerIdValue() {
    return hasProperty("TINKER_ID") ? TINKER_ID : android.defaultConfig.versionName
}复制代码

ps:我拷贝官方demo例子的gradle配置就报这个错,后来把它改成上面一样就行了。

     2)、把这个改为true:ignoreWarning = true   // 是否忽略有风险的补丁包。这里选择忽略,当补丁包风险时不会中断编译。不然在生成补丁包会出错。

    3)、然后就是这个:

tinkerOldApkPath:基础包所在路径复制代码

之所以改成old-app.apk,主要是为了区分新的apk和基础包,因为每次build一次都会生成一个apk

虽然每次都不同,你不改下名字根据编号很容易搞错。官方例子是用的apk名称ps:old-app.apk和old-app-mapping.txt很重要!!!你后面制作补丁都需要根据这个基础包来制作,最好保存好并备份!!,如果不小心弄丢了,那就只能推送更新app吧~~~

基础包:指的是发布出去的安装包(用户正在使用的安装包)。

4)、注意这个BuildInfo引用的BuildConfig类:


一开始会报错,找不到这个BuildConfig类,你build一下就出来了。ps:我能说我直接把这个BuildInfo给的PLATFORM改成空了么,在后面打补丁死活打不上~~~~~,主要还是gradle配置不能出错~~~~


这里的字段都是gradle配置的时候生成的。


配置好gradle后build下,看下是否成功,然后切换project视图app>build目录下是否生成bakApk目录,上图所示。

打开gradle操作界面双击TinkerPatchDebug,生成补丁包


切换project视图app>build>outputs>tinkerPatch目录下看是否生成补丁:


解释:


如果失败或者没有生成这些个文件夹,请仔细检查你的gradle配置是否正确~~。

拷贝java文件(官方demo的这些文件~~):




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

这些只是对Tinker功能的拓展和封装,都是可选的,你也可以自己封装

TinkerApplication,这个类并不是继承Application,如果自己有自定义的application可以把初始化操作放在onCreat()方法里面:

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

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

    // 固定写法
    public TinkerApplication(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()方法所执行的操作搬到这里...
    }

    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());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 将之前自定义的Application中onCreate()方法所执行的操作搬到这里...

        String appId = "20171213203556412-8689";
        String appSecret = "cd34d15329cb4caeac3bbd4dc335707d";
        PatchManager.getInstance().init(getApplication(), "http://192.168.0.105:8080/hotfix-apis", appId, appSecret, new IPatchManager() {
            @Override
            public void cleanPatch(Context context) {
//                TinkerInstaller.cleanPatch(context);
            }

            @Override
            public void patch(Context context, String patchPath) {
//                TinkerInstaller.onReceiveUpgradePatch(context, patchPath);
                Contact.patchPath = patchPath;
                System.out.println("patch:"+patchPath);

            }
        });
        PatchManager.getInstance().register(new Listener() {
            @Override
            public void onQuerySuccess(String response) {
                Log.d("TinkerApplication","获取补丁成功"+response);
            }

            @Override
            public void onQueryFailure(Throwable e) {
                Log.d("TinkerApplication","获取补丁失败"+e.getMessage());
            }

            @Override
            public void onDownloadSuccess(String path) {
                Log.d("TinkerApplication","下载补丁成功"+path);
            }

            @Override
            public void onDownloadFailure(Throwable e) {

            }

            @Override
            public void onPatchSuccess() {

            }

            @Override
            public void onPatchFailure(String error) {

            }

            @Override
            public void onLoadSuccess() {

            }

            @Override
            public void onLoadFailure(String error) {

            }
        });
        PatchManager.getInstance().setTag("");
        PatchManager.getInstance().setChannel("");
        PatchManager.getInstance().queryAndPatch();
    }
}

复制代码

清单文件:

权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>复制代码

application

这个文件是动态生成,不存在我们项目中的,但是我们项目是可以引用的

android:name=".OriginalApplication"复制代码

Service

<service
    android:name="com.oking.mytinker.tinker.SampleResultService"
    android:exported="false"/>复制代码

三、服务器搭建

放个Github地址

1、下载部署所需要的文件(war包、配置文件、建库sql文件) war包下载.

2、在mysql(需要5.x版本)里面建数据库,建表sql在patchserver-manager/import.sql中

3、把hotfix-apis.properties和hotfix-console.properties两个配置文件放到/opt/config(*如果是windows部署,放置在tomcat对应的盘符下,假如tomcat在d://tomcat 目录配置文件就放在d://opt/config目录下,并且修改里面对应的配置(数据源配置、访问路径配置、补丁存放目录)

4、把hotfix-apis.war hotfix-console.war放到tomcat下面的webapps目录下

等服务启动完毕就可以在浏览器上访问http://localhost:8080/hotfix-console

会配置Tomcat或者会一点Javaee方面的知识的部署起来会很容易。

下载Tomcat配置好环境变量

安装数据库Mysql新建数据库patch_manager,ps:注意名称要和配置文件数据库名称一致

修改hotfix-apis.properties配置文件


修改hotfix-console.properties文件


注意上面加粗说明,文件别放错了!!给个部署参照

拷贝war包到tomcat的webapp目录下

运行Tomcat服务器

访问地址,注册登录。


到目前为止我们已经把Tinker集成好了,服务器也部署成功了,下面我们来撸代码~~~

四、撸代码、实操

app的Gradle加入一行

compile 'com.dx168.patchsdk:patchsdk:1.2.7'复制代码

上面集成Tinker的时候有加上就不用加了

TinkerApplication的onCreat方法里面加入:

        String appId = "20171214154046922-6495";
        String appSecret = "9f820d28ac854e9a82e755fefd69ea63";
        PatchManager.getInstance().init(getApplication(), "http://192.168.0.105:8080/hotfix-apis", appId, appSecret, new IPatchManager() {
            @Override
            public void cleanPatch(Context context) {
//                TinkerInstaller.cleanPatch(context);
            }

            @Override
            public void patch(Context context, String patchPath) {
//                TinkerInstaller.onReceiveUpgradePatch(context, patchPath);
                Contact.patchPath = patchPath;
                System.out.println("patch:"+patchPath);

            }
        });
        PatchManager.getInstance().register(new Listener() {
            @Override
            public void onQuerySuccess(String response) {
                Log.d("TinkerApplication","获取补丁成功"+response);
            }

            @Override
            public void onQueryFailure(Throwable e) {
                Log.d("TinkerApplication","获取补丁失败"+e.getMessage());
            }

            @Override
            public void onDownloadSuccess(String path) {
                Log.d("TinkerApplication","下载补丁成功"+path);
            }

            @Override
            public void onDownloadFailure(Throwable e) {

            }

            @Override
            public void onPatchSuccess() {

            }

            @Override
            public void onPatchFailure(String error) {

            }

            @Override
            public void onLoadSuccess() {

            }

            @Override
            public void onLoadFailure(String error) {

            }
        });
        PatchManager.getInstance().setTag("");
        PatchManager.getInstance().setChannel("");
        PatchManager.getInstance().queryAndPatch();复制代码

我们登录补丁管理后台,创建应用后面会得到appId和appSecret,保存好:


用过第三方平台的都明白是什么意思,这个也是一样的。

创建一个版本:


在AS中build project

然后把安装包并发送到手机上进行安装(ps我这直接改了名字了~~):


安卓界面我们长这样~~~ps注意中间文本和Toast~:


假设我们项目上线了突然出现紧急bug(如果用检测更新推送新安装包,这个用户体验就很不好了~~安装包不要流量?一个小小的bug就让我下载安装包更新?差评啊,卸载~~~)

我们修复好的代码:




然后,我们找到上个版本安装包和txt文件把它放在bakApk目录下改名为old-app,切换到gradle视图双击tinkerPatchDebug:


找到patch_signed_7zip.apk补丁包,拷贝到桌面



进入补丁管理后台上传补丁:


发布补丁:


重新打开app点击“修复”按钮:

查看控制台打印日志

app界面有修复成功提示



然后点退出,重新打开应用我们上面修改的代码都同步到app上来了,用户不用重新下载安装包且无感知修复bug:


整个热修复过程就这样~~~说实话有点复杂~~

ps:修复成功后再点击修复按钮是没用的,一个补丁成功完成一次修复使命也就结束了,同时补丁文件也被删除了(不用担心补丁塞满sd卡啥的~~),即使你再次用同一个补丁也是打不了补丁的,这就是补丁的作用,Tinker为我们做了处理,不过你可以卸载某个版本的补丁或者全部补丁~~~,具体请看文档。。。。


五、总结

Tinker的热修复远不止我讲的这些像资源文件、so、library修复等,更深层次原理性的东西还需要进一步去学习~~~官方WIKI文档。

关于那个补丁管理平台,开源的后台,下发补丁,管理补丁、补丁统计、黑名单机制等等。还有源代码,有兴趣的大佬可以去研究研究改造改造~~,这样我们就不用出钱给第三方补丁平台了。。。如果单纯的就下发补丁,可以不用这个平台,后台写个类似版本更新的接口就可以,下载文件>修复。平台的好处就是更加方便、智能化管理、统计数据。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值