打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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定义常量;建议在这里管理所有第三方库的版本
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
从零开始的Android新项目2
Gradle-构建生命周期
AndroidStudio3.6升级后的坑-apk打包
Eclipse 安装Gradle插件
uboot编译连接脚本文件uboot.lds
深入理解 PHP opcode 优化 – 码农网
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服