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嗽上,實踐中發(fā)現(xiàn)生成不了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 {
//設(shè)置支持的SO庫架構(gòu)
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
// 下面的字段是在每次打完基線版本的包后兽愤,找到對應(yīng)的文件位置彼念,修改路勁,然后再打補丁包
//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",// 這個填寫的我們自己實現(xiàn)的
// Application類也就是繼承TinkerApplication的類(項目中我們還需要實現(xiàn)
// 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()
// 對應(yīng)tinker插件applyMapping
baseApkProguardMapping = getApplyMappingPath()
// 對應(yīng)tinker插件applyResourceMapping
baseApkResourceMapping = getApplyResourceMappingPath()
tinkerId = getTinkerIdValue()
}*/
}
// 下面的代碼是對打基準版本的包存放位置的管理何暇,包括多渠道陶夜,不需要改動
List<String> 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類条辟,發(fā)現(xiàn)里面其實是調(diào)用代理類的方法。
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);
// 設(shè)置版本號(可以不是appversion)
strategy.setAppVersion(BuildConfig.VERSION_NAME);
// 設(shè)置渠道
// strategy.setAppChannel(CommonUtils.getUmengChannelValue(context));
strategy.setAppChannel("develop");
// 設(shè)置是否為上報進程
strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
// 如果您之前使用過Bugly SDK,請將以下這句注釋掉
// CrashReport.initCrashReport(context, "6ad653a1be", false, strategy);
// 統(tǒng)一初始化方法:
Bugly.setIsDevelopmentDevice(getApplication(), true);
Bugly.init(getApplication(), "6ad653a1be", false);
}
/**
* 獲取進程號對應(yīng)的進程名
*
* @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 (真正的實現(xiàn)還是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", // 上面實現(xiàn)的類
"com.tencent.tinker.loader.TinkerLoader", // 默認即可
false);
}
}
MyApplication類肩袍,參數(shù)解析
參數(shù)1:tinkerFlags 表示Tinker支持的類型 dex only杭棵、library only or all suuport,默認: TINKER_ENABLE_ALL
參數(shù)2:delegateClassName Application代理類,這里填寫你自定義的MyApplicationDelegate
參數(shù)3:loaderClassName Tinker的加載器魂爪,使用默認即可
參數(shù)4:tinkerLoadVerifyFlag 加載dex或者lib是否驗證md5先舷,默認為false
發(fā)布補丁到bugly后臺流程
- 打好基準包(每次發(fā)布版本),備份bakApk目錄及文件
- 修改基準包路徑滓侍,build.gradle中的幾個字段蒋川,多渠道包,只需給定一個根目錄就行
- gradle 執(zhí)行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對應(yīng)到一個目標版本
- 發(fā)布補丁包到后臺時秩霍,有開發(fā)設(shè)備和全量設(shè)備,可以Bugly.setIsDevelopmentDevice(getApplication(), true);設(shè)置蚁阳。
bugly熱更新還提供了自定義擴展Tinker接口铃绒,更多功能請參考bugly官方文檔
最后附上截圖;-)
多渠道基準包和補丁包
bugly后臺發(fā)布補丁包