Android Gradle学习(三)- 生命周期与构建过程

784 阅读6分钟

1. gradle生命周期

生命周期分为三个阶段

  • Initialization初始化阶段:各工程初始化,解析settings.gradle,构建project对象
  • Configuration配置阶段:执行所有build.gradle的配置代码,解析所有project对象中的task,构建task的有向无环图。
  • Execution执行阶段: 执行task

2. ProjectTask构建流程

API文档:public interface Gradle

方法名说明
beforeSettings在setting.gradle 被加载和解析之前调用
settingsEvaluated在settings.gradle被加载和解析时调用
projectsLoaded当settings.gradle包含的项目的project实例都被创建但是还未被解析时调用
beforeProject当每一个Project实例被解析之前调用,注意是解析,这时Project已经被创建了
afterProject当每一个Project实例被解析之后调用,注意是解析,这时Project已经被创建了
projectsEvaluated当所有的Project实例都被解析后调用
buildStarted当构建开始前调用
buildFinished当构建结束后调用
whenReady当Tasks关系依赖图创建成功时
beforeTask当Task执行前调用
afterTask当Task执行后调用

执行顺序如下:

image.png

/**  
* 配置阶段开始前的监听回调  
*/  
this.beforeEvaluate {  
    println '配置阶段执行前'  
}  
  
/**  
* 配置阶段后的监听回调  
*/  
this.afterEvaluate {  
    println '配置阶段执行后'  
}  
  
/**  
* gradle执行完毕后的回调  
*/  
this.gradle.buildFinished {  
    println '执行阶段完成后'  
}  
  
  
//等同于 beforeEvaluate  
this.gradle.beforeProject {  
  
}  
  
//等同于 afterEvaluate  
this.gradle.afterProject {  
    println '配置阶段执行完毕'  
}

2. 任务列表

// 查看任务
./gradlew tasks

// 查看所有任务
./gradlew tasks --all

任务列表如下:

Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for the base and test modules
sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
assemble - Assemble main outputs for all the variants.
assembleAndroidTest - Assembles all the Test applications.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
bundle - Assemble bundles for all the variants.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Cleanup tasks
-------------
lintFix - Runs lint on all variants and applies any safe suggestions to the source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'Demo2'.
dependencies - Displays all dependencies declared in root project 'Demo2'.
dependencyInsight - Displays the insight into a specific dependency in root project 'Demo2'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains. [incubating]
outgoingVariants - Displays the outgoing variants of root project 'Demo2'.
projects - Displays the sub-projects of root project 'Demo2'.
properties - Displays the properties of root project 'Demo2'.
tasks - Displays the tasks runnable from root project 'Demo2' (some of the displayed tasks may belong to subprojects).
taskTree - Prints task dependency tree.

Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
installRelease - Installs the Release build.
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
lintVitalRelease - Runs lint on just the fatal issues in the release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.

3. assembleDebug任务构建过程

./gradlew assembleDebug运行后打印任务如下:

Executing tasks: [:app:assembleDebug, :app:assembleDebugUnitTest, :app:assembleDebugAndroidTest] in project E:\git\Demo2

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:checkDebugManifest
> Task :app:generateDebugBuildConfig
> Task :app:mainApkListPersistenceDebug
> Task :app:generateDebugResValues
> Task :app:generateDebugResources
> Task :app:javaPreCompileDebug
> Task :app:createDebugCompatibleScreenManifests
> Task :app:processDebugManifest
> Task :app:mergeDebugShaders
> Task :app:compileDebugShaders
> Task :app:generateDebugAssets
> Task :app:mergeDebugAssets
> Task :app:processDebugJavaRes NO-SOURCE
> Task :app:checkDebugDuplicateClasses
> Task :app:mergeDebugResources
> Task :app:processDebugResources
> Task :app:mergeExtDexDebug
> Task :app:compileDebugJavaWithJavac
> Task :app:compileDebugSources
> Task :app:mergeLibDexDebug
> Task :app:transformClassesWithDexBuilderForDebug
> Task :app:mergeDebugJavaResource
> Task :app:validateSigningDebug
> Task :app:signingConfigWriterDebug
> Task :app:mergeProjectDexDebug
> Task :app:mergeDebugJniLibFolders
> Task :app:preDebugUnitTestBuild UP-TO-DATE
> Task :app:javaPreCompileDebugUnitTest
> Task :app:compileDebugUnitTestJavaWithJavac NO-SOURCE
> Task :app:processDebugUnitTestJavaRes NO-SOURCE
> Task :app:compileDebugUnitTestSources UP-TO-DATE
> Task :app:assembleDebugUnitTest UP-TO-DATE
> Task :app:bundleDebugClasses
> Task :app:preDebugAndroidTestBuild SKIPPED
> Task :app:compileDebugAndroidTestAidl NO-SOURCE
> Task :app:processDebugAndroidTestManifest
> Task :app:compileDebugAndroidTestRenderscript NO-SOURCE
> Task :app:generateDebugAndroidTestBuildConfig
> Task :app:javaPreCompileDebugAndroidTest
> Task :app:mainApkListPersistenceDebugAndroidTest
> Task :app:generateDebugAndroidTestResValues
> Task :app:generateDebugAndroidTestResources
> Task :app:mergeDebugAndroidTestResources
> Task :app:processDebugAndroidTestResources
> Task :app:compileDebugAndroidTestJavaWithJavac
> Task :app:compileDebugAndroidTestSources
> Task :app:mergeDebugNativeLibs
> Task :app:stripDebugDebugSymbols
> Task :app:packageDebug
> Task :app:assembleDebug
> Task :app:mergeDebugAndroidTestShaders
> Task :app:compileDebugAndroidTestShaders
> Task :app:generateDebugAndroidTestAssets
> Task :app:mergeDebugAndroidTestAssets
> Task :app:processDebugAndroidTestJavaRes NO-SOURCE
> Task :app:mergeDebugAndroidTestJniLibFolders
> Task :app:mergeDebugAndroidTestJavaResource
> Task :app:checkDebugAndroidTestDuplicateClasses
> Task :app:mergeExtDexDebugAndroidTest
> Task :app:mergeLibDexDebugAndroidTest
> Task :app:transformClassesWithDexBuilderForDebugAndroidTest
> Task :app:mergeDebugAndroidTestNativeLibs
> Task :app:validateSigningDebugAndroidTest
> Task :app:signingConfigWriterDebugAndroidTest
> Task :app:mergeProjectDexDebugAndroidTest
> Task :app:packageDebugAndroidTest
> Task :app:assembleDebugAndroidTest

BUILD SUCCESSFUL in 50s
49 actionable tasks: 49 executed

3.1 查看任务关系树

可以使用插件来查看任务关系树,在项目级build.gradle中加入插件依赖

task-tree : github.com/dorongold/g…

task-tree版本和gradle版本对应关系:

task-treegradle
1.5(下载失败)2.3 - 6.7.1
3.0.06.8 - 7.5.1
4.0.08.0+
buildscript { 
    repositories { 
        maven { 
            url "https://plugins.gradle.org/m2/" 
        }
    } 
    dependencies {
        classpath "com.dorongold.plugins:task-tree:3.0.0" 
    } 
} 

apply plugin: "com.dorongold.task-tree"

执行任务查看任务依赖树

./gradlew build taskTree

运行结果:

:app:build
+--- :app:assemble
|    +--- :app:assembleDebug
|    |    +--- :app:compileDebugSources
|    |    |    \--- :app:compileDebugJavaWithJavac
|    |    |         +--- :app:compileDebugAidl
|    |    |         |    \--- :app:preDebugBuild
|    |    |         |         \--- :app:preBuild
|    |    |         +--- :app:compileDebugRenderscript
|    |    |         |    \--- :app:preDebugBuild *
|    |    |         +--- :app:generateDebugBuildConfig
|    |    |         |    \--- :app:preDebugBuild *
|    |    |         +--- :app:javaPreCompileDebug
|    |    |         |    \--- :app:preDebugBuild *
|    |    |         +--- :app:preDebugBuild *
|    |    |         \--- :app:processDebugResources
|    |    |              +--- :app:checkDebugAarMetadata
|    |    |              |    \--- :app:preDebugBuild *
|    |    |              +--- :app:mergeDebugResources
|    |    |              |    +--- :app:generateDebugResources
|    |    |              |    |    +--- :app:compileDebugRenderscript *
|    |    |              |    |    \--- :app:generateDebugResValues
|    |    |              |    |         \--- :app:preDebugBuild *
|    |    |              |    \--- :app:preDebugBuild *
|    |    |              +--- :app:preDebugBuild *
|    |    |              +--- :app:processDebugManifest
|    |    |              |    +--- :app:createDebugCompatibleScreenManifests
|    |    |              |    |    \--- :app:preDebugBuild *
|    |    |              |    +--- :app:preDebugBuild *
|    |    |              |    \--- :app:processDebugMainManifest
|    |    |              |         +--- :app:extractDeepLinksDebug
|    |    |              |         |    \--- :app:preDebugBuild *
|    |    |              |         \--- :app:preDebugBuild *
|    |    |              \--- :app:processDebugManifestForPackage
|    |    |                   +--- :app:preDebugBuild *
|    |    |                   \--- :app:processDebugManifest *
|    |    +--- :app:mergeDebugNativeDebugMetadata
|    |    |    \--- :app:preDebugBuild *
|    |    \--- :app:packageDebug
|    |         +--- :app:compileDebugJavaWithJavac *
|    |         +--- :app:compressDebugAssets
|    |         |    +--- :app:mergeDebugAssets
|    |         |    |    +--- :app:compileDebugShaders
|    |         |    |    |    +--- :app:mergeDebugShaders
|    |         |    |    |    |    \--- :app:preDebugBuild *
|    |         |    |    |    \--- :app:preDebugBuild *
|    |         |    |    +--- :app:generateDebugAssets
|    |         |    |    |    \--- :app:compileDebugShaders *
|    |         |    |    \--- :app:preDebugBuild *
|    |         |    \--- :app:preDebugBuild *
|    |         +--- :app:mergeDebugAssets *
|    |         +--- :app:mergeDebugJavaResource
|    |         |    +--- :app:preDebugBuild *
|    |         |    \--- :app:processDebugJavaRes
|    |         |         \--- :app:preDebugBuild *
|    |         +--- :app:mergeExtDexDebug
|    |         |    +--- :app:checkDebugDuplicateClasses
|    |         |    |    \--- :app:preDebugBuild *
|    |         |    \--- :app:preDebugBuild *
|    |         +--- :app:mergeLibDexDebug
|    |         |    +--- :app:checkDebugDuplicateClasses *
|    |         |    \--- :app:preDebugBuild *
|    |         +--- :app:mergeProjectDexDebug
|    |         |    +--- :app:checkDebugDuplicateClasses *
|    |         |    +--- :app:dexBuilderDebug
|    |         |    |    +--- :app:compileDebugJavaWithJavac *
|    |         |    |    +--- :app:preDebugBuild *
|    |         |    |    \--- :app:processDebugResources *
|    |         |    \--- :app:preDebugBuild *
|    |         +--- :app:preDebugBuild *
|    |         +--- :app:processDebugManifestForPackage *
|    |         +--- :app:processDebugResources *
|    |         +--- :app:stripDebugDebugSymbols
|    |         |    +--- :app:mergeDebugNativeLibs
|    |         |    |    +--- :app:mergeDebugJniLibFolders
|    |         |    |    |    \--- :app:preDebugBuild *
|    |         |    |    \--- :app:preDebugBuild *
|    |         |    \--- :app:preDebugBuild *
|    |         \--- :app:validateSigningDebug
|    |              \--- :app:preDebugBuild *
|    \--- :app:assembleRelease
|         +--- :app:compileReleaseSources
|         |    \--- :app:compileReleaseJavaWithJavac
|         |         +--- :app:compileReleaseAidl
|         |         |    \--- :app:preReleaseBuild
|         |         |         +--- :app:extractProguardFiles
|         |         |         |    \--- :app:preBuild *
|         |         |         \--- :app:preBuild *
|         |         +--- :app:compileReleaseRenderscript
|         |         |    \--- :app:preReleaseBuild *
|         |         +--- :app:generateReleaseBuildConfig
|         |         |    \--- :app:preReleaseBuild *
|         |         +--- :app:javaPreCompileRelease
|         |         |    \--- :app:preReleaseBuild *
|         |         +--- :app:preReleaseBuild *
|         |         \--- :app:processReleaseResources
|         |              +--- :app:checkReleaseAarMetadata
|         |              |    \--- :app:preReleaseBuild *
|         |              +--- :app:mergeReleaseResources
|         |              |    +--- :app:generateReleaseResources
|         |              |    |    +--- :app:compileReleaseRenderscript *
|         |              |    |    \--- :app:generateReleaseResValues
|         |              |    |         \--- :app:preReleaseBuild *
|         |              |    \--- :app:preReleaseBuild *
|         |              +--- :app:preReleaseBuild *
|         |              +--- :app:processReleaseManifest
|         |              |    +--- :app:createReleaseCompatibleScreenManifests
|         |              |    |    \--- :app:preReleaseBuild *
|         |              |    +--- :app:preReleaseBuild *
|         |              |    \--- :app:processReleaseMainManifest
|         |              |         +--- :app:extractDeepLinksRelease
|         |              |         |    \--- :app:preReleaseBuild *
|         |              |         \--- :app:preReleaseBuild *
|         |              \--- :app:processReleaseManifestForPackage
|         |                   +--- :app:preReleaseBuild *
|         |                   \--- :app:processReleaseManifest *
|         +--- :app:lintVitalRelease
|         |    +--- :app:compileReleaseJavaWithJavac *
|         |    +--- :app:processReleaseMainManifest *
|         |    +--- :app:processReleaseManifestForPackage *
|         |    \--- :app:processReleaseResources *
|         +--- :app:mergeReleaseNativeDebugMetadata
|         |    \--- :app:preReleaseBuild *
|         \--- :app:packageRelease
|              +--- :app:compileReleaseJavaWithJavac *
|              +--- :app:compressReleaseAssets
|              |    +--- :app:mergeReleaseAssets
|              |    |    +--- :app:compileReleaseShaders
|              |    |    |    +--- :app:mergeReleaseShaders
|              |    |    |    |    \--- :app:preReleaseBuild *
|              |    |    |    \--- :app:preReleaseBuild *
|              |    |    +--- :app:generateReleaseAssets
|              |    |    |    \--- :app:compileReleaseShaders *
|              |    |    \--- :app:preReleaseBuild *
|              |    \--- :app:preReleaseBuild *
|              +--- :app:mergeReleaseAssets *
|              +--- :app:minifyReleaseWithR8
|              |    +--- :app:checkReleaseDuplicateClasses
|              |    |    \--- :app:preReleaseBuild *
|              |    +--- :app:compileReleaseJavaWithJavac *
|              |    +--- :app:mergeReleaseGeneratedProguardFiles
|              |    |    +--- :app:compileReleaseJavaWithJavac *
|              |    |    +--- :app:preReleaseBuild *
|              |    |    \--- :app:processReleaseResources *
|              |    +--- :app:mergeReleaseJavaResource
|              |    |    +--- :app:preReleaseBuild *
|              |    |    \--- :app:processReleaseJavaRes
|              |    |         \--- :app:preReleaseBuild *
|              |    +--- :app:preReleaseBuild *
|              |    \--- :app:processReleaseResources *
|              +--- :app:preReleaseBuild *
|              +--- :app:processReleaseManifestForPackage *
|              +--- :app:processReleaseResources *
|              +--- :app:sdkReleaseDependencyData
|              |    +--- :app:collectReleaseDependencies
|              |    |    \--- :app:preReleaseBuild *
|              |    \--- :app:preReleaseBuild *
|              +--- :app:stripReleaseDebugSymbols
|              |    +--- :app:mergeReleaseNativeLibs
|              |    |    +--- :app:mergeReleaseJniLibFolders
|              |    |    |    \--- :app:preReleaseBuild *
|              |    |    \--- :app:preReleaseBuild *
|              |    \--- :app:preReleaseBuild *
|              \--- :app:validateSigningRelease
|                   \--- :app:preReleaseBuild *
\--- :app:check
     +--- :app:lint
     |    +--- :app:compileDebugJavaWithJavac *
     |    +--- :app:compileReleaseJavaWithJavac *
     |    +--- :app:processDebugMainManifest *
     |    +--- :app:processDebugManifestForPackage *
     |    +--- :app:processDebugResources *
     |    +--- :app:processReleaseMainManifest *
     |    +--- :app:processReleaseManifestForPackage *
     |    \--- :app:processReleaseResources *
     \--- :app:test
          +--- :app:testDebugUnitTest
          |    +--- :app:bundleDebugClasses
          |    |    +--- :app:compileDebugJavaWithJavac *
          |    |    +--- :app:preDebugBuild *
          |    |    \--- :app:processDebugResources *
          |    +--- :app:compileDebugUnitTestJavaWithJavac
          |    |    +--- :app:bundleDebugClasses *
          |    |    +--- :app:javaPreCompileDebugUnitTest
          |    |    |    \--- :app:preDebugUnitTestBuild
          |    |    |         \--- :app:preBuild *
          |    |    +--- :app:preDebugUnitTestBuild *
          |    |    \--- :app:processDebugResources *
          |    +--- :app:preDebugUnitTestBuild *
          |    +--- :app:processDebugJavaRes *
          |    +--- :app:processDebugResources *
          |    \--- :app:processDebugUnitTestJavaRes
          |         \--- :app:preDebugUnitTestBuild *
          \--- :app:testReleaseUnitTest
               +--- :app:bundleReleaseClasses
               |    +--- :app:compileReleaseJavaWithJavac *
               |    +--- :app:preReleaseBuild *
               |    \--- :app:processReleaseResources *
               +--- :app:compileReleaseUnitTestJavaWithJavac
               |    +--- :app:bundleReleaseClasses *
               |    +--- :app:javaPreCompileReleaseUnitTest
               |    |    \--- :app:preReleaseUnitTestBuild
               |    |         +--- :app:extractProguardFiles *
               |    |         \--- :app:preBuild *
               |    +--- :app:preReleaseUnitTestBuild *
               |    \--- :app:processReleaseResources *
               +--- :app:preReleaseUnitTestBuild *
               +--- :app:processReleaseJavaRes *
               +--- :app:processReleaseResources *
               \--- :app:processReleaseUnitTestJavaRes
                    \--- :app:preReleaseUnitTestBuild *

4. 插入自定义任务

build.gradle加入自定义任务cleanCache,可以在项目clean时自动清理一些编译期间生成的数据

task cleanCache {  
    doLast {
        // delete files
        println "cleanCache"  
    }  
}  
  
afterEvaluate {  
    clean.dependsOn cleanCache  
}

执行任务查看任务依赖树

./gradlew clean taskTree

结果如下:

:app:clean
\--- :app:cleanCache

clean任务依赖cleanCache,在执行clean时,会先执行cleanCache

Executing tasks: [clean] in project E:\git\Demo2


> Configure project :app
config.gradle load start

> Task :app:cleanCache
cleanCache

> Task :app:clean UP-TO-DATE

BUILD SUCCESSFUL in 465ms
2 actionable tasks: 1 executed, 1 up-to-date

5. 修改打包apk名称

默认打包产物名称是app-debug.apk,没有任何标记,希望文件名包含打包分支、版本号、git号和打包时间等等信息,此时可以通过gradle来自动修改

android {
    // ...
    
    flavorDimensions "market"  
  
    productFlavors {  
        xiaomi {  
            dimension "market"  
        }  

        huawei {  
            dimension "market"  
        }  
    }
    
    // 修改编译产物的输出名称  
    applicationVariants.all { variant ->  
        variant.outputs.all { output ->  

            // 这里可以使用variant.buildType.name来获取构建类型名称  
            def outputFile = output.outputFile  
            // 新的apk名称格式:app-type-build.apk  
            def branchName = getGitBranchName()  
            def gitSha = getGitSHA()  
            def curTime = getCurTime()  
            def channelName = variant.productFlavors[0].name // 渠道名称  
            def buildTypeName = variant.buildType.name  
            // newname = app_master_3b4a04ab_huawei_debug_202406291440.apk
            def newName = "${project.name}_${branchName}_${gitSha}_${channelName}_${buildTypeName}_${curTime}.apk"  

            println("newName=" + newName)  
            // 重命名apk文件  
            outputFileName = newName  
        }  
    }
}

static def getCurTime() {  
    return new Date().format("yyyyMMddHHmm", TimeZone.getTimeZone("GMT+08:00"))  
}  
  
static def getGitBranchName() {  
    return 'git symbolic-ref --short -q HEAD'.execute().text.trim()  
}  
  
static def getGitSHA() {  
    // return 'git rev-parse --short HEAD'.execute().text.trim() // 只有七位
    return 'git rev-parse HEAD'.execute().text.trim().substring(0,8)  
}

参考:Gradle系列学习:Gradle的简介、常用命令和生命周期Gradle总结-生命周期