Gradle脚本重命名文件问题

Gradle script rename file problems

我使用下面的代码生成了一个 .apk 文件,它工作正常。 但是,为了能够调试,我需要在 "applicationVariants.all" 周围注释代码,否则 Android Studio 会说找不到文件。

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def apk = output.outputFile;
                    def newName = "app-release-" + getDate() + ".apk";
                    output.outputFile = new File(apk.parentFile, newName);
                }
            }

        }
    }

我怎样才能让它适用于生成 .apk 文件并在 Android Studio 上进行调试?

更新

我发现发生了什么,实际上当我在文件名中使用日期和时间时,生成文件中的时间与 Android Studio 尝试安装的时间不同。

我的函数 getDate() returns 这个:

def getDate() {
    def date = new Date()
    def formattedDate = date.format('yyyyMMddHHmm')
    return formattedDate
}

创建的文件是app-release-201507110957.apk。 但是,在 Android Studio 控制台中,错误是:

Uploading file
    local path: /Volumes/Macintosh HD/AndroidstudioProjects/App/app/build/outputs/apk/app-release-201507110956.apk
    remote path: /data/local/tmp/com.domain.app
Local path doesn't exist.

生成文件的文件名比 Android Studio 尝试安装的文件名提前 1 分钟。 关于如何解决这个问题的任何想法?我想在文件名中包含小时和分钟,因为我可能每天为 QA 团队生成多个版本。

目前重命名是您发布版本的一部分。只需将重命名作为一般操作,如下所示:

android {

  ...

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }

    debug {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

  applicationVariants.all { variant ->
      variant.outputs.each { output ->
      def apk = output.outputFile;
      def newName = "app-release-" + getDate() + ".apk";
      output.outputFile = new File(apk.parentFile, newName);
    }
  }
}

我通过验证变体是否可调试解决了我的问题。

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            applicationVariants.all { variant ->
                if (!variant.buildType.isDebuggable()) {
                    variant.outputs.each { output ->
                        def apk = output.outputFile;
                        def newName = "app-release-" + getDate() + ".apk";
                        output.outputFile = new File(apk.parentFile, newName);
                    }
                }
            }
        }
    }

像这样,我只为发布版本应用我的文件名。可调试的将继续使用 Android Studio 设置的相同名称,因此在调试应用程序时不会产生问题。