Gradle脚本中定义编译常量

说明

  • Android Studio等IDE都使用了gradle作为编译脚本,定义相关变量能够提高开发效率,便于随时切换环境
  1. BuildConfig成员变量:
    生成后都是public static final 类型;在gradle脚本中定义方式为:

    defaultConfig {
    	...
    	buildConfigField "String", "APP_KEY", '"3b495847766em3f74f6e07d0"'
    	buildConfigField "Integer", "DEFAULT_PORT", '5000'
    }
    

    生成文件为对应包下的BuildConfig.java

  2. Manifest常量,在AndroidManifest.xml中使用例如${XIAOMI_APPKEY}

    manifestPlaceholders = [
           PKGNAME   : applicationId,
           CHANNEL   : "developer-default",
           XIAOMI_APPKEY   : "MI-549754564161",
           HUAWEI_APPID    : "10374276",
           MAP_APPKEY     : "b10033ef0204e72768c8082677475283"]
    
  3. gradle.properities定义全局键值对

    COMPILE_SDK_VERSION=28
    BUILD_TOOLS_VERSION=28.0.0
    TARGET_SDK_VERSION=28
    MIN_SDK_VERSION=21
    
    VERSION_NAME=1.0.0
    VERSION_CODE=1
    

    使用规则: 在model的build.gradle中,字符串可以直接引用,整形需在后加 as int

    defaultConfig {
    	minSdkVersion MIN_SDK_VERSION as int
    	targetSdkVersion TARGET_SDK_VERSION as int
    	versionCode VERSION_CODE as int
    	versionName VERSION_NAME as String
    }
    
  4. 全局build.gradle中定义常量

    ext{
    	frescoVersion = '1.13.0'
    	eventbusVersion = '3.1.1'
     	picassoVersion = '2.5.2'
    	retrofitVersion = '2.5.0'
    	okhttploggingVersion = '3.4.1'
    	okhttpVersion = '3.4.1'
    }
    

    使用方法,在model的build.gradle中引用示例:

    dependencies {
    	//Fresco
    	api "com.facebook.fresco:fresco:$rootProject.frescoVersion"
    	api "com.facebook.fresco:imagepipeline-okhttp3:$rootProject.frescoVersion"
    
    	//eventbus
    	api "org.greenrobot:eventbus:$rootProject.eventbusVersion"
    
    	//picasso
    	api "com.squareup.picasso:picasso:$rootProject.picassoVersion"
    
    	// Retrofit
    	api "com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion"
    	api "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofitVersion"
    	api "com.squareup.retrofit2:converter-gson:$rootProject.retrofitVersion"
    
    	//okhttp
    	api "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttploggingVersion"
    	api "com.squareup.okhttp3:okhttp:$rootProject.okhttpVersion"
    }
    
  • 总结:
    1. 需要在java代码中引用的常量,使用buildConfigField编译进BuildConfig.java
    2. 需要清单引用的,使用manifestPlaceholders
    3. 为全局gradle提供基础环境的变量,在gradle.properities中定义为全局键值对;建议在这里定义整个项目的编译版本、版本号等
    4. 其他的gradle环境变量使用项目的全局build.gradle定义常量;建议在这里管理所有第三方库的版本
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值