天天看點

Android 熱更新 微信的tinker方案 騰訊的bugly內建

以前看到遊戲的更新不需要直覺看到下載下傳安裝就已經更新好了,覺得這個更新方案很NB,然後知道了熱更新,但是也沒有深究

最近公司突然說需要熱更新,不要安裝也可以解決一些小bug。

一、為什麼需要熱更新

正常的流程是:

新版本上線,發現問題或使用者回報bug,緊急修複,上線版本,使用者重新安裝。

每次出現bug都要重新安裝,這個會讓客戶奔潰,然後解除安裝的

熱修複流程:

新版本上線,發現問題或使用者回報,緊急修複,上線更新檔,自動修複

直接在使用者沒什麼感覺的時候就修複了 -- 完美

2.熱更新技術選擇

目前熱更新的技術主流的有微信的tinker,qq更新檔,阿裡Andfix,餓了麼得amigo,美團的robust 

附帶一張他們對比圖

Android 熱更新 微信的tinker方案 騰訊的bugly內建

由于我選擇的是Tinker 而且用了Bugly統計異常的更新,下面就說說bugly和bugly的熱更新(其實用了Tinker)

二.內建SDK

Bugly 文檔位址  

1.首先工程根目錄下“build.gradle”檔案中添加:

buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        // tinkersupport插件, 其中lastest.release指拉取最新版本,也可以指定明确版本号,例如1.1.2
        //注意:自tinkersupport 1.0.3版本起無需再配tinker插件的classpath。 要是嫌麻煩 直接用我這個版本号
        classpath "com.tencent.bugly:tinker-support:1.1.2" //主要這行
    }
}
           

2.在app module的“build.gradle”檔案中添加(示例配置):

apply plugin: 'com.android.application'
// 依賴插件腳本 這個等下我們會建立一個配置檔案
apply from: 'tinker-support.gradle'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.qdama.updatet"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 2
        versionName "1.0.1"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"


        ndk {
            //設定支援的SO庫架構
            abiFilters 'armeabi', 'armeabi-v7a'//, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
        }
    }

//    // 簽名配置  這裡自己改一下配置
    signingConfigs {
        release {
            try {
                storeFile file("******")
                storePassword "******"
                keyAlias "******"
                keyPassword "******"
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }

        debug {
            try {
                 storeFile file("******") 
                 storePassword "******" 
                 keyAlias "******" 
                 keyPassword "******"
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }
    }

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

//    compile 'com.tencent.bugly:crashreport_upgrade:latest.release'//其中latest.release指代最新版本号,也可以指定明确的版本号,例如1.2.0
//    compile 'com.tencent.bugly:nativecrashreport:latest.release' //其中latest.release指代最新版本号,也可以指定明确的版本号,例如2.2.0

    implementation "com.android.support:multidex:1.0.1" // 多dex配置
    //注釋掉原有bugly的倉庫
    //compile 'com.tencent.bugly:crashreport:latest.release'//其中latest.release指代最新版本号,也可以指定明确的版本号,例如1.3.4
    implementation 'com.tencent.bugly:crashreport_upgrade:1.3.5'
    // 指定tinker依賴版本(注:應用更新1.3.5版本起,不再内置tinker)
    implementation 'com.tencent.tinker:tinker-android-lib:1.9.6'
    implementation 'com.tencent.bugly:nativecrashreport:latest.release'
    //其中latest.release指代最新版本号,也可以指定明确的版本号,例如2.2.0
}
           

3 在同級目錄下建立tinker-support.gradle

Android 熱更新 微信的tinker方案 騰訊的bugly內建
apply plugin: 'com.tencent.bugly.tinker-support'

def bakPath = file("${buildDir}/bakApk/")

/**
 * 此處填寫每次建構生成的基準包目錄
 */
def baseApkDir = "app-1217-15-33-54"

/**
 * 對于插件各參數的詳細解析請參考
 */
tinkerSupport {

    // 開啟tinker-support插件,預設值true
    enable = true

    // 指定歸檔目錄,預設值目前module的子目錄tinker
    autoBackupApkDir = "${bakPath}"

    // 是否啟用覆寫tinkerPatch配置功能,預設值false
    // 開啟後tinkerPatch配置不生效,即無需添加tinkerPatch
    overrideTinkerPatchConfiguration = true

    // 編譯更新檔包時,必需指定基線版本的apk,預設值為空
    // 如果為空,則表示不是進行更新檔包的編譯
    // @{link tinkerPatch.oldApk }
    baseApk = "${bakPath}/${baseApkDir}/app-release.apk"

    // 對應tinker插件applyMapping
    baseApkProguardMapping = "${bakPath}/${baseApkDir}/app-release-mapping.txt"

    // 對應tinker插件applyResourceMapping
    baseApkResourceMapping = "${bakPath}/${baseApkDir}/app-release-R.txt"

    // 建構基準包和更新檔包都要指定不同的tinkerId,并且必須保證唯一性  base-1.0.1   patch
    tinkerId = "patch-1.0.1"

    // 建構多管道更新檔時使用
    // buildAllFlavorsDir = "${bakPath}/${baseApkDir}"

    // 是否啟用加強模式,預設為false.(tinker-spport 1.0.7起支援)
    // isProtectedApp = true

    // 是否開啟反射Application模式
    enableProxyApplication = false

    // 是否支援新增非export的Activity(注意:設定為true才能修改AndroidManifest檔案)
    supportHotplugComponent = true

}

/**
 * 一般來說,我們無需對下面的參數做任何的修改
 * 對于各參數的詳細介紹請參考:
 * https://github.com/Tencent/tinker/wiki/Tinker-%E6%8E%A5%E5%85%A5%E6%8C%87%E5%8D%97
 */
tinkerPatch {
    //oldApk ="${bakPath}/${appName}/app-release.apk"
    ignoreWarning = false
    useSign = true
    dex {
        dexMode = "jar"
        pattern = ["classes*.dex"]
        loader = []
    }
    lib {
        pattern = ["lib/*/*.so"]
    }

    res {
        pattern = ["res/*", "r/*", "assets/*", "resources.arsc", "AndroidManifest.xml"]
        ignoreChange = []
        largeModSize = 100
    }

    packageConfig {
    }
    sevenZip {
        zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
//        path = "/usr/local/bin/7za"
    }
    buildConfig {
        keepDexApply = false
        //tinkerId = "1.0.1-base"
        //applyMapping = "${bakPath}/${appName}/app-release-mapping.txt" //  可選,設定mapping檔案,建議保持舊apk的proguard混淆方式
        //applyResourceMapping = "${bakPath}/${appName}/app-release-R.txt" // 可選,設定R.txt檔案,通過舊apk檔案保持ResId的配置設定
    }
}

主要是紅色的2個設定 其他的都可以不用理
           

4 初始化SDK

為了相容性更好 建議enableProxyApplication = false 

① 建立一個MyApplication (名字請随意) 這個類不做任何操作,所有application代碼都會放在SampleApplicationLike裡面

public class MyApplication extends TinkerApplication {

    public MyApplication() {
        super(ShareConstants.TINKER_ENABLE_ALL, "com.qdama.updatet.SampleApplicationLike",
                "com.tencent.tinker.loader.TinkerLoader", false);
    }
}
           

②建立 SampleApplicationLike 

public class SampleApplicationLike extends DefaultApplicationLike {

    public static final String TAG = "Tinker.SampleApplicationLike";

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


    @Override
    public void onCreate() {
        super.onCreate();
        // 這裡實作SDK初始化,appId替換成你的在Bugly平台申請的appId
        // 調試時,将第三個參數改為true
        Bugly.init(getApplication(), "48dd221d31", true);
    }


    @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);

        // 安裝tinker
        // TinkerManager.installTinker(this); 替換成下面Bugly提供的方法
        Beta.installTinker(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }
}
           

5 AndroidManifest.xml配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qdama.updatet">
    <!-- 注意改一下name -->
    <application
        android:name=".MyApplication"
        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=".LoginActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- ② -->
        <activity
            android:name="com.tencent.bugly.beta.ui.BetaActivity"
            android:configChanges="keyboardHidden|orientation|screenSize|locale"
            android:theme="@android:style/Theme.Translucent" />
        <!-- ③ -->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </application>
    <!-- ① -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

</manifest>
           

① 權限配置

② Activity配置

③ FileProvider配置

Android 熱更新 微信的tinker方案 騰訊的bugly內建

在src目錄建立xml檔案,建立provider_paths檔案

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- /storage/emulated/0/Download/${applicationId}/.beta/apk-->
    <external-path name="beta_external_path" path="Download/"/>
    <!--/storage/emulated/0/Android/data/${applicationId}/files/apk/-->
    <external-path name="beta_external_files_path" path="Android/data/"/>
</paths>
           

如果你使用的第三方庫也配置了同樣的FileProvider, 可以通過繼承FileProvider類來解決合并沖突的問題,示例如下:

<provider
    android:name=".utils.BuglyFileProvider"
    android:authorities="${applicationId}.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true"
    tools:replace="name,authorities,exported,grantUriPermissions">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"
        tools:replace="name,resource"/>
</provider>
           

注意 FileProvider類是在support-v4包中的,檢查你的工程是否引入該類庫

還有一個是provider的name 沒有使用Androidx的用 android.support.v4.content.FileProvider

使用了Androidx的用 androidx.core.content.FileProvider 不然報錯(親測)

5 混淆

-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
-keep class android.support.**{*;}

# tinker混淆規則
-dontwarn com.tencent.tinker.**
-keep class com.tencent.tinker.** { *; }


-keep class android.support.**{*;}
           

內建道這裡就好了 

三 使用

使用就2個很重要的參數 tinkerId  baseApkDir

tinkerId  基線版本配置一個唯一的tinkerId,而這個基線版本能夠應用更新檔的前提是內建過熱更新SDK,并啟動上報過聯網,這樣我們背景會将這個tinkerId對應到一個目标版本,例如tinkerId = "patch_1.0.0" 對應了一個目标版本是1.0.0,基于這個版本打的更新檔包就能比對到目标版本

baseApkDir 基線版本的打包目錄 打包後的apk包之類的,更新檔就是基于這個目錄下面的apk包操作的,是以這個目錄要記得儲存

配置好那我們開始

1.

Android 熱更新 微信的tinker方案 騰訊的bugly內建

assembleReleasse 打一下包 這個目錄就有這個打好的包 儲存好這個目錄

Android 熱更新 微信的tinker方案 騰訊的bugly內建

然後在bugly上面上傳一個版本

Android 熱更新 微信的tinker方案 騰訊的bugly內建

然後我們改一下代碼(模拟改了bug)

然後确認一下baseApkDir是不是填寫的線上版本的目錄 然後把tinkerId改為patch_1.0.0

Android 熱更新 微信的tinker方案 騰訊的bugly內建

然後點選這個編譯會生成

Android 熱更新 微信的tinker方案 騰訊的bugly內建

把這個檔案上傳到bugly 然後下發

Android 熱更新 微信的tinker方案 騰訊的bugly內建

因為tinker不是即時生效的。是以要過一會 重新打開app檢視

Android 熱更新 微信的tinker方案 騰訊的bugly內建

熱更新的基本操作就這些了。