archive_apk.gradle 2.53 KB
android.applicationVariants.all { variant ->
    if (variant.buildType.name != 'release') {
        println("archive apk: current buildType=[${variant.buildType.name}], not release, cancel copy.")
        return
    }
    // 我嫌找起来麻烦才写的这个东西,所以直接放到下载文件里, /Users/key/Downloads/kyxq_archive
    File desFilePath = new File("${System.properties['user.home']}/Downloads/wow_archive")
    if (!desFilePath.exists()) {
        println("archive apk: you are not Key, return.")
        return
    }
    // 简化版可以:variant.assemble.doLast
    /*variant.assemble.doLast {
        println("archive apk: ${variant.outputs[0].outputFile.absolutePath} copy to: ${desFilePath.absolutePath}, exists=${desFilePath.exists()}")
        try {
            copy {
                from variant.outputs[0].outputFile
                into desFilePath
            }
        } catch (Exception e) {
            e.printStackTrace()
        }
    }*/

    variant.assembleProvider.configure {
        doLast {
            variant.outputs.all {
                println("archive apk: copy from ${outputFile}")
                println("archive apk: copy to ${desFilePath.absolutePath}/${outputFileName}")
                try {
                    // 删除同一分钟的编译文件
                    File desFile = new File(desFilePath, outputFileName)
                    if (desFile.exists()) {
                        boolean delete = desFile.delete()
                        println("archive apk: the same name File: ${desFile.name} has been deleted(${delete}).")
                    }
                    int keepCount = 5
                    File[] files = desFilePath.listFiles()
                    if (files.length >= keepCount) {
                        // 按最后修改时间排序,升序(最旧的文件在前)
                        files = files.sort { it.lastModified() }
                        files.take(files.length - keepCount + 1).each {
                            boolean delete = it.delete()
                            println("archive apk: old File: ${it.name} has been deleted(${delete}).")
                        }
                    }
                    File destFile = new File(desFilePath, outputFileName)
                    boolean moved = outputFile.renameTo(destFile)
                    println("archive apk: current archive count=${desFilePath.listFiles().length}. moved=${moved}")
                } catch (Exception e) {
                    e.printStackTrace()
                }
            }
        }
    }
}