0
点赞
收藏
分享

微信扫一扫

如何接入腾讯Tinker热更新,并使用Bugly进行托管

如何接入腾讯Tinker热更新,并使用Bugly进行托管

【Tinker Github地址】: GitHub - Tencent/tinker: Tinker is a hot-fix solution library for Android, it supports dex, library and resources update without reinstall apk.

【Bugly 地址】: 腾讯Bugly - 一种愉悦的开发方式 _android anr_android anr分析_iOS崩溃日志分析平台

【如何接入】

1.进入Bugly网站,登陆后新建产品

[图片上传失败...(image-176945-1547370765018)]

2.新建后便会得到AppID,该id需要在后面初始化时候用到

[图片上传失败...(image-7379f6-1547370765018)]

至次,申请工作已经完成,Bugly主要用来在后面上传Patch补丁包以及监控异常等作用,接下来就需要在代码中进行配置热更新,我们通过在gradle中集成方式进行配置

【引入依赖】

1.在工程跟目录的build.gradle中添加如下依赖

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

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

       // tinkersupport插件, 其中lastest.release指拉取最新版本,也可以指定明确版本号,例如1.0.4
       classpath('com.tencent.tinker:tinker-patch-gradle-plugin:1.9.1')
       // tinkersupport插件(1.0.3以上无须再配置tinker插件)
       classpath "com.tencent.bugly:tinker-support:1.1.1"
   }
}

这里要注意,tinker版本和tinkersupport版本号是对应的,如1.9.1对应1.1.1,不可写错


其中,版本对应关系为:


2.在app下面的build.gradle中添加如下依赖:

// 依赖插件脚本
apply from: 'tinker-support.gradle'

defaultConfig {
       applicationId "com.thekey.buglyhotfix"
       minSdkVersion 15
       targetSdkVersion 26
       versionCode 2
       versionName "v2.0"
       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
       // 开启multidex
       multiDexEnabled true
   }
   
   // recommend
   dexOptions {
       jumboMode = true
   }
   
   // 构建类型
   buildTypes {
       release {
           minifyEnabled true
           signingConfig signingConfigs.release
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
       debug {
           debuggable true
           minifyEnabled false
           signingConfig signingConfigs.debug
       }
   }
   
   // 签名配置
   signingConfigs {
       release {
           try {
               storeFile file("./keystore/release.keystore")
               storePassword "android"
               keyAlias "android"
               keyPassword "android"
           } catch (ex) {
               throw new InvalidUserDataException(ex.toString())
           }
       }

       debug {
           storeFile file("./keystore/debug.keystore")
       }
   }
   
   dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:26.1.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

   implementation "com.android.support:multidex:1.0.1" // 多dex配置
   implementation 'com.tencent.bugly:crashreport_upgrade:1.3.4'// 远程仓库集成方式(推荐)
}

3.配置依赖插件版本tinker-support.gradle

apply plugin: 'com.tencent.bugly.tinker-support'

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

/**
* 此处填写每次构建生成的基准包目录
*/
def baseApkDir = "app-0111-14-10-58"
//def myTinkerId = "base-" + rootProject.ext.android.versionName // 用于生成基准包(不用修改)
def myTinkerId = "patch-" + "v2.0" + ".2.1" // 用于生成补丁包(每次生成补丁包都要修改一次,最好是 patch-${versionName}.x.x)
//这里配置是debug还是release
def variantName = "release"

/**
* 对于插件各参数的详细解析请参考
*/
tinkerSupport {

   // 开启tinker-support插件,默认值true
   enable = true

   // 是否启用加固模式,默认为false.(tinker-spport 1.0.7起支持)
   isProtectedApp = false

   // 是否开启反射Application模式
   enableProxyApplication = true

   // 是否支持新增非export的Activity(注意:设置为true才能修改AndroidManifest文件)
   supportHotplugComponent = true

   // 指定归档目录,默认值当前module的子目录tinker
   autoBackupApkDir = "${bakPath}"

   // 是否启用覆盖tinkerPatch配置功能,默认值false
   // 开启后tinkerPatch配置不生效,即无需添加tinkerPatch
   overrideTinkerPatchConfiguration = true

   // 编译补丁包时,必需指定基线版本的apk,默认值为空
   // 如果为空,则表示不是进行补丁包的编译
   // @{link tinkerPatch.oldApk }

   //简化配置
   def name = "${project.name}-${variantName}"

   baseApk = "${bakPath}/${baseApkDir}/${name}.apk"

   // 对应tinker插件applyMapping
   baseApkProguardMapping = "${bakPath}/${baseApkDir}/${name}-mapping.txt"

   // 对应tinker插件applyResourceMapping
   baseApkResourceMapping = "${bakPath}/${baseApkDir}/${name}-R.txt"

   // 构建基准包和补丁包都要指定不同的tinkerId,并且必须保证唯一性
   tinkerId = "${myTinkerId}"

   // 构建多渠道补丁时使用
   // buildAllFlavorsDir = "${bakPath}/${baseApkDir}"

}

/**
* 一般来说,我们无需对下面的参数做任何的修改
* 对于各参数的详细介绍请参考:
* 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的分配
   }
}

在该项目中,我们使用enableProxyApplication = true方式进行接入,该方式可以尽可能少的改变自己的Application

【代码配置】

1.在自己的Application中进行如下初始化:

public class MyApplication extends Application{

    private static final String TAG = "MyApplication";

    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        //这里实现SDK初始化,appId为自己申请的appId
        //同时在调试时将第3个参数isDebug修改为true
        //是否提示用户重启,这里默认设置为false
        configTinker();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(mContext);
        // 安装tinker
        // 此接口仅用于反射Application方式接入。
        Beta.installTinker();
    }

    /**
     * 初始化Tinker
     */
    private void configTinker(){
        //是否开启热更新能力,默认为true
        Beta.enableHotfix = true;
        //是否开启自动下载补丁,默认为true
        Beta.canAutoDownloadPatch = true;
        //是否自动合成补丁,默认为true
        Beta.canAutoPatch = true;
        //是否提示用户重启,这里默认设置为false
        Beta.canNotifyUserRestart = true;
        //补丁回调接口
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String s) {
                Log.e(TAG, "补丁下载地址:" + s);
            }

            @Override
            public void onDownloadReceived(long l, long l1) {
                Log.e(TAG, String.format(Locale.getDefault(), "%s %d%%",
                        Beta.strNotificationDownloading,
                        (int) (l1 == 0 ? 0 : l * 100 / l1)));
            }

            @Override
            public void onDownloadSuccess(String s) {
                Log.e(TAG, "补丁下载成功");
                Toast.makeText(mContext, "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String s) {
                Log.e(TAG, "补丁下载失败");
                Toast.makeText(mContext, "补丁下载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplySuccess(String s) {
                Log.e(TAG, "补丁应用成功");
                Toast.makeText(mContext, "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String s) {
                Log.e(TAG, "补丁应用失败");
                Toast.makeText(mContext, "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {

            }
        };

        //设置开发设备,默认为false,上传补丁如果下发范围指定为“开发设备”,需要调用此接口来标识开发设备
        Bugly.setIsDevelopmentDevice(mContext, false);
        // 多渠道需求塞入
        // String channel = WalleChannelReader.getChannel(getApplication());
        // Bugly.setAppChannel(getApplication(), channel);
        // 这里实现SDK初始化,appId替换成你的在平台申请的appId
//        Bugly.init(mContext, "24662872d6", true);
    }

}

2.自定义Application、ApplicationLike

public class SampleApplication extends TinkerApplication{

    public SampleApplication() {
        super(ShareConstants.TINKER_ENABLE_ALL, "com.thekey.buglyhotfix.SampleApplicationLike",
                "com.tencent.tinker.loader.TinkerLoader", false);
    }

}
public class SampleApplicationLike extends DefaultApplicationLike {

    private static final String TAG = "SampleApplicationLike";

    private Application mContext;

    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();
        mContext = getApplication();
        configTinker();
    }

    @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 registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Beta.unInit();
    }

    /**
     * 初始化Tinker
     */
    private void configTinker(){
        //是否开启热更新能力,默认为true
        Beta.enableHotfix = true;
        //是否开启自动下载补丁,默认为true
        Beta.canAutoDownloadPatch = true;
        //是否自动合成补丁,默认为true
        Beta.canAutoPatch = true;
        //是否提示用户重启,这里默认设置为false
        Beta.canNotifyUserRestart = true;
        //补丁回调接口
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String s) {
                Log.e(TAG, "补丁下载地址:" + s);
            }

            @Override
            public void onDownloadReceived(long l, long l1) {
                Log.e(TAG, String.format(Locale.getDefault(), "%s %d%%",
                        Beta.strNotificationDownloading,
                        (int) (l1 == 0 ? 0 : l * 100 / l1)));
            }

            @Override
            public void onDownloadSuccess(String s) {
                Log.e(TAG, "补丁下载成功");
                Toast.makeText(mContext, "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String s) {
                Log.e(TAG, "补丁下载失败");
                Toast.makeText(mContext, "补丁下载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplySuccess(String s) {
                Log.e(TAG, "补丁应用成功");
                Toast.makeText(mContext, "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String s) {
                Log.e(TAG, "补丁应用失败");
                Toast.makeText(mContext, "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {

            }
        };

        //设置开发设备,默认为false,上传补丁如果下发范围指定为“开发设备”,需要调用此接口来标识开发设备
        Bugly.setIsDevelopmentDevice(mContext, false);
        // 多渠道需求塞入
        // String channel = WalleChannelReader.getChannel(getApplication());
        // Bugly.setAppChannel(getApplication(), channel);
        // 这里实现SDK初始化,appId替换成你的在平台申请的appId
        Bugly.init(mContext, "24662872d6", true);
    }


}

【配置xml】

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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" />
 <provider
    android:name="android.support.v4.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>

<?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>

注意:这里配置的两个外部存储路径是升级SDK下载的文件可能存在的路径,一定要按照上面格式配置,不然可能会出现错误。

注:1.3.1及以上版本,可以不用进行以上配置,aar已经在AndroidManifest配置了,并且包含了对应的资源文件。


【混淆配置】

为了避免混淆SDK,需要在Proguard混淆文件中增加以下配置:

-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
# tinker混淆规则
-dontwarn com.tencent.tinker.**
-keep class com.tencent.tinker.** { *; }

//如果你使用了support-v4包,你还需要配置以下混淆规则:
-keep class android.support.**{*;}

【如何打包】

1.编译基准包
这里需要进行配置,主要配置tinkerid以及variantName


这里进行配置打什么类型的包
[图片上传失败...(image-8d16f8-1547370765018)]


tinkerId最好是一个唯一标识,例如git版本号、versionName等等。 如果你要测试热更新,你需要对基线版本进行联网上报。

[图片上传失败...(image-6f87fd-1547370765018)]

如:打基准包时可以命名为:"base- + "你的版本号"
打差异包时可以命名为: "patch-" + "你的版本号" + ".x.x"


2.执行assembleRelease打Release基准包
[图片上传失败...(image-dabacc-1547370765018)]

3.配置目录
[图片上传失败...(image-2d17f0-1547370765018)]

[图片上传失败...(image-ccb5b7-1547370765018)]

4.执行buildTinkerPatchRelease打对应的差异包

[图片上传失败...(image-9e377b-1547370765018)]

完成之后,差异包会在outputs/patch/release/路径下的patch_signed_7zip.apk

[图片上传失败...(image-ffe333-1547370765018)]

[图片上传失败...(image-31efc-1547370765018)]

该YAPATCH.MF文件中包含基准包和差异包相关对应信息:

[图片上传失败...(image-15beff-1547370765018)]

5.获取差异包之后,最好将后缀改为 .jar .zip .dex ,防止运营商劫持

【上传补丁】

1.上传补丁到Bugly

[图片上传失败...(image-b19482-1547370765018)]

[图片上传失败...(image-1adbff-1547370765018)]

2.在加载补丁的过程中可以在log看到相关信息:

[图片上传失败...(image-ef2ef4-1547370765018)]

[图片上传失败...(image-25b421-1547370765018)]

【支持加固】

只需改变该配置即可:在tinker-support配置当中设置isProtectedApp = true,表示你要打加固的的apk。 是否使用加固模式,仅仅将变更的类合成补丁。注意,这种模式仅仅可以用于加固应用中。

【API文档】
1.安装Tinker

Beta.installTinker();
Beta.installTinker(this);

2.指定加载路径

Beta.applyTinkerPatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/patch_signed_7zip.apk");

3.清除补丁

Beta.cleanTinkerPatch();

4.主动检查更新

Beta.checkUpgrade();

5.设置是否允许自动下载补丁

Beta.canAutoDownloadPatch = true;

6.设置是否允许自动合成补丁

Beta.canAutoPatch = true;

7.设置是否显示弹窗提示用户重启

Beta.canNotifyUserRestart = false

8.用户主动下载补丁文件

 Beta.downloadPatch();

9.用户主动合成补丁

Beta.applyDownloadedPatch();

10.相关回调

Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
                Toast.makeText(getApplication(), "补丁下载地址" + patchFile, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                Toast.makeText(getApplication(),
                        String.format(Locale.getDefault(), "%s %d%%",
                                Beta.strNotificationDownloading,
                                (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadSuccess(String msg) {
                Toast.makeText(getApplication(), "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String msg) {
                Toast.makeText(getApplication(), "补丁下载失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onApplySuccess(String msg) {
                Toast.makeText(getApplication(), "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String msg) {
                Toast.makeText(getApplication(), "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {
                Toast.makeText(getApplication(), "补丁回滚", Toast.LENGTH_SHORT).show();
            }
        };

更对相关API及说明,请参照热更新API - Bugly 文档

举报

相关推荐

0 条评论