LoginSignup
35
25

More than 5 years have passed since last update.

Android Gradle 3.0以上で出力するapkのファイル名を変更する

Posted at

3.0以前の設定方法と3.0以降で発生する問題

これまでGradle上で出力するapkのファイル名を変更するときは、下のような設定を記述していました。

app/build.gradle
android {
    applicationVariants.all { variant ->
        if (variant.buildType.name.equals("release")) {
            // releaseビルドのみ、ファイル名にVesionNameとビルド時間を付与
            variant.outputs.each { output ->
                if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
                    def versionName = variant.versionName
                    def date = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
                    def newName = "apk_v${versionName}_${date}.apk"
                    output.outputFile = new File(output.outputFile.parent, newName)
                }
            }
        }
    }
}

しかしこの設定、Android Gradle 3.0(自分は3.0.0-arpha5にて確認)だと、output.outputFileが読み取り専用のプロパティとなってしまうためエラーが起きてしまいます。

* What went wrong:
A problem occurred configuring project ':app'.
> Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=release, filters=[]}} of type com.android.build.gradle.internal.api.ApkVariantOutputImpl.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED in 0s

解決策

variant.outputs.each ではなく variant.outputs.all とし、outputFileNameに出力したいファイル名を設定することで解決できました。

app/build.gradle
applicationVariants.all { variant ->
    if (variant.buildType.name.equals("release")) {
        // releaseビルドのみ、ファイル名にVesionNameとビルド時間を付与
        variant.outputs.all {
            def versionName = variant.versionName
            def date = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
            def newName = "apk_v${versionName}_${date}.apk"
            outputFileName = newName
        }
    }
}

ただしこの場合だと、apk以外のファイルを出力させている場合は上書きしてしまうかもしれません。よりよい変更方法がありましたらコメントもしくは編集リクエストお待ちいたしております。

参考

Android Gradle 3.0.0-alpha2 plugin, Cannot set the value of read-only property 'outputFile' - Stack Overflow

35
25
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
25