在Android的实际开发中,一般会有这样的需求,debug和release版本不同,接口地址不同,同时控制日志是否打印等,系统为我们提供了一个很方便的类BuildConfig可以自动判断是否是debug模式。
有了BuildConfig.DEBUG之后,你在代码中可以直接写入
if (BuildConfig.DEBUG) {
Log.d(TAG, "output something");
}
在平时直接运行代码的时候BuildConfig.DEBUG的值自动为true,
在发布后BuildConfig.DEBUG的值自动为false,
可以说是非常方便。
可是as中无论你是debug还是release,model中的DEBUG一直为false(也许是as的bug)
解决方案:1。手动修改modle中的defaultPublishConfig “release”或debug,但是每次运行debug或者release的时候都需要更改一下
2.module中配置
android {
publishNonDefault true
}
app中配置
dependencies {
releaseCompile project(path: ':library', configuration: 'release')
debugCompile project(path: ':library', configuration: 'debug')
}
3、如果module都引用统一的base modlue的话,在basemodule中定义一个静态变量Config.DEBUG,然后再application初始化的时候把app的BuildConfig.DEBUG的值赋值给Config.DEBUG,
4、app中
// Application
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0 alpha"
rootProject.ext.variantRelease = false //default we are in debug mode, will be overriden on task execution
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
debug {
versionNameSuffix ' dev'
}
}
}
dependencies {
// ui
compile 'com.android.support:support-v4:+'
// local jars
compile fileTree(dir: 'libs', include: ['*.jar'])
}
// Trigger build type (as soon as possible) and make some action via corresponding tasks
project.afterEvaluate {
tasks.all { task ->
if (task.name =~ /check.*Manifest/) {
if (task.name =~ /[dD]ebug/) {
task.dependsOn(onDebugTypeTriggered)
} else {
task.dependsOn(onReleaseTypeTriggered)
}
}
}
}
task onDebugTypeTriggered << {
rootProject.ext.variantRelease = false
}
task onReleaseTypeTriggered << {
rootProject.ext.variantRelease = true
}
module中
// Library
apply plugin: 'android-library'
repositories {
mavenCentral()
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
}
// Trigger BuildConfig creation
project.afterEvaluate {
tasks.all { task ->
if (task.name =~ /generate.*BuildConfig/) {
task.dependsOn(propagateBuildConfig)
}
}
}
task propagateBuildConfig << {
project.android.buildTypes.all { type ->
type.buildConfigField "boolean", "RELEASE", isVariantRelease().toString()
}
}
def isVariantRelease() {
return rootProject.ext.variantRelease
}
网友评论