如何从 gradle 原始配置方式 转到 version catelogs 配置

文章已过时:请查看google 官方配置
https://developer.android.com/studio/build/migrate-to-catalogs?hl=zh-cn

先贴一下gradle 配置
外层 build.gradle

buildscript {
    ext {

        compileSdkVersion = 33
        minSdkVersion = 21
        targetSdkVersion = 33
        applicationId = 'com.aaa.bbb'
        
        versionName = '1.4.8'
        versionCode = 148

        debugStoreFile = '../platform.jks'
        debugKeyAlias = 'android'
        storeFile = '../platform.jks'
        storePassword = 'android'
        keyAlias = 'android'
        keyPassword = 'android'

        coreKtxVersion = '1.9.0'
        appcompatVErsion = '1.5.1'
        materialVersion = '1.6.1'
        constraintlayoutVersion = '2.1.4'
        lifecycleLivedataKtx = '2.5.1'
        lifecycleViewmodelKtx = '2.5.1'
        coroutinesVersion = "1.6.4"
        junitVersion = '1.1.3'
        espressoCoreVersion = '3.4.0'
        estExtJunit = '1.1.3'
        recyclerViewVersion = '1.3.0-rc01'
        retrofitVersion = '2.9.0'
        roomVersion = '2.4.3'
        viewPagerVersion = '1.0.0'
        workVersion = '2.7.1'
        gsonVersion = '2.9.0'
        glideVersion = '4.12.0'
        fragmentVersion = '1.3.0'
        hiltVersion = '2.3.5'
        navigationVersion = '2.5.2'
        okhttpLoggingVersion = '4.9.3'
        hiltVersion = '2.44'
        gradleVersion = '7.3.1'
        kotlinVersion = '1.5.30'
        startupVersion = '1.1.0'
        aspectjVersion = '1.8.9'
        toastyVersion= '1.5.0'
        aspectjrtVersion='1.9.5'
        BaseRecyclerViewAdapterHelperVersion = '3.0.4'
        switchViewVersion='1.1.7'
        utilcodexVersion='1.30.1'
        hawkVersion = '2.0.1'
        easypermissionsVersion = '3.0.0'
        legacySupportVersion='1.0.0'
        dialogx_version = "0.0.45.beta17"
        EasyPhotosVersion = '3.1.4'
        PickerViewVersion = '4.1.9'
        updateVersion= '1.1.0'
    }
    repositories {
        maven { url 'https://maven.aliyun.com/repository/public' }//jcenter
        maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }//gradle-plugin
        maven { url 'https://maven.aliyun.com/repository/central' }//central
        maven { url 'https://maven.aliyun.com/repository/google' }//google
        maven { url "https://jitpack.io" }
        maven {
            allowInsecureProtocol = true
            url 'http://xx.xx.xx.xx:8081/repository/maven-public/'
        }
        google()


    }
    dependencies {
        //classpath 'com.github.2017398956:AspectPlugin:2.4'
        classpath "com.android.tools.build:gradle:$gradleVersion"
        //classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hiltVersion"
    }


}


task clean(type: Delete) {
    delete rootProject.buildDir
}

内层 gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'androidx.navigation.safeargs.kotlin'
    id 'kotlin-kapt'
    //id 'AspectPlugin'
    id 'dagger.hilt.android.plugin'
}

static def buildApkTime() {
    return new Date().format("yyyyMMddHHmmss")
}

android {
    signingConfigs {
        debug {
            storeFile file(rootProject.debugStoreFile)
            storePassword rootProject.storePassword
            keyAlias rootProject.debugKeyAlias
            keyPassword rootProject.keyPassword
        }
        release {
            storeFile file(rootProject.storeFile)
            storePassword rootProject.storePassword
            keyAlias rootProject.keyAlias
            keyPassword rootProject.keyPassword
        }
    }
    compileSdk rootProject.compileSdkVersion
    buildFeatures {
        dataBinding true
    }
    flavorDimensions "versionCode"

    defaultConfig {
        applicationId rootProject.applicationId
        minSdk rootProject.minSdkVersion
        targetSdk rootProject.targetSdkVersion
        versionCode rootProject.versionCode
        versionName rootProject.versionName
        vectorDrawables.useSupportLibrary true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
        signingConfig signingConfigs.debug
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters 'armeabi', 'armeabi-v7a'
        }
    }

    buildTypes {
        debug {
            minifyEnabled false
            signingConfig signingConfigs.release
            jniDebuggable true
            debuggable true
            renderscriptDebuggable true

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

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = "11"
        freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
        freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.FlowPreview"
    }
    lint {
        abortOnError false
        checkReleaseBuilds false
    }
    namespace 'com.aaa.bbb'
    android.applicationVariants.all { variant ->
        def fileName
        variant.outputs.all {
            if (outputFile != null && outputFile.name.endsWith('.apk')) {
                if (variant.buildType.name == 'release') {
                    fileName = "aaa_android_v${defaultConfig.versionName}_${variant.buildType.name}.apk"
                } else if (variant.buildType.name == 'debug') {
                    fileName = "aaa_android_v${defaultConfig.versionName}.apk"
                }
                outputFileName = fileName
                println(outputFileName)
            }
        }
        variant.assemble.doLast {
            File out = new File("E://Apk打包文件夹/aaa")
            variant.outputs.forEach { file ->
                copy {
                    from file.outputFile
                    into out
                }
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar", '*.aar'])
    implementation "androidx.core:core-ktx:$rootProject.coreKtxVersion"
    implementation "androidx.appcompat:appcompat:$rootProject.appcompatVErsion"
    implementation "com.google.android.material:material:$rootProject.materialVersion"
    implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintlayoutVersion"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleLivedataKtx"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleViewmodelKtx"
    implementation "com.google.code.gson:gson:$rootProject.gsonVersion"
    implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttpLoggingVersion"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutinesVersion"
    implementation "com.squareup.retrofit2:converter-gson:$rootProject.retrofitVersion"
    implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion"
    implementation "androidx.work:work-runtime-ktx:$rootProject.workVersion"
    implementation "com.github.bumptech.glide:glide:$rootProject.glideVersion"
    annotationProcessor "com.github.bumptech.glide:compiler:$rootProject.glideVersion"
    implementation "com.google.dagger:hilt-android:$rootProject.hiltVersion"
    implementation "androidx.navigation:navigation-fragment-ktx:$rootProject.navigationVersion"
    implementation "androidx.navigation:navigation-ui-ktx:$rootProject.navigationVersion"
    implementation "androidx.recyclerview:recyclerview:$rootProject.recyclerViewVersion"
    kapt "com.google.dagger:hilt-android-compiler:$rootProject.hiltVersion"
    kapt "androidx.room:room-compiler:$rootProject.roomVersion"
    implementation "androidx.room:room-runtime:$rootProject.roomVersion"
    implementation "androidx.room:room-ktx:$rootProject.roomVersion"
    implementation "androidx.startup:startup-runtime:$rootProject.startupVersion"
    androidTestImplementation "androidx.test.ext:junit:$rootProject.estExtJunit"
    androidTestImplementation "androidx.test.espresso:espresso-core:$rootProject.espressoCoreVersion"
    implementation "org.aspectj:aspectjrt:$rootProject.aspectjrtVersion"
    implementation "com.github.CymChad:BaseRecyclerViewAdapterHelper:$rootProject.BaseRecyclerViewAdapterHelperVersion"
    implementation "com.ld:switchView:$rootProject.switchViewVersion"
    implementation "com.blankj:utilcodex:$rootProject.utilcodexVersion"
    implementation "com.orhanobut:hawk:$rootProject.hawkVersion"
    implementation "com.github.GrenderG:Toasty:$rootProject.toastyVersion"
    implementation "pub.devrel:easypermissions:$rootProject.easypermissionsVersion"
    implementation "androidx.legacy:legacy-support-v4:$rootProject.legacySupportVersion"
    implementation "com.github.kongzue.DialogX:DialogX:$rootProject.dialogx_version"
    implementation "com.github.HuanTanSheng:EasyPhotos:$rootProject.EasyPhotosVersion"
    implementation "com.contrarywind:Android-PickerView:$rootProject.PickerViewVersion"
    implementation 'com.caverock:androidsvg-aar:1.3'


}

看了最新的更新,决定切换到kotlin和version catalogs

首先,不要按照官网的说法,先把文件名改成build.gradle.kts,这样做你很难搞清楚到底哪里出问题了。
第一步,先升级android studio
目前最新版是 Android Studio Dolphin | 2021.3.1 Patch 1,升级过程中注意 compileSdktargetSdk,为了避免麻烦,直接升级到33就行了,能省去后面很多麻烦。
第二步,升级kotlin 版本
主要过程是:File->setting->Plugins,如图

image.png

升级到最新即可,目前最新版本是1.7.20,对应gradle 版本是 7.1+,升级过程中有个小技巧,即gradle 的位置。
如果每次都从
https://services.gradle.org/distributions/gradle-7.5.1-bin.zip
下载,挺浪费时间的,建议从
https://gradle.org/releases/
下载需要的版本,放在硬盘上一个文件夹内。(注意不要解压),然后在此文件

image.png

中修改 distributionUrl

image.png

注意由原来的 https://services.gradle.org/distributions/gradle-7.5.1-bin.zip 修改为 file:///E:/gradle/gradle-7.4-all.zip 即可

此步骤要注意的是 Plugins 中的kotlin版本一定要和 setting 中的kotlin Compiler 版本对应,Project 的build.gradle 中的 gradle版本和上图中的gradle 版本对应。一旦出错,先检车这两个方面
第三步,升级各依赖包版本版本和 java 版本
这一步没什么好说的,鼠标放在module 中的dependencies 各依赖包上,有新版本会弹出对应提示,按照提示升级即可。另外,如果检查有没有新版本,可以前往maven中检查
http://mvnrepository.com/ 对应版本

另外 java版本的问题,不建议安装 java 11 JDK,但是可以这样用


image.png

然后,选择11即可


image.png

至此,升级kotlin和 catalogs 前置工作准备完毕。另外说一下版本的问题。有同学认为程序能运行就可以,不必升级最新稳定版本,其实笔者认为这是不正确的,很多时候程序运行过程中的bug就是由于版本低引起的。
现在可以重现编译项目,然后能够正常运行的话可以准备升级 catalogs 了

第四步,升级gradle 为kotlin 语法
在gradle 仍然使用 groovy的时候 管理gradle 依赖可以使用 buildSrc, ext,以及外链 apply 不嫌麻烦的话其实 外链apply最好用,ext也不错。
当然我们现在要升级 kotlin了,当然要使用 datalogs。我建议大家第一次用的话,慢慢来,先修改其中一句代码,然后同步一下gradle,看看有没有问题,有问题就查查gradle api,看看具体怎么解决,这样虽然慢,但是总体来说比较简单。
首先我们先修改 settting.gradle,这是gradle的入口,要注意几点

  • maven { url 'https://maven.aliyun.com/repository/public'} 要改成 maven { setUrl("https://maven.aliyun.com/repository/public") }
  • 有使用自建仓库的,如果没有https, 原来是
    maven { allowInsecureProtocol = true url 'http://xx.xxx.xx.xx:8081/repository/maven-public/' } 要改成 maven { isAllowInsecureProtocol = true url = uri("http://xx.xx.xx.xx:8081/repository/maven-public/") }

然后把 setting.gradle 直接重命名为 setting.gradle.kts ,重新编译一下,就可以了
第五步,创建catalogs文件
在gradle 文件夹中创建 file,名称为 libs.versions.toml
先写 [versions] 这是版本号的标签 以 名称 = “版本号“ 格式,其中名称可以随便写,符合自己习惯即可。
然后写 [libraries] ,这里的格式为 名称= { module = " group ID : artifact ID", version.ref = "版本号" } ,这里的名称最好是artifact ID ,然后把其中的点改成下划线,如com.google.dagger:hilt-android-gradle-plugin:2.44 改成符合格式的就是hilt-android-gradle-plugin= { module = "com.google.dagger:hilt-android-gradle-plugin", version.ref = "hiltVersion" } ,其中 hiltVersion就是在[versions] 中定义

注意:名称不能以大写字母开头

第五步,修改Module 的build.gradle
到这里就简单多了,主要配置dependencies ,配置成 implementation(libs.gson) 这种格式,其中libs 是datalogs 文件名称,后面的就是在 [libraries] 中定义的响应名称,这里不需要写版本。

关于如何把groovy 改成kotlin 请参考大神文章https://zhuanlan.zhihu.com/p/381942140,这是我目前看到最明白的。
第五步,修改Project 的build.gradle
最后一步,直接改完 重新编辑就可以。


最新更新:看到大神写的一篇,https://www.jianshu.com/p/7ccdca8199b8

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容