问题
Is there anyway to detect the environment I'm running my project.
Something like this:
build.gradle
def usingIntelliJ = ...
def usingAndroidStudio = ...
if (usingIntelliJ) {
buildConfigField "String", "IDE_ENV", "IDEA"
} else if (usingAndroidStudio) {
buildConfigField "String", "IDE_ENV", "AndroidStudio"
}
回答1:
To determine if your build is triggered by an IDE, the Android build chain will set a specific property:
def isIdeBuild() {
return project.properties['android.injected.invoked.from.ide'] == 'true'
}
In our builds we use this method to set a static versionCode
for our IDE builds, but keep the desired behavior to automatically increase it on our build servers:
def getNumberOfGitCommits() {
def text = 'git rev-list --count HEAD'.execute().text.trim()
return text == '' ? 0 : text.toInteger()
}
def calculateVersionCode() {
return isIdeBuild() ? 123456789 : getNumberOfGitCommits()
}
android {
defaultConfig {
// ...
versionCode calculateVersionCode()
}
}
This solved two problems we had:
- Before, new commits effectively disabled Instant Run. Because the
versionCode
was updated automatically, the Manifest was changed – which triggers a full rebuild in Instant Run. - Before, when we switched Git branches, the
versionCode
often changed to a smaller one (downgrade), so we had to re-install the app. Now we have the same versionCode for all our IDE builds.
回答2:
In build script you can evaluate following properties which IDE adds:
idea.active
property that IDE sets when you run Gradle tasks from IDE;idea.sync.active
property which is added by IDE when IDE reloads project from Gradle build scripts.
For example: System.getProperty('idea.active')
.
来源:https://stackoverflow.com/questions/25324880/detect-ide-environment-with-gradle