Android Studio中如何自定义Android BuildConfig配置文件

时间:2024-05-31 14:38:53

一个project会有多个app,不同module中都要配置compileSdkVersion、buildToolsVersion等变量值,这时候每个app中的compile工程如果不能统一,在以后升级里会很麻烦,所以我们要把这些公共的配置项称为共享变量。
步骤:
1、在项目的根目录下定义了一个build_config.gradle的配置文
config.gradle:
configField 数组中定义 测试环境和正式环境的地址还有API版本和apk的名字


ext {

    configField = [
              ServerAddress_release    : "\"https://s.xxxx.com/\"",
//              ServerAddress_release    : "\"http://inflexion.xxxx.com/\"",



//              ServerAddress_debug      : "\"https://s.xxxx.com/\"",
              ServerAddress_debug      : "\"http://inflexion.xxxx.com/\"",



              APIVersionName           : "\"ver\"",
              APIVersionCode           : "\"2.36\"",
              APKVersionName_release   : "车店长Boss_正式版_",
              APKVersionName_debug     : "车店长Boss_测试版_",
    ]

    android = [
               compileSdkVersion       : 25,
               buildToolsVersion       : "26.0.2",
               minSdkVersion           : 20,
               targetSdkVersion        : 25,
               versionCode             : 15,
               versionName             : "3.13.0"
    ]

versions数组,用来存放compileSdkVersion、versionCode、versionName等数据:

     version = [
//                androidSupportSdkVersion: "23.1.1",
                   androidSupportSdkVersion: "25.0.0",
                   retrofitSdkVersion      : "2.3.0",
                   dagger2SdkVersion       : "2.11",
                   glideSdkVersion         : "4.0.0",
                   butterknifeSdkVersion   : "8.7.0",
                   rxlifecycleSdkVersion   : "1.0",
                   rxlifecycle2SdkVersion  : "2.1.0",
                   espressoSdkVersion      : "2.2.2",
                   canarySdkVersion        : "1.5.1",
                   rxbindingSdkVersion     : "0.4.0"
        ]

dependencies数组,用来存放第三发依赖的地址;

    dependencies = [

                //support
                "appcompat-v7"             : "com.android.support:appcompat-v7:${version["androidSupportSdkVersion"]}",
                "design"                   : "com.android.support:design:${version["androidSupportSdkVersion"]}",
                "support-v4"               : "com.android.support:support-v4:${version["androidSupportSdkVersion"]}",
                "cardview-v7"              : "com.android.support:cardview-v7:${version["androidSupportSdkVersion"]}",
                "annotations"              : "com.android.support:support-annotations:${version["androidSupportSdkVersion"]}",
                "recyclerview-v7"          : "com.android.support:recyclerview-v7:${version["androidSupportSdkVersion"]}",
                "gridlayout-v7"            : "com.android.support:gridlayout-v7:${version["androidSupportSdkVersion"]}",

                //network
                "retrofit"                 : "com.squareup.retrofit2:retrofit:${version["retrofitSdkVersion"]}",
                "retrofit-converter-gson"  : "com.squareup.retrofit2:converter-gson:${version["retrofitSdkVersion"]}",
                "retrofit-adapter-rxjava"  : "com.squareup.retrofit2:adapter-rxjava:${version["retrofitSdkVersion"]}",
                "retrofit-adapter-rxjava2" : "com.squareup.retrofit2:adapter-rxjava2:${version["retrofitSdkVersion"]}",
                "okhttp3"                  : "com.squareup.okhttp3:okhttp:3.8.1",
                "okhttp-urlconnection"     : "com.squareup.okhttp:okhttp-urlconnection:2.0.0",
                "glide"                    : "com.github.bumptech.glide:glide:${version["glideSdkVersion"]}",
                "glide-compiler"           : "com.github.bumptech.glide:compiler:${version["glideSdkVersion"]}",
                "glide-loader-okhttp3"     : "com.github.bumptech.glide:okhttp3-integration:${version["glideSdkVersion"]}",
                "picasso"                  : "com.squareup.picasso:picasso:2.5.2",

                //view
                "autolayout"               : "com.zhy:autolayout:1.4.5",
                "butterknife"              : "com.jakewharton:butterknife:${version["butterknifeSdkVersion"]}",
                "butterknife-compiler"     : "com.jakewharton:butterknife-compiler:${version["butterknifeSdkVersion"]}",
                "pickerview"               : "com.contrarywind:Android-PickerView:3.2.5",
                "photoview"                : "com.github.chrisbanes.photoview:library:1.2.3",
                "numberprogressbar"        : "com.daimajia.numberprogressbar:library:[email protected]",
                "nineoldandroids"          : "com.nineoldandroids:library:2.4.0",
                "paginate"                 : "com.github.markomilos:paginate:0.5.1",
                "vlayout"                  : "com.alibaba.android:vlayout:[email protected]",

                //rx1
                "rxandroid"                : "io.reactivex:rxandroid:1.2.1",
                "rxjava"                   : "io.reactivex:rxjava:1.2.1",
                "rxlifecycle"              : "com.trello:rxlifecycle:${version["rxlifecycleSdkVersion"]}",
                "rxlifecycle-components"   : "com.trello:rxlifecycle-components:${version["rxlifecycleSdkVersion"]}",
                "rxcache"                  : "com.github.VictorAlbertos.RxCache:runtime:1.7.0-1.x",
                "rxcache-jolyglot-gson"    : "com.github.VictorAlbertos.Jolyglot:gson:0.0.3",
                "rxbinding-recyclerview-v7": "com.jakewharton.rxbinding:rxbinding-recyclerview-v7:1.0.1",
                "rxpermissions"            : "com.tbruyelle.rxpermissions:rxpermissions:[email protected]",
                "rxerrorhandler"           : "me.jessyan:rxerrorhandler:1.0.1",

                //rx2
                "rxandroid2"                : "io.reactivex.rxjava2:rxandroid:2.0.1",
                "rxjava2"                   : "io.reactivex.rxjava2:rxjava:2.1.1",
                "rxlifecycle2"              : "com.trello.rxlifecycle2:rxlifecycle:${version["rxlifecycle2SdkVersion"]}",
                "rxlifecycle2-components"   : "com.trello.rxlifecycle2:rxlifecycle-components:${version["rxlifecycle2SdkVersion"]}",
                "rxcache2"                  : "com.github.VictorAlbertos.RxCache:runtime:1.8.1-2.x",
                "rxpermissions2"            : "com.tbruyelle.rxpermissions2:rxpermissions:[email protected]",
                "rxerrorhandler2"           : "me.jessyan:rxerrorhandler:2.0.2",

                //rxbinding
                "rxbinding"                  : "com.jakewharton.rxbinding:rxbinding:${version["rxbindingSdkVersion"]}",
                "rxbinding-design"           : "com.jakewharton.rxbinding:rxbinding-design:${version["rxbindingSdkVersion"]}",
                "rxbinding-kotlin"           : "com.jakewharton.rxbinding:rxbinding-kotlin:${version["rxbindingSdkVersion"]}",
                "rxbinding-support-v4"           : "com.jakewharton.rxbinding:rxbinding-support-v4:${version["rxbindingSdkVersion"]}",
                "rxbinding-support-v7"           : "com.jakewharton.rxbinding:rxbinding-appcompat-v7:${version["rxbindingSdkVersion"]}",

                //tools
                "dagger2"                  : "com.google.dagger:dagger:${version["dagger2SdkVersion"]}",
                "dagger2-compiler"         : "com.google.dagger:dagger-compiler:${version["dagger2SdkVersion"]}",
                "androideventbus"          : "org.simple:androideventbus:1.0.5.1",
                "otto"                     : "com.squareup:otto:1.3.8",
                "gson"                     : "com.google.code.gson:gson:2.8.1",
                "multidex"                 : "com.android.support:multidex:1.0.1",
                "javax.annotation"         : "javax.annotation:jsr250-api:1.0",
                "arouter"                  : "com.alibaba:arouter-api:1.2.1.1",
                "arouter-compiler"         : "com.alibaba:arouter-compiler:1.1.2.1",
                "progressmanager"          : "me.jessyan:progressmanager:+",

                //test
                "junit"                    : "junit:junit:4.12",
                "androidJUnitRunner"       : "android.support.test.runner.AndroidJUnitRunner",
                "runner"                   : "com.android.support.test:runner:0.5",
                "espresso-core"            : "com.android.support.test.espresso:espresso-core:${version["espressoSdkVersion"]}",
                "espresso-contrib"         : "com.android.support.test.espresso:espresso-contrib:${version["espressoSdkVersion"]}",
                "espresso-intents"         : "com.android.support.test.espresso:espresso-intents:${version["espressoSdkVersion"]}",
                "mockito-core"             : "org.mockito:mockito-core:1.+",
                "timber"                   : "com.jakewharton.timber:timber:4.5.1",
                "logger"                   : "com.orhanobut:logger:2.1.1",
                "canary-debug"             : "com.squareup.leakcanary:leakcanary-android:${version["canarySdkVersion"]}",
                "canary-release"           : "com.squareup.leakcanary:leakcanary-android-no-op:${version["canarySdkVersion"]}",
                "umeng-analytics"          : "com.umeng.analytics:analytics:6.0.1"
        ]


}

2、在项目根目录的build.gradle中直接引入我们配置的build_config.gradle配置文件。

apply from: “config.gradle”

Android Studio中如何自定义Android BuildConfig配置文件
3、当我们编写完自定义的gradle files,在Android Studio中实时保持同步

Android Studio中如何自定义Android BuildConfig配置文件

4、使用的时候:在各个module的build.gradle里面使用

android {
    compileSdkVersion rootProject.ext.android["compileSdkVersion"]
    buildToolsVersion '26.0.2'
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    defaultConfig {
        applicationId "com.icarzoo"
        minSdkVersion rootProject.ext.android["minSdkVersion"]
        targetSdkVersion rootProject.ext.android["targetSdkVersion"]
        versionCode rootProject.ext.android["versionCode"]
        versionName rootProject.ext.android["versionName"]
      ...
        }
   buildTypes {
        release {
            buildConfigField('boolean', 'isShowLoaCat', "false")
            buildConfigField('String', 'APIVersionName', rootProject.ext.configField["APIVersionName"])
            buildConfigField('String', 'APIVersionCode', rootProject.ext.configField["APIVersionCode"])
            buildConfigField('String', 'ServerAddress', rootProject.ext.configField["ServerAddress_release"])
            signingConfig signingConfigs.release
            debuggable true
            minifyEnabled true
            zipAlignEnabled true
            pseudoLocalesEnabled false //默认false,是否支持本地化整理
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            buildConfigField('boolean', 'isShowLoaCat', "true")
            buildConfigField('String', 'APIVersionCode', rootProject.ext.configField["APIVersionCode"])
            buildConfigField('String', 'APIVersionName', rootProject.ext.configField["APIVersionName"])
            buildConfigField('String', 'ServerAddress', rootProject.ext.configField["ServerAddress_debug"])
            //signingConfig signingConfigs.release
            debuggable true
            minifyEnabled false

            zipAlignEnabled true
            pseudoLocalesEnabled false //默认false,是否支持本地化整理
        }
    }
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
//            def outputFile = output.outputFile
//            def outputFile = outputFileName
            def fileName
            if (variant.buildType.name.equals('release')) {
                fileName = "${rootProject.ext.configField["APKVersionName_release"]}.apk"
            } else if (variant.buildType.name.equals('debug')) {
                fileName = "${rootProject.ext.configField["APKVersionName_debug"]}.apk"
            }
//            ${project.projectDir}/../outputs/apks/+ variant.name
            outputFileName = new File("", fileName)
//            output.outputFile = new File(outputFile.parent, fileName)
//            outputFileName  = new File(outputFile.parent, fileName)
        }
    }
    dependencies {
    testCompile 'junit:junit:4.12'

    //  所需的support包
    compile rootProject.ext.dependencies["multidex"]
    compile rootProject.ext.dependencies["appcompat-v7"]
    compile rootProject.ext.dependencies["annotations"]
    compile rootProject.ext.dependencies["recyclerview-v7"]
    compile rootProject.ext.dependencies["design"]
    compile rootProject.ext.dependencies["support-v4"]
    compile rootProject.ext.dependencies["gridlayout-v7"]
    compile rootProject.ext.dependencies["cardview-v7"]


    //  Rxbinding
    compile rootProject.ext.dependencies["rxbinding"]
    compile rootProject.ext.dependencies["rxbinding-design"]
    compile rootProject.ext.dependencies["rxbinding-kotlin"]
    compile rootProject.ext.dependencies["rxbinding-support-v4"]
    compile rootProject.ext.dependencies["rxbinding-support-v7"]
    ...
    }

buildConfigField使用的时候 这样调用:

public class NetWorkURLBean {

    /**
     * 访问服务端的地址

     */
    public static String ADDRESS = BuildConfig.ServerAddress + "api/";
    public static String ADDRESS_2 = BuildConfig.ServerAddress;

    /**
     * 登录
    */
    public static final String STAFF = ADDRESS + "store_staff/staff_user/lunch_login";

详细的标签解释链接:https://www.jianshu.com/p/7ca459085b96