Android 编译过程中 添加 Gradle task 任务

最近碰到一个问题,写了一个processor 生成资源文件,希望这个资源文件在编译的时候自动拷贝到到assets 目录,折腾了很久,想想估计是这个问题太简单了,所以没人写,现在写一写自己的成果。

apply plugin: 'com.android.application'

android {
    ...
}

dependencies {
    ...
}

// do some custom actions
project.afterEvaluate {
    tasks.matching {
        it.name.startsWith('compile') && it.name.endsWith('JavaWithJavac')
    }.each { task ->
        task.doFirst{
            ...
        }
        task.doLast {
            ...
        }
    }
}

这里主要是说匹配一个javac 编译任务,可以在增加了 doFist doLast 两个地方,可以自定义一些任务,例如我可能是希望增加拷贝任务,可以在 doLast 之后增加


project.afterEvaluate {
    tasks.matching {
        it.name.startsWith('compile') && it.name.endsWith('JavaWithJavac')
    }.each { task ->
        task.doLast {
            copy {
                from 'build/generated/source/apt/release/'
                into 'src/main/assets/'
            }
        }
    }
}

当然你也可以做一些编译之前的事情, 或者编译之后的事情,例如上传 apk 到什么地方。

project.afterEvaluate {
    preBuild.doFirst {
        ...
    }
    preBuild.doLast {
        ...
    }    
}
Executing tasks: [:app:assembleDebug]
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:checkDebugManifest UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:prepareLintJar UP-TO-DATE
:app:mainApkListPersistenceDebug UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:createDebugCompatibleScreenManifests UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:splitsDiscoveryTaskDebug UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:javaPreCompileDebug
:app:compileDebugJavaWithJavac
:app:compileDebugNdk NO-SOURCE
:app:compileDebugSources
:app:mergeDebugShaders
:app:compileDebugShaders
:app:generateDebugAsset
:app:mergeDebugAssets
:app:transformClassesWithDexBuilderForDebug
:app:transformDexArchiveWithExternalLibsDexMergerForDebug
:app:transformDexArchiveWithDexMergerForDebug
:app:mergeDebugJniLibFolders
:app:transformNativeLibsWithMergeJniLibsForDebug
:app:processDebugJavaRes NO-SOURCE
:app:transformResourcesWithMergeJavaResForDebug
:app:validateSigningDebug
:app:packageDebug
:app:assembleDebug
BUILD SUCCESSFUL in 8s
26 actionable tasks: 13 executed, 13 up-to-date

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容