Android tinker熱修復——實戰接入專案

鋸齒流沙發表於2018-01-06

《Android tinker熱修復——從執行demo開始》該篇文章已經成功的將tinker的demo執行起來了,相信大家也知道了tinker的神奇之處,如果線上版本一旦出現bug,可以通過tinker打patch包,能夠及時修復bug,從而提高使用者體驗。

如果你的專案是使用外掛化技術,需要更新宿主程式,那麼tinker或許不適用了,這時候需要下載整個專案的apk,然後安裝。也可以通過增量更新,下載差分包,合併,然後安裝。關於增量更新可以參考我的這篇文章《NDK增量更新》

好了,言歸正傳。我們看看如何在自己的專案接入tinker熱修復,先看看我專案結構

tinker

上圖就是我的專案結構,我將tinker做成了一個lib,在宿主app中直接add進來即可。

tinker

在專案的build.gradle定義ext,主要是方便管理各個外掛的build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1')
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

ext {
    verName = "1.0"//版本名稱
    fixDir = "TinkerFix"//專案名稱
    proj = [
            minSDK        : 15,//最低相容版本
            targetSDK     : 22,//目標版本
            compileSdk    : 26,//編譯版本
            buildTool     : "26.0.2",
            versionName   : "$verName",
            versionCode   : 1,//版本號
            tinkerEnabled : true,
            oldVersionName: "app-debug-1128-16-32-49",//老版本字首(用於tinker打patch包)
            tinkerId      : "${getTinkerId()}",
            patchVersion  : "1"//tinker版本號
    ]

    supportLibraryVersion = "25.0.0"
    sup = [
            SupportV7            : "com.android.support:appcompat-v7:$supportLibraryVersion",
            SupportV4            : "com.android.support:support-v4:$supportLibraryVersion",
            SupportRecyclerviewV7: "com.android.support:recyclerview-v7:$supportLibraryVersion"
    ]
}

def getTinkerId() {
    fixDir + "_" + verName
}
複製程式碼

將各個外掛的build.gradle的配置,使用專案build.gradle在ext中定義的變數

tinker

專案new一個Module,選擇Library

tinker

配置tinkerlib的build.gradle,同時引入tinker的新增gradle依賴

apply plugin: 'com.android.library'

android {
    compileSdkVersion proj.compileSdk
    buildToolsVersion proj.buildTool

    defaultConfig {
        minSdkVersion proj.minSDK
        targetSdkVersion proj.targetSDK
        multiDexEnabled true
        versionCode proj.versionCode
        versionName proj.versionName
        /**
         * client version would update with patch
         * so we can get the newly git version easily!
         */
        buildConfigField "String", "TINKER_ID", "\"${proj.tinkerId}\""
        buildConfigField "String", "PATCH_DIRECTORY", "\"${fixDir}\""
        buildConfigField "String", "PLATFORM", "\"all\""
        buildConfigField "Integer", "PATCH_VERSION", "${proj.patchVersion}"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:multidex:1.0.1'
    //可選,用於生成application類
    provided('com.tencent.tinker:tinker-android-anno:1.9.1')
    //tinker的核心庫
    compile('com.tencent.tinker:tinker-android-lib:1.9.1')

}
複製程式碼

該build.gradle使用到的變數都是在專案build.gradle中定義的,如proj.tinkerId.

使用tinker必須使用multidex,所以要新增multidex依賴,並且在defaultConfig中的multiDexEnabled為true,在application的onBaseContextAttached方法中需要呼叫MultiDex.install(base);

tinker

tinkerlib的目錄結構和檔案

tinker

相信執行過tinker的demo的讀者對這些目錄和檔案一定很熟悉吧,沒錯,這個就是我從demo中拿過來的檔案,直接拿過來使用即可,最後別忘了,註冊Service。

tinker

這裡需要注意的唯一需要處理的地方就是tinkerlib的MyTestApplicationLike不需要SuppressWarnings和DefaultLifeCycle註解。

public class MyTestApplicationLike extends DefaultApplicationLike {
    private static final String TAG = "MyTestApplicationLike";

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


    /**
     * install multiDex before install tinker
     * so we don't need to put the tinker lib classes in the main dex
     *
     * @param base
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        //you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        SampleApplicationContext.application = getApplication();
        SampleApplicationContext.context = getApplication();
        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 tinker = Tinker.with(getApplication());
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) {
        getApplication().registerActivityLifecycleCallbacks(callback);
    }
}
複製程式碼

不需要註解,是因為在我們的宿主程式app中的Application直接繼承TinkerApplication即可。而且在tinkerlib的AndroidManifest.xml不需要指定MyTestApplicationLike。

宿主(app)程式的MyApplication繼承TinkerApplication

public class MyApplication extends TinkerApplication {

    public MyApplication() {
        super(
                //tinkerFlags, tinker支援的型別,dex,library,還是全部都支援!
                ShareConstants.TINKER_ENABLE_ALL,
                //ApplicationLike的實現類,只能傳遞字串
                "com.main.mytinker.app.MyTestApplicationLike",
                //Tinker的載入器,一般來說用預設的即可
                "com.tencent.tinker.loader.TinkerLoader",
                //tinkerLoadVerifyFlag, 執行載入時是否校驗dex與,ib與res的Md5
                false);
    }
}
複製程式碼

注意:這裡的構造方法訪問修飾符必須為public,否則出錯,程式閃退。

在AndroidManifest.xml新增MyApplication ,並新增需要的許可權。

tinker.png

在MyApplication中不需要呼叫MultiDex.install()和TinkerManager.installTinker(),因為在tinkerlib的application中已經呼叫了。同時在宿主的build.gradle也不需要新增tinker和multidex的依賴,這些工作在tinkerlib中已經做好了。

接下來只需要在app的build.gradle中新增tinker打包的配置即可

apply plugin: 'com.android.application'

android {

    signingConfigs {
        mySigned {
            keyAlias 'Tinkerdemo'
            keyPassword '123456'
            storeFile file('Tinkerdemo.jks')
            storePassword '123456'
        }
    }

    compileSdkVersion proj.compileSdk
    buildToolsVersion proj.buildTool
    defaultConfig {
        applicationId "com.main.mytinker"
        minSdkVersion proj.minSDK
        targetSdkVersion proj.targetSDK
        versionCode proj.versionCode
        versionName proj.versionName
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.mySigned
        }
        debug{
            signingConfig signingConfigs.mySigned
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile project(':tinkerlib')
}


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 {
    //for some reason, you may want to ignore tinkerBuild, such as instant run debug build?
    tinkerEnabled = proj.tinkerEnabled

    //for normal build
    //old apk file to build patch apk
    tinkerOldApkPath = "${bakPath}/${proj.oldVersionName}.apk"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/${proj.oldVersionName}-mapping.txt"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/${proj.oldVersionName}-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 : proj.tinkerId
}

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

def getTinkerBuildFlavorDirectory() {
    return ext.tinkerBuildFlavorDirectory
}

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

    tinkerPatch {
        /**
         * necessary錛宒efault 'null'
         * the old apk path, use to diff with the new apk to build
         * add apk from the build/bakApk
         */
        oldApk = getOldApkPath()
        /**
         * optional錛宒efault '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錛宒efault '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錛宒efault 'true'
         * whether use tinker to build
         */
        tinkerEnable = buildWithTinker()

        /**
         * Warning, applyMapping will affect the normal android build!
         */
        buildConfig {
            /**
             * optional錛宒efault '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錛宒efault 'null'
             * It is nice to keep the resource id from R.txt file to reduce java changes
             */
            applyResourceMapping = getApplyResourceMappingPath()

            /**
             * necessary錛宒efault '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
        }

        dex {
            /**
             * optional錛宒efault '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錛宒efault '[]'
             * what dexes in apk are expected to deal with tinkerPatch
             * it support * or ? pattern.
             */
            pattern = ["classes*.dex",
                       "assets/secondary-dex-?.jar"]
            /**
             * necessary錛宒efault '[]'
             * 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錛宒efault '[]'
             * 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錛宒efault '[]'
             * 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錛宒efault '[]'
             * 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錛宒efault '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", proj.patchVersion)
        }
        //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錛宒efault '7za'
             * the 7zip artifact path, it will use the right 7za with your platform
             */
            zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
            /**
             * optional錛宒efault '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.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"
                    }

                }
            }
        }
    }
}

複製程式碼

同樣的,以上的build.gradle中的一些配置使用到專案的build.gradle中定義的變數。關於tinker的gradle引數,可以參考GitHub中的tinkergradle引數詳解

一切準備就緒後,別忘記了在app中新增tinkerlib依賴。

測試

MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.findViewById(R.id.test_fix).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), 
                        Environment.getExternalStorageDirectory().
                                getAbsolutePath() + "/patch_signed_7zip.apk");
            }
        });
        this.findViewById(R.id.test_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"你好",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

複製程式碼

佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="com.main.mytinker.MainActivity">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <Button
                android:id="@+id/test_fix"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="fix"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="50dp"
                android:text="版本2.0"/>

            <Button
                android:id="@+id/test_btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="你好"/>
        </LinearLayout>
    </ScrollView>


</LinearLayout>

複製程式碼

tinker

新增兩張圖片

<ImageView
                android:layout_width="400dp"
                android:layout_height="400dp"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/timg"/>

<ImageView
                android:id="@+id/img"
                android:layout_width="400dp"
                android:layout_height="400dp"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/aa"/>
複製程式碼

更改專案build.gradle中ext定義的oldVersionName變數的值

tinker

tinkerPatchDebug

tinker

拿到patch_signed_7zip.apk,複製到目錄指定的安裝資料夾下,然後熱更新

tinker

熱更新後的效果圖:

tinker

以上,已經完成了tinker接入專案中了,讀者可以根據本文可以自己實戰一下。

相關文章