踩坑热修复框架Tinker

Tinker是什么

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

为什么使用Tinker

当前市面的热补丁方案有很多,其中比较出名的有阿里的AndFix、美团的Robust以及QZone的超级补丁方案。但它们都存在无法解决的问题,这也是正是使用Tinker的原因。

总的来说:
1、AndFix作为native解决方案,首先面临的是稳定性与兼容性问题,更重要的是它无法实现类替换,它是需要大量额外的开发成本的;
2、Robust兼容性与成功率较高,但是它与AndFix一样,无法新增变量与类只能用做的bugFix方案;
3、Qzone方案可以做到发布产品功能,但是它主要问题是插桩带来Dalvik的性能问题,以及为了解决Art下内存地址问题而导致补丁包急速增大的。

Tinker的已知问题

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

以上关于Tinker的介绍来自Tinker官方Wiki

Tinker集成

一、配置gradle

1,在项目的gradle.properties文件中添加Tinker的版本号

TINKER_VERSION=1.9.14.3
#TINKER_ID主要作用是区分当前打出的补丁包是基于哪个版本的apk,也就是说当前打出的补丁包能修复哪个版本的bug。这里可以填versionName
versionName=1.0.1
TINKER_ENABLE=true
android.enableD8.desugaring = true
android.useDexArchive = true

2,在项目的build.gradle中,添加tinker-patch-gradle-plugin的依赖

  dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.14.3')

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

3,在app的gradle文件app/build.gradle,添加tinker的库依赖

implementation 'com.android.support:multidex:1.0.3'
//optional, help to generate the final application
 compileOnly('com.tencent.tinker:tinker-android-anno:1.9.14.3')
//tinker's main Android lib
implementation('com.tencent.tinker:tinker-android-lib:1.9.14.3')

4,在app的gradle文件app/build.gradle,添加tinker的相关配置

下面就把整个app/build.gradle配置提出来,其中Tinker相关配置抽取到另一个文件tinkerpatch.gradle,其中比较重要的属性都标有中文注释,其余属性解释可以自行参考 Tinker 接入指南

apply from: 'tinkerpatch.gradle'
apply plugin: 'com.tencent.tinker.patch'

//-----------------------tinker配置区-----------------------------
def bakPath = file("${buildDir}/bakApk/")
def baseInfo = "app-release-1018-17-55-04"//这里需要修改为build/bakApk下面比对的旧包名字。这里填对应发版的文件名,只会修复发这个版本之后的bug,以前发的其它版本不起作用

//def gitSha() {//该方法需要安装git,并将项目与git建立连接,本例中不使用git,故注释
//    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'")
//    }
//}

/**
 * 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 sp = project.gradle.startParameter
    def taskName = sp.taskNames[0]
    def isopenthinker = true
    if (taskName.equals(":app:assembleDebug")) {
        isopenthinker = false
    }
    //for some reason, you may want to ignore tinkerBuild, such as instant run debug build?
    tinkerEnabled = isopenthinker

    //for normal build
    //old apk file to build patch apk
    tinkerOldApkPath = "${bakPath}/${baseInfo}.apk"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/${baseInfo}-mapping.txt"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/${baseInfo}-R.txt"

    //only use for build all flavor, if not, just ignore this field
    tinkerBuildFlavorDirectory = "${bakPath}/app-1018-17-32-47"
}


def getOldApkPath() {
    return hasProperty("OLD_APK") ? OLD_APK : ext.tinkerOldApkPath
}

def getApplyMappingPath() {
    return hasProperty("APPLY_MAPPING") ? APPLY_MAPPING : ext.tinkerApplyMappingPath
}

def getApplyResourceMappingPath() {
    return hasProperty("APPLY_RESOURCE") ? APPLY_RESOURCE : ext.tinkerApplyResourcePath
}

def getTinkerIdValue() {
//    return hasProperty("TINKER_ID") ? TINKER_ID : gitSha()
    return versionName //需要保证TINKER_ID有设置(在gradle.properties中)
}

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
         * 必须,默认为null
         * 基准apk包的路径
         */
        oldApk = getOldApkPath()
        /**
         *
         * optional,default 'false'
         * there are some cases we may get some warnings
         * if ignoreWarning is true, we would just assert the patch process
         * case 1: minSdkVersion is below 14, but you are using dexMode with raw.
         *         it must be crash when load.
         * case 2: newly added Android Component in AndroidManifest.xml,
         *         it must be crash when load.
         * case 3: loader classes in dex.loader{} are not keep in the main dex,
         *         it must be let tinker not work.
         * case 4: loader classes in dex.loader{} changes,
         *         loader classes is ues to load patch dex. it is useless to change them.
         *         it won't crash, but these changes can't effect. you may ignore it
         * case 5: resources.arsc has changed, but we don't use applyResourceMapping to build
         *
         * 可选,默认为false
         * 当设置false,可能会出现以下警告:
         * 1.minSdkVersion小于14,但你使用的是dexMode为"raw",加载时会崩溃
         * 2.AndroidManifest.xml中新增的Android组件,加载时会崩溃。
         * 3.dex.loader {}中的加载器类不保留在主dex中,会导致tinker无效
         * 4.加载器类在dex.loader {}中发生变化,加载器类用于加载补丁dex。改变它们是没有用的。它不会崩溃,但这些更改不会生效。你可以忽略它
         * 5.resources.arsc已更改,但我们不使用applyResourceMapping来构建
         */
        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
         * 可选,默认为true
         * 是否为你签名补丁文件
         * 如果false,则需要自己签名
         */
        useSign = true

        /**
         * 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!
             * 如果使用tinkerPatch构建补丁的apk,那么如果启用了minifyEnabled,则最好使用旧的apk mapping文件
             */
            applyMapping = getApplyMappingPath()
            /**
             * optional,default 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             * 可以保留R.txt文件中的资源来减少java的更改
             */
            applyResourceMapping = getApplyResourceMappingPath()

            /**
             * necessary,default 'null'
             * because we don't want to check the base apk with md5 in the runtime(it is slow)
             * tinkerId is use to identify the unique base apk when the patch is tried to apply.
             * we can use git rev, svn rev or simply versionCode.
             * we will gen the tinkerId in your manifest automatic
             * 这里就是我们需要设置的tinkerId
             */
            tinkerId = getTinkerIdValue()

            /**
             * if keepDexApply is true, class in which dex refer to the old apk.
             * open this can reduce the dex diff file size.
             * 如果为true,则dex指旧的apk,打开可以减少dex diff的文件大小
             */
            keepDexApply = false

            /**
             * optional, default 'false'
             * Whether tinker should treat the base apk as the one being protected by app
             * protection tools.
             * If this attribute is true, the generated patch package will contain a
             * dex including all changed classes instead of any dexdiff patch-info files.
             * 是否修补程序应该将基本apk视为受应用程序保护工具保护的那个。 如果此属性为true,
             * 则生成的修补程序包将包含一个dex,其中包含所有已更改的类,而不是任何dexdiff patch-info文件。
             */
            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>
             * 如果此属性为true,则新补丁程序中添加的组件将在补丁程序成功加载后可用。 否则在编译时生成补丁时会报错。
             */
            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
             * 对于raw,会保留原来的格式,对于jar,会用zip格式重新打包dex,如果要支持14以下,必须使用jar,如果想保存rom或更快检查,则可使用raw
             */
            dexMode = "jar"

            /**
             * necessary,default '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             * 需要处理dex路径,支持*、?通配符,路径是相对安装包的
             */
            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
             * 这一项非常重要,它定义了哪些类在加载补丁包的时候会用到。这些类是通过Tinker无法修改的类,也是一定要放在main dex的类。
             * 这里需要定义的类有:
             * 1. 你自己定义的Application类;
             * 2. Tinker库中用于加载补丁包的部分类,即com.tencent.tinker.loader.*;
             * 3. 如果你自定义了TinkerLoader,需要将它以及它引用的所有类也加入loader中;
             * 4. 其他一些你不希望被更改的类,例如Sample中的BaseBuildInfo类。这里需要注意的是,这些类的直接引用类也需要加入到loader中。或者你需要将这个类变成非preverify。
             * 5. 使用1.7.6版本之后版本,参数1、2会自动填写。
             *
             */
            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的pattern,在编译时会忽略该文件的新增、删除与修改。
             */
            ignoreChange = ["assets/sample_meta.txt"]

            /**
             * default 100kb
             * for modify resource, if it is larger than 'largeModSize'
             * we would like to use bsdiff algorithm to reduce patch file size
             * 对于修改的资源,如果大于largeModSize,将使用bsdiff算法。
             * 这可以降低补丁包的大小,但是会增加合成时的复杂度。
             */
            largeModSize = 100
        }

        packageConfig {//用于生成补丁包中的’package_meta.txt’文件
            /**
             * optional,default 'TINKER_ID, TINKER_ID_VALUE' 'NEW_TINKER_ID, NEW_TINKER_ID_VALUE'
             * package meta file gen. path is assets/package_meta.txt in patch file
             * you can use securityCheck.getPackageProperties() in your ownPackageCheck method
             * or TinkerLoadResult.getPackageConfigByName
             * we will get the TINKER_ID from the old apk manifest for you automatic,
             * other config files (such as patchMessage below)is not necessary
             * configField(“key”, “value”), 默认我们自动从基准安装包与新安装包的Manifest中读取tinkerId,并自动写入configField。
             * 在这里,你可以定义其他的信息,在运行时可以通过TinkerLoadResult.getPackageConfigByName得到
             */
            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"
                    }

                }
            }
        }
    }
}
//---------------------tinker配置结束----------------------------------

二、自定义Application类

程序启动时会加载默认的Application类,这导致补丁包无法对它做修改。所以Tinker官方说不建议自己去实现Application,而是由Tinker自动生成。即需要创建一个SampleApplication类,继承DefaultApplicationLike,然后将我们自己的MyApplication中所有逻辑放在SampleApplication中的onCreate中。最后需要将我们项目中之前的MyApplication类删除。如下


 /**
  * @author chenli 
  * @create 
   * @Describe 集成官方给的application
  */
@DefaultLifeCycle(application = "com.example.zhuguoqing.ztinker.ZTinkerApp",
        //这里填写包名和你想要生成的Application类名,tinker会自动生成该类
        flags = ShareConstants.TINKER_ENABLE_ALL)


public class SampleApplicationLike extends DefaultApplicationLike {


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



    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        
        TinkerInstaller.install(this);
        MultiDex.install(base);

    }
}

其中DefaultLifeCycle中的ZTinkerApp为我们真正的Application,清单文件中的Application的name改为ZTinkerApp的全路径。如下:


    <application
        android:name=".ZTinkerApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:process=":restart"
            android:name=".killSelfService" />
    </application>
/**
 * 热更新
 * @author chenli
 * @date 2019/10/24
 * @since 1.0
 * @version 1.0
 * @copyRights
 */
public class TinkerManager {
    private static final String TAG = "Tinker.TinkerManager";

    private static boolean isInstalled = false;

    /**
     * you can specify all class you want.
     * sometimes, you can only install tinker in some process you want!
     *
     * @param appLike
     */
    public static void installTinker(ApplicationLike appLike) {
        if (isInstalled) {
            TinkerLog.w(TAG, "install tinker, but has installed, ignore");
            return;
        }
        //
        //调试模式下 才开启Tinker日志
        if(!BuildConfig.DEBUG){
            TinkerLog.setTinkerLogImp(null);
        }

        //you can set your own upgrade patch if you need
        AbstractPatch upgradePatchProcessor = null;
        //适配小米
        if(PropertiesHelper.getInstance().isXM()&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){
            upgradePatchProcessor = new PatchProcessor();
        }else{
            upgradePatchProcessor = new UpgradePatch();
        }

        TinkerInstaller.install(appLike,
                new DefaultLoadReporter(appLike.getApplication()),
                new DefaultPatchReporter(appLike.getApplication()),
                new DefaultPatchListener(appLike.getApplication()),
                 LoadPatchService.class,
                upgradePatchProcessor);

        isInstalled = true;
        //使用Hack的方式,如果补丁中有so库 那么直接加载补丁中的armeabi-v7a下的so库(将tinker library中的armeabi-v7a注册到系统的library path中。)
        TinkerLoadLibrary.installNavitveLibraryABI(appLike.getApplication(), "armeabi-v7a");
    }
}

三、在清单文件添加读写sd卡的权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

四、加载补丁包代码


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    if (granted) {
//                        Observable.timer(5, TimeUnit.SECONDS).subscribe {
//                            if (isAppInBackground(this)) {
////                                TinkerInstaller.onReceiveUpgradePatch(application.applicationContext, Environment.getExternalStorageDirectory().absolutePath + "/ouyu.patch")//不要以.apk结尾,因为有些运营商会挟持以.apk结尾的资源
//                            }
//                        }
                    } else {
                    }
                }

        btTinker.setOnClickListener {
            Observable.timer(5, TimeUnit.SECONDS).subscribe {
                if (isAppInBackground(this)) {
//                                TinkerInstaller.onReceiveUpgradePatch(application.applicationContext, Environment.getExternalStorageDirectory().absolutePath + "/ouyu.patch")//不要以.apk结尾,因为有些运营商会挟持以.apk结尾的资源
//                                deleteFile(Environment.getExternalStorageDirectory().absolutePath + "/ouyu.patch")
                    TinkerInstaller.onReceiveUpgradePatch(application.applicationContext, Environment.getExternalStorageDirectory().absolutePath + "/ouyu.patch")//不要以.apk结尾,因为有些运营商会挟持以.apk结尾的资源
                }
            }
        }

    }

    /**
     * APP是否运行在后台
     *
     * @param context
     * @return
     */
    private fun isAppInBackground(context: Context): Boolean {
        var isInBackground = true
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { // Android5.0及以后的检测方法
            val runningProcesses = am.runningAppProcesses
            for (processInfo in runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (activeProcess in processInfo.pkgList) {
                        if (activeProcess == context.packageName) {
                            isInBackground = false
                        }
                    }
                }
            }
        } else {
            val taskInfo = am.getRunningTasks(1)
            val componentInfo = taskInfo[0].topActivity
            if (componentInfo.packageName == context.packageName) {
                isInBackground = false
            }
        }
        return isInBackground
    }
}

测试Tinker热修复

这里只讲release版本。

一、按正常流程打包出带签名的APK,并装到手机上

打包完成,会自动在项目的app/build文件夹下生成bakAPK文件夹并有三个文件(基础包的一些文件),如图:

二、将上面的三个文件路径复制到app.build中对应的位置,如图

三、修复bug(测试的时候随便改动一点代码)

四、运行补丁命令获取补丁包

运行补丁命令,单击AS右侧顶部gradle-->双击tinkerPatchRelease,如图:
(也可以直接在Android studio中的Terminal中输入命令gradlew tinkerPatchRelease)

运行完成会在build->outputs->tinkerPatch->release文件夹中生成一个名为patch_signed_7zip.apk的补丁包,如图:

五、将该补丁包复制到之前加载补丁包中对应的SD卡路劲即可。

注意:该补丁包需要重新命名,不要以.apk结尾,因为有些运营商会挟持以.apk结尾的资源,名字要与之前加载补丁包的名字相同,例如Demo中命名为patch_signed_7zip。

六、运行项目发现bug并没有修复,因为tinker是不支持即时修复的,关掉APP重启。恭喜你!bug已修复!

七、存放补丁包的平台选取

1,存放在自己公司的服务器
2,使用TinkerPatch平台,需要收费
3,腾讯Bugly平台,免费
为了安全与经济考虑,我们公司选取了第一种。大家可以根据自己的需要选择。

tinkerId应该如何选择?

tinkerId主要作用是区分当前打出的补丁包是基于哪个版本的apk,也就是说当前打出的补丁包能修复哪个版本的bug。每次发布版本需要保证tinkerId一定是要唯一性的,Tiker官方推荐使用git版本号或者versionName作为tinkerId。我自己项目使用的是versionName,你可以将versionName配置在项目的gradle.properties文件中,这样就不用每次都修改tinkerId了。如图:

后台接口的设计

问题:如果A用户用1.0.0版本的APK,B用户用2.0.0版本的APK,这个时候1.0.0和2.0.0都有对应的补丁包。接口该怎么设计?

方案: (可以保证用1.0.0还是2.0.0的用户都可以修复)
叫后台给一个接口,前端传versionName给后台(这里的versionName要保证和TinkerID一样), 传1.0.0后台就返回1.0.0的补丁包。传2.0.0后台则返回2.0.0的补丁包。字段后台返回一个补丁包的链接就可以了,每次更新补丁包后台都要换不同的链接(下面前端设计有讲到)。没有则返回空。

前端设计与问题

问题: 前端下载APK的时机和逻辑
方案: 放在启动页-SplashActivity请求比较好(越早请求越好),每次都去请求,把请求回来的链接保存在本地,进行对比,链接不一样则下载补丁包并加载。链接一样则不用重复下载。

问题: 前端下载的时候需不需要提示用户?
方案: 这个看产品经理的需求,一般可以不提示,我修复bug告诉你干嘛...

问题: 如果1.0.0版本上线后,过了很久才发现有bug, 我的trunk主线代码已经改了很多了。这个时候打补丁包那不是把其他代码也认为是差异的代码,然后直接加载补丁包到1.0.0的apk上?这样不合理吧?
方案:
发布1.0.0版本后, 新建一个1.0.0的分支, 然后在1.0.0分支上修改bug,打出补丁包发给后台,最后把1.0.0的代码merge到trunk主线即可。

问题: 要给同一个版本多次打补丁包,又怎样弄呢?
直接在每次发布版本新建的分支上修复bug,然后每次打不同的补丁包,就需要叫后台返回不通的连接(为了区分该补丁包是否已加载过,上面后台接口的设计有讲到)。即都要以发布时的版本作为基础包进行bug修改。

问题:加载补丁包后,怎样才能让修改的bug生效呢?
解决:因为Tinker不是即时生效的。所以我们这里不用处理,加载完补丁包,用户退出下次进来就自然生效。或者在后台直接重启就好了

八、Demo地址

集成TinkerDemo地址

发布了89 篇原创文章 · 获赞 33 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/chenli_001/article/details/102630047