Bugly热更新实践

bugly热更新采用的是微信Tinker开源方案(Tinker接入指南)


集成热更新
  • 工程根目录build.gradle文件中添加
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        
        // 下面是需要添加的
        // 当前tinker最新版本为1.7.6,我们需要使用1.7.5,实践中发现生成不了patch目录
        // 询问了官方客服,他们正在适配1.7.6
        classpath ('com.tencent.tinker:tinker-patch-gradle-plugin:1.7.5')
        // tinkersupport插件
        classpath "com.tencent.bugly:tinker-support:latest.release"
    }
}
  • app的build.gradle文件中添加(参考BuglyHotfixDemo中的gradle配置)
apply plugin: 'com.android.application'

android {
    compileSdkVersion = 23
    buildToolsVersion = '23.0.1'
    defaultConfig {
        applicationId "com.bric.testtinker2"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode APP_VERSION_CODE as int
        versionName APP_VERSION_NAME
        
        multiDexEnabled true
        // 以Proguard的方式手动加入要放到Main.dex中的类
        multiDexKeepProguard file("keep_in_main_dex.txt")
        ndk {
            //设置支持的SO库架构
            abiFilters 'armeabi', 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
        }
    }

    //recommend
    dexOptions {
        jumboMode = true
    }

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

        debug {
            storeFile file("./keystore/debug.keystore")
        }
    }

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

    productFlavors {
        baidu {} //
        qq {} // QQ
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile "com.android.support:multidex:1.0.1"
//    Bugly
//    compile 'com.tencent.bugly:crashreport:latest.release'
//    compile 'com.tencent.bugly:nativecrashreport:latest.release'
// 原先集成了bugly sdk的依然可以使用之前的功能不影响,只需换成下面这一句就可以
    compile 'com.tencent.bugly:crashreport_upgrade:latest.release'
}


def gitSha() {
    try {
        String gitRev = 'git rev-parse --short HEAD'.execute(null, project.rootDir).text.trim()
        if (gitRev == null) {
            throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
        }
        return gitRev
    } catch (Exception e) {
        throw new GradleException("can't get git rev, you should add git to system path or just input test value, such as 'testTinkerId'")
    }
}

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 = true

    // 下面的字段是在每次打完基线版本的包后,找到对应的文件位置,修改路劲,然后再打补丁包
    //for normal build
    //old apk file to build patch apk
    tinkerOldApkPath = "${bakPath}/app-release-0113-09-43-56.apk"
    //proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/app-release-0113-09-43-56-mapping.txt"
    //resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-release-0113-09-43-56-R.txt"

    //only use for build all flavor, if not, just ignore this field
    // 这个字段是多渠道包的目录,如果使用了多渠道打包,上面的几个字段就可以忽略,只需填写多渠道
    // 包的路劲,如果不使用多渠道打包,则忽略此字段,上面的三个字段路劲需要填写的(分别是:app路
    // 劲,混淆的mapping路劲,资源R文件的路劲)
    tinkerBuildFlavorDirectory = "${bakPath}/app-0113-10-02-14"
}

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

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

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

def getTinkerIdValue() {
    return hasProperty("TINKER_ID") ? TINKER_ID : gitSha()
}

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

def getTinkerBuildFlavorDirectory() {
    return ext.tinkerBuildFlavorDirectory
}

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

    // 注意:必须要配置tinker-support
    tinkerSupport {
    }

    tinkerPatch {
        oldApk = getOldApkPath()
        ignoreWarning = false
        useSign = true

        /**
         * Warning, applyMapping will affect the normal android build!
         */
        buildConfig {
            applyMapping = getApplyMappingPath()
            applyResourceMapping = getApplyResourceMappingPath()
            tinkerId = project.APP_VERSION_NAME
        }

        dex {
            dexMode = "jar"
            usePreGeneratedPatchDex = true // 可选,默认为false
            pattern = ["classes*.dex",
                       "assets/secondary-dex-?.jar"]
            // 必选
            loader = ["com.tencent.tinker.loader.*",
                      "com.bric.testtinker2.app.MyApplication",// 这个填写的我们自己实现的
                      // Application类也就是继承TinkerApplication的类(项目中我们还需要实现
                      // DefaultApplicationLike)
            ]
        }

        lib {
            pattern = ["lib/armeabi/*.so"]
        }

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

        packageConfig {
            configField("patchMessage", "tinker is sample to use")
            configField("platform", "all")
            configField("patchVersion", "1.0")
        }

        sevenZip {
            zipArtifact = "com.tencent.mm:SevenZip:1.1.10"
        }

        /*// 如果只用Bugly提供的插件,可以进行以下配置
        tinkerSupport {
            // 开启tinker-support插件,默认值true
            enable = true
            // 是否编译完成后,归档apk到指定目录,默认值false
            autoBackupApk = false
            // 指定归档目录,默认值当前module的子目录tinker
            // backupApkDir = 'tinker'
            // 是否启用覆盖tinkerPatch配置功能,默认值false
            // 开启后tinkerPatch配置不生效,即无需添加tinkerPatch
            overrideTinkerPatchConfiguration = true
            // 编译补丁包时,必需指定基线版本的apk,默认值为空
            // 如果为空,则表示不是进行补丁包的编译
            // @{link tinkerPatch.oldApk }
            baseApk = getOldApkPath()
            // 对应tinker插件applyMapping
            baseApkProguardMapping = getApplyMappingPath()
            // 对应tinker插件applyResourceMapping
            baseApkResourceMapping = getApplyResourceMappingPath()
            tinkerId = getTinkerIdValue()
        }*/

    }

    // 下面的代码是对打基准版本的包存放位置的管理,包括多渠道,不需要改动
    
    List flavors = new ArrayList<>();
    project.android.productFlavors.each {flavor ->
        flavors.add(flavor.name)
    }
    boolean hasFlavors = flavors.size() > 0
    /**
     * bak apk and mapping
     */
    android.applicationVariants.all { variant ->
        /**
         * task type, you want to bak
         */
        def taskName = variant.name
        def date = new Date().format("MMdd-HH-mm-ss")

        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"
                    }

                }
            }
        }
    }
}
  • 自定义Application(两个Application),完成后在AndroidManifest.xml中注册Application(继承TinkerApplication的,源码中可以看出TinkerApplication是继承Application),

    查看TinkerApplication类,发现里面其实是调用代理类的方法。

package com.bric.testtinker2.app;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.bric.testtinker2.BuildConfig;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.tinker.loader.app.DefaultApplicationLike;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Application 代理类
 *
 * Created on 2017/1/12.
 *
 * @author Administrator
 * @version 1.0.0
 */
// Tinker提供的注解方式可以生成MyApplicationDelegate类,这里我们不使用注解方式也可以,手动继承
// TinkerApplication
//@DefaultLifeCycle(application = "com.bric.testtinker2.app.MyApplication",
//flags = ShareConstants.TINKER_ENABLE_ALL,
//loadVerifyFlag = false)
public class MyApplicationDelegate extends DefaultApplicationLike {

    public MyApplicationDelegate(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent, Resources[] resources, ClassLoader[] classLoader, AssetManager[] assetManager) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent, resources, classLoader, assetManager);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initBugly();
    }

    /**
     * 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);
        // 安装tinker
        Beta.installTinker(this);
    }

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

    private void initBugly() {
        Context context = getApplication();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        //
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        // 设置版本号(可以不是appversion)
        strategy.setAppVersion(BuildConfig.VERSION_NAME);
        // 设置渠道
//        strategy.setAppChannel(CommonUtils.getUmengChannelValue(context));
        strategy.setAppChannel("develop");
        // 设置是否为上报进程
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
//         初始化Bugly
//        如果您之前使用过Bugly SDK,请将以下这句注释掉
//        CrashReport.initCrashReport(context, "6ad653a1be", false, strategy);
//        统一初始化方法:
        Bugly.setIsDevelopmentDevice(getApplication(), true);
        Bugly.init(getApplication(), "6ad653a1be", false);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}

package com.bric.testtinker2.app;

import com.tencent.tinker.loader.app.TinkerApplication;
import com.tencent.tinker.loader.shareutil.ShareConstants;

/**
 *
 * Application (真正的实现还是com.bric.testtinker2.app.MyApplicationDelegate)
 *
 * Created on 2017/1/12.
 *
 * @author Administrator
 * @version 1.0.0
 */

public class MyApplication extends TinkerApplication {

    public MyApplication() {
        super(ShareConstants.TINKER_ENABLE_ALL, //
                "com.bric.testtinker2.app.MyApplicationDelegate", // 上面实现的类
                "com.tencent.tinker.loader.TinkerLoader", // 默认即可
                false);
    }
}

MyApplication类,参数解析

参数1:tinkerFlags 表示Tinker支持的类型 dex only、library only or all suuport,默认: TINKER_ENABLE_ALL

参数2:delegateClassName Application代理类,这里填写你自定义的MyApplicationDelegate

参数3:loaderClassName Tinker的加载器,使用默认即可

参数4:tinkerLoadVerifyFlag 加载dex或者lib是否验证md5,默认为false

发布补丁到bugly后台流程

  • 打好基准包(每次发布版本),备份bakApk目录及文件
  • 修改基准包路径,build.gradle中的几个字段,多渠道包,只需给定一个根目录就行
  • gradle 执行tinkerPatchRelease命令,开始打补丁包
  • 最后在app/build/outputs/patch/目录中生成了patch_signed_7zip.apk,将后缀改成zip,上传到bugly后台

分割线


还有
  • 选择app/build/outputs/patch目录下的补丁包并上传(注:不要选择tinkerPatch目录下的补丁包,不然上传会有问题),目前需使用1.7.5版本
  • 打包补丁前,填写补丁包路劲、mapping文件路径、resId文件路径
  • tinkerId是一个唯一标识,例如git版本号、versionName等等,后台会将这个tinkerId对应到一个目标版本
  • 发布补丁包到后台时,有开发设备和全量设备,可以Bugly.setIsDevelopmentDevice(getApplication(), true);设置。
bugly热更新还提供了自定义扩展Tinker接口,更多功能请参考bugly官方文档
最后附上截图;-)
Bugly热更新实践_第1张图片
多渠道基准包和补丁包
Bugly热更新实践_第2张图片
bugly后台发布补丁包
参考文章

Tinker接入指南

Bugly Android热更新使用指南

Android热补丁Tinker原理解析

使用Bugly快速接入Tinker热更新功能

你可能感兴趣的:(Bugly热更新实践)