Android gradle build config - 重命名生成的APK

时间:2016-10-09 05:54:43

标签: android gradle

每当我建立一个APK时,我需要用特殊名称保存每个APK 这是所需的名称格式:" buildType appName_version_Date_Time.apk"
示例:" 调试myAppName_v1.0_20161009_0854.apk "
示例:" 发布myAppName_v1.0_20161009_0854.apk "

为此,我添加了这个gradle脚本:

 buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release
    }
    debug {

    }
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def formattedDate = new Date().format('yyyyMMdd_HHmm')
            println(output.outputFile)
            def newName = variant.name + " myAppName_v" + defaultConfig.versionName + "_" + formattedDate + ".apk"
            output.outputFile = new File(output.outputFile.parent, newName)
        }
    }

}

此脚本有效,但android studio无法找到重命名的APK。我也尝试了清洁/重建项目,但它再次出现了。

Android stuio错误:
APK文件路径\到\ project \ app \ build \ outputs \ apk \ debug myAppName_v1.0_ [20161009_ 0854 ]。磁盘上不存在apk。 安装APK时出错

当我检查" build \ outputs \ apk"目录我看到已经构建了一个APK,其名称是" myAppName_v1.0_ [20161009_ 0856 ]。apk"。

这里有什么问题?

2 个答案:

答案 0 :(得分:2)

不要在APK文件名中包含当前时间(分钟,不少于),请考虑以下方法:

  • 获取最新版本控制提交的时间戳(保持稳定)
  • 不是更改apk文件名,而是将其从Android Studio很容易找到的非时间戳名称复制到时间戳的apk。

这是一个尝试的例子(没有运行它,但应该给出一般的想法)。选择Files.copy或复制任务,而不是两者。

applicationVariants.all { variant ->
  variant.outputs.each { output ->
    def copyApkTask = tasks.create(name: "copy" + variant.name + "Apk") {
      def newName = ... // can include the timestamp with minutes
      println(newName)

      // Using java.nio.Files.copy
      def targetPath = new File(output.outputFile.parent, newName).toPath()
      Files.copy(output.outputFile.toPath(), targetPath)

      // Using gradle's Copy logic (clunky for single-file copy and rename)
      copy {
        from output.outputFile
        into output.outputFile.parent
        rename { String fileName ->
          newName
        }
      }
    }
    copyApkTask.mustRunAfter variant.assemble
  }
}

答案 1 :(得分:2)

你告诉gradle在apk的名字中包含分钟。

然后在n分钟内使用您想要的名称构建它,当它想在n+1分钟内引用它时,它无法找到该文件。所以它遇到了这个错误。

您最好使用提交哈希或apk名称中的日期。 (不包括像小时或秒钟甚至小时的小单位)