[Android] 使用 Gradle 建置專案

Android 從 Eclipse 轉移到 Android Studio 後使用 Gradle 來作為 build tool

本篇紀錄一些使用 Gradle 建置專案遇到的問題

Android 官方建議將 Gradle Wrapper 放進 version control

好處是不需要安裝 Gradle, 不同的專案可以有不同版本的 Gradle

最基本的建置只需要執行

./gradlew clean build

如果執行 gradlew clean build 遇到下列的錯誤

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:lint'.
> Lint found errors in the project; aborting build.

Fix the issues identified by lint, or add the following to your build script to proceed with errors:
...
android {
lintOptions {
abortOnError false
}
}
...

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

解決方法

修改 project_path/project_name/app/build.gradle
android {} 關閉 lint 遇到錯誤時中斷建置

app {
compileSdkVersion 23
buildToolsVersion '23.0.0'
... //其他的設定

lintOptions { //加上這個
abortOnError false
}
}

專案沒有 gradlew 的話, 可以執行

如果執行 gradle clean build 失敗, 遇到下列的錯誤

FAILURE: Build failed with an exception.

* Where:
Build file 'project_path/project_name/app/build.gradle' line: 1

* What went wrong:
A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
> Gradle version 2.2 is required. Current version is 2.12. If using the gradle wrapper, try editing the distributionUrl in project_path/project_name/gradle/wrapper/gradle-wrapper.properties to gradle-2.2-all.zip

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

解決方法

修改專案的根目錄中的 build.gradleAndroid Plugin for Gradle 換成較新的版本
 //2016/03/25最新的 Android Plugin for Gradle1.5.0

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}

本篇使用的 Gradle 版本: Gradle 2.12

參考文件:

Android Documentation — Build System Overview