美文网首页Android开发Android知识Android 技术开发
Bugly(Tinker)详细集成热更新及使用

Bugly(Tinker)详细集成热更新及使用

作者: laer_L | 来源:发表于2017-01-03 17:01 被阅读2422次
demo链接:https://github.com/93Laer/TinkerDome

标题之所以加上了tinker, 是因为bugly就是采用的tinker来做热更新处理

集成步骤如下:
  • 首先在工程gradle文件中添加依赖
 dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

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

        // tinkersupport插件
        classpath "com.tencent.bugly:tinker-support:latest.release"
    }
  • 复制下面代码到module的gradle中
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-debug-0103-14-57-18.apk"
    // proguard mapping file to build patch apk
    tinkerApplyMappingPath = "${bakPath}/app-debug-0103-14-57-18-mapping.txt"
    // resource R.txt to build patch apk, must input if there is resource changed
    tinkerApplyResourcePath = "${bakPath}/app-debug-0103-14-57-18-R.txt"

    // only use for build all flavor, if not, just ignore this field
    tinkerBuildFlavorDirectory = "${bakPath}/app-debug-0103-14-57-18"
}

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
}

/**
 * 更多Tinker插件详细的配置,参考:https://github.com/Tencent/tinker/wiki
 */
if (buildWithTinker()) {
    apply plugin: 'com.tencent.bugly.tinker-support'
    // 依赖tinker插件
    apply plugin: 'com.tencent.tinker.patch'

    tinkerSupport {
    }

    // 全局信息相关配置项
    tinkerPatch {
        oldApk = getOldApkPath() //必选, 基准包路径

        ignoreWarning = false // 可选,默认false

        useSign = true // 可选,默认true, 验证基准apk和patch签名是否一致

        // 编译相关配置项
        buildConfig {
            applyMapping = getApplyMappingPath() //  可选,设置mapping文件,建议保持旧apk的proguard混淆方式
            applyResourceMapping = getApplyResourceMappingPath() // 可选,设置R.txt文件,通过旧apk文件保持ResId的分配
            tinkerId = "1.0.2" // 必填,这里填写你自己的,这个可以随便写,但是对于你的app必须是唯一的
        }

        // dex相关配置项
        dex {
            dexMode = "jar" // 可选,默认为jar
            usePreGeneratedPatchDex = false // 可选,默认为false
            pattern = ["classes*.dex",
                       "assets/secondary-dex-?.jar"]
            //注意 必选
            loader = ["com.tencent.tinker.loader.*",
                      "bugly.haegyeong.com.testbugly.SampleApplication",
            ]
        }

        // lib相关的配置项
        lib {
            pattern = ["lib/armeabi/*.so"]
        }

        // res相关的配置项
        res {
            pattern = ["res/*", "assets/*", "resources.arsc", "AndroidManifest.xml"]
            ignoreChange = ["assets/sample_meta.txt"]
            largeModSize = 100
        }

        // 用于生成补丁包中的'package_meta.txt'文件
        packageConfig {
            configField("patchMessage", "tinker is sample to use")

            configField("platform", "all")

            configField("patchVersion", "1.0")
        }

        // 7zip路径配置项,执行前提是useSign为true
        sevenZip {
            zipArtifact = "com.tencent.mm:SevenZip:1.1.10" // optional
            //  path = "/usr/local/bin/7za" // optional
        }

        // 如果只用我们提供的插件,可以进行以下配置
        /* apply plugin: 'com.tencent.bugly.tinker-support'
    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 = "aaaaafasdfasdfasdfasdf"
    }*/

    }
}

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

            }
        }
    }
}
  • 在module的gradle中添加依赖
 dependencies {
          // 多dex配置
          compile "com.android.support:multidex:1.0.1"
          compile 'com.tencent.bugly:crashreport_upgrade:latest.release'//其中latest.release指代最新版本号,也可以指定明确的版本号,例如1.2.0
      }

注:如果报一下图片中的错误

报错

解决办法直接将: usePreGeneratedPatchDex = false // 可选,默认为false注释掉即可,现在的微信热更新demo里面没有这句代码了

  • 自定义Application
public class SampleApplication extends TinkerApplication {
    public SampleApplication() {
        super(ShareConstants.TINKER_ENABLE_ALL, "xxx.xxx.SampleApplicationLike",//这里xx对应的是你的SampleApplicationLike所在的包名。例如:"com.laer.tinkerdome.SampleApplicationLike"
                "com.tencent.tinker.loader.TinkerLoader", false);
    }
}
  • 自定义ApplicationLike
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, Resources[] resources,
            ClassLoader[] classLoader, AssetManager[] assetManager) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime,
                applicationStartMillisTime, tinkerResultIntent, resources, classLoader,
                assetManager);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        // 这里实现SDK初始化,appId替换成你的在Bugly平台申请的appId
        Bugly.init(getApplication(), "你的appid", 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);
    }

}
  • 配置权限
<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" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • 在清单文件中配置application
 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name=".SampleApplication"//这里填写刚刚的SampleApplication
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
注:name可以不是全名
  • 到此热更新就集成完了,但是原文文档下面还有一大截,个人觉得下面那几段对于热更新来说放到哪里有点碍眼
    如果同步后发现tinkerId没有设置这个错误,就随便设置一个就好了,但一般用versionName或是git版本号

使用步骤如下:

  • 首先写一个原版简单的代码(给Hello World!一个点击事件)
 public void onClick(View v){
        ((TextView)v).setText("这是旧的代码");
//        ((TextView)v).setText("这是新的代码");
    }
  • 双击如图位置,生成基准包,并把这个基准包安装到手机(可以直接将包放到手机,再安装),
Paste_Image.png
  • 切换视图project
Paste_Image.png
  • 更改module的gradle的配置(把名字前面的改到一样)
Paste_Image.png
到这里基准包就创建完毕了,这里需要开启手机刚刚安装的这个基准包app,它会自动上传信息,这步是必须的,会影响到后面上传补丁
  • 更改代码,实现想要的功能
 public void onClick(View v){
//        ((TextView)v).setText("这是旧的代码");
        ((TextView)v).setText("这是新的代码");
    }

  • 打包补丁
Paste_Image.png
  • 上传补丁
上传补丁 选择补丁
注意这里一定要是patch里面的,注:不要选择tinkerPatch目录下的补丁包,不然上传会有问题 发布到所有版本
  • 接下来就可以退出app,重新进入了,但是我在测试时一直没有出现效果,一度茫然,以为代码出错,结果过了十多分钟后,又成功了

后台查看

更新补丁的数量

相关文章

网友评论

    本文标题:Bugly(Tinker)详细集成热更新及使用

    本文链接:https://www.haomeiwen.com/subject/pccnvttx.html