Android:Gradle计算错误的apk名称

时间:2016-04-19 16:45:46

标签: android android-gradle gradlew android-studio-2.0

我正在使用以下代码重命名我的apk文件:

 applicationVariants.all { variant ->
            android.defaultConfig.versionName = variant.mergedFlavor.versionName;
            renameAPK(variant, defaultConfig)
        }

def renameAPK(variant, defaultConfig) {
    variant.outputs.each { output ->
        def formattedDate = new Date().format('ddMMMyy')
        def applicationName = "Myapp"


        def alignedFile = output.outputFile
        def unalignedFile = output.packageApplication.outputFile

        def fileName = applicationName + "_" + defaultConfig.versionName + "_" + variant.buildType.name + "_" + formattedDate


        //If there's no ZipAlign task it means that our artifact will be unaligned and we need to mark it as such.
        if (variant.buildType.zipAlignEnabled) {
            fileName = fileName + ".apk"
            output.outputFile = new File(alignedFile.parent, fileName)
        }
        fileName = fileName + "-unaligned.apk"
        output.packageApplication.outputFile = new File(unalignedFile.parent, fileName)


    }

在大多数情况下这很好用。但是,偶尔在尝试在设备上安装应用程序时出现错误:

  

Gradle build in 1s 615ms 12:37:04 PM EmptyThrowable:APK   文件./build/outputs/apk/Myapp_4.0_debug_18Apr16.apk不存在   磁盘。

问题是在这种情况下,Gradle使用的日期是错误的。如果我从命令行运行gradle脚本,它会生成一个具有正确日期的apk。

但是,如果我选择"运行"从Android Studio,gradle计算错误的文件名。

我尝试过无效缓存并重新启动Android Studio。此外,清洁项目和重建。没有什么能够100%解决这个问题。

之前还有其他人遇到过这个吗?

2 个答案:

答案 0 :(得分:1)

使用带有时间戳或动态计数器的APK名称效果不佳(取决于更改率),因为Android Studio会在缓存中保留APK名称。 AS运行过时的文件或抱怨没有APK

答案 1 :(得分:0)

转到aap文件夹下的项目目录删除生成的文件并删除apk文件,如果存在构建并再次运行..希望这有帮助