gradle.addBuildListener(new CustomListener(gradle))

class CustomListener implements BuildListener {

    private timings = []
    private File file
    private Gradle gradle

    CustomListener(Gradle gradle) {
        this.gradle = gradle
    }

    @Override
    void settingsEvaluated(Settings settings) {
        log("settingsEvaluated")
    }

    @Override
    void projectsLoaded(Gradle gradle) {
        log("projectsLoaded")

        configDep()
    }

    @Override
    void projectsEvaluated(Gradle gradle) {
        log("projectsEvaluated")
    }

    @Override
    void buildStarted(Gradle gradle) {
        log("buildStarted")

        gradle.addListener(new TaskExecutionListener() {

            @Override
            void beforeExecute(Task task) {
                log("beforeExecute")
                task.ext.startTime = System.currentTimeMillis()
            }

            @Override
            void afterExecute(Task task, TaskState state) {
                log("afterExecute")
                def ms = System.currentTimeMillis() - task.ext.startTime
                timings.add([ms, task.path])
            }
        })

        def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")
        file = new File(rootProject.buildDir.getAbsolutePath(),
                "buildTime_" + sdf.format(new Date(System.currentTimeMillis())) + ".txt")
    }

    @Override
    void buildFinished(BuildResult result) {
        ArrayList<Long> array = new ArrayList()
        for (timing in timings) {
            if (timing[0] >= 100) {
                array.add(timing)
            }
        }
        if (!array.isEmpty()) {
            Collections.sort(array)
            StringBuilder sb = new StringBuilder()
            array.reverseEach {
                sb.append(String.format("%7sms  %s\n", it[0], it[1]))
            }
            def content = sb.toString()
            log(content)
            com.android.utils.FileUtils.writeToFile(file, content)
        }
    }

    /**
     * 根据 depConfig 生成 dep
     */
    private void configDep() {
        gradle.depConfig.each { name, config ->
            if (!config.isApply) return
            if (config.useLocal) {
                if (config.localPath == "") return
                gradle.ext.dep[name] = gradle.rootProject.findProject(config.localPath)
            } else {
                gradle.ext.dep[name] = config.remotePath
            }
        }
        log("dep = " + gradle.ext.Utils.object2String(gradle.ext.dep))
    }

    private void log(Object content) {
        gradle.ext.Utils.log(content)
    }
}