Android使用gradle.properties详解(一)
一、Android开发为什么要使用gradle.properties
1、对于项目而言,有时候需要配置某些敏感信息。比如密码、密钥、APP ID、帐号等。而这些信息需要被很多类共同使用,所以必须有一个全局的配置。
2、当需要把项目push到git上时,我们不希望别人看到我们项目的key,token等。我们可以将这些信息设置在gradle.properties中。
二、如何使用gradle.properties
1、在gradle.properties文件中进行变量初始化
# Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. #就是让你让你编译时使用守护进程。 org.gradle.daemon=true #使用并行编译 org.gradle.parallel=true org.gradle.configureondemand=true #JVM最大允许分配的堆内存,按需分配。JVM最大允许分堆非内存512m org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app"s APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true android.enableJetifier=true android.useDeprecatedNdk=true #签名文件路径 storeFile=../xxxxxx.keystore #签名文件密码 storePassword=diyidaima #签名文件别名 keyAlias=diyidaima #签名密码 keyPassword=diyidaima #编译版本号 compileSdkVersion=30 #构建工具版本号 buildToolsVersion=30.0.3 #最小编译版本号 minSdkVersion=21 #目标sdk版本号 targetSdkVersion=30 #友盟APPKey YmAppKey="diyidaima88888888" #友盟渠道号 YmChannelID="diyidaima" #微信APPID WxAppId="diyidaima88888888" #开发环境的地址 API_DEBUG_HOST="https://www.zhiyincv.com/" #正式环境的地址 API_RELEASE_HOST="https://www.diyidaima.com/" #每次发布可能需要修改的值 #版本号 versionCode=1000 #版本名称 versionName=2.0.08 #是否是推广版本(0:推广版本;1:上线审核版本) APP_EXTENSION=1
2、在build.gradle(module app)中进行变量的重定义,即将配置内容转化成java能够使用的形式
plugins {
id 'com.android.application'
}
//返回格式化日期
def releaseTime() {
return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}
//如果是推广版本,则增加后缀
String releaseType() {
boolean hasProperties = project.hasProperty("APP_EXTENSION")
int extension = hasProperties ? Integer.parseInt(project.properties["APP_EXTENSION"]) : 1;
return extension == 0 ? "-extension" : "";
}
android {
compileSdkVersion Integer.parseInt(project.property("compileSdkVersion"))
buildToolsVersion project.property("buildToolsVersion").toString()
defaultConfig {
applicationId "com.diyidaima.com"
minSdkVersion Integer.parseInt(project.property("minSdkVersion"))
targetSdkVersion Integer.parseInt(project.property("targetSdkVersion"))
versionCode Integer.parseInt(project.property("versionCode"))
versionName project.property("versionName").toString()
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
}
}
}
buildTypes {
debug {
minifyEnabled false
//minifyEnabled true // 混淆
//zipAlignEnabled true // Zipalign优化
//shrinkResources true // 移除无用的resource文件
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//buildConfigField定义的方式是:buildConfigField 类型、变量名、值
//调试模式下调用的网址
buildConfigField("String", "API_HOST", "${API_DEBUG_HOST}")
buildConfigField("int", "APP_EXTENSION", "${APP_EXTENSION}")
buildConfigField("String", "YmAppKey", "${YmAppKey}")
buildConfigField("String", "YmChannelID", "${YmChannelID}")
buildConfigField("String", "WxAppId", "${WxAppId}")
//resValue定义的方式是:resValue XML中的类型、变量名、值
resValue "string","YmAppKey", "${YmAppKey}"
resValue "string","YmChannelID", "${YmChannelID}"
resValue "string","WxAppId", "${WxAppId}"
}
release {
//minifyEnabled false
minifyEnabled true // 混淆
zipAlignEnabled true // Zipalign优化
shrinkResources true // 移除无用的resource文件
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
//buildConfigField定义的方式是:buildConfigField 类型、变量名、值
//正式模式下调用的网址
buildConfigField("String", "API_HOST", "${API_RELEASE_HOST}")
buildConfigField("int", "APP_EXTENSION", "${APP_EXTENSION}")
buildConfigField("String", "YmAppKey", "${YmAppKey}")
buildConfigField("String", "YmChannelID", "${YmChannelID}")
buildConfigField("String", "WxAppId", "${WxAppId}")
//resValue定义的方式是:resValue XML中的类型、变量名、值
resValue "string","YmAppKey", "${YmAppKey}"
resValue "string","YmChannelID", "${YmChannelID}"
resValue "string","WxAppId", "${WxAppId}"
}
}
//自定义apk安装包名
applicationVariants.all { variant ->
variant.outputs.all {
//caige-release-版本号-版本名-日期.apk
outputFileName = "caige-${variant.buildType.name}-${variant.versionCode}-${variant.versionName}-${releaseTime()}${releaseType()}.apk".toLowerCase()
}
}
//保证调试版本和正式版本的签名一样
signingConfigs {
debug {
storeFile file(project.properties["storeFile"].toString())
storePassword project.properties["storePassword"].toString()
keyAlias project.properties["keyAlias"].toString()
keyPassword project.properties["keyPassword"].toString()
}
release {
keyAlias project.properties["keyAlias"].toString()
keyPassword project.properties["keyPassword"].toString()
storeFile file(project.properties["storeFile"].toString())
storePassword project.properties["storePassword"].toString()
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main {
assets.srcDirs = ['src/main/assets', 'src/main/assets/']
jni {
srcDirs 'src\\main\\jni'
}
}
}
configurations{
cleanedAnnotations
compile.exclude group: 'org.jetbrains', module:'annotations'
}
}
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar',"*.aar"], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'org.jetbrains:annotations-java5:15.0'
implementation 'androidx.viewpager:viewpager:1.0.0'
implementation 'com.google.code.gson:gson:2.8.7'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
其中有两种定义方式要说明一下:
buildConfigField定义的方式是:buildConfigField 类型、变量名、值
resValue定义的方式是:resValue XML中的类型、变量名、值
3、在Java中使用
使用BuildConfig可以直接读取配置信息:
preInit(context, BuildConfig.YmAppKey, BuildConfig.YmChannelID);
4、在布局文件中使用
通过build.gradle中的配置,可以直接使用@string 访问:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/YmAppKey"
android:background="@drawable/selector_blue_join"
android:textColor="@color/white"
android:textSize="18sp"
android:gravity="center"/>
或者在Java代码中也可以这样访问:
String ymChannelID= getString(R.string.YmChannelID);
使用gradle.properties不仅可以配置全局信息,还能针对debug和release环境自动切换配置。如上面的API_HOST,在debug和release可以使用不同的网站。同理,有些SDK分区分正式和测试环境的Key,我们也可以使用这种方式解决。不用每次编译的时候手动更改。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。



