乐闻世界logo
搜索文章和话题

How to set versionName in APK filename using gradle?

1个答案

1

In Android projects, using Gradle to configure the APK filename is a common practice, particularly for embedding the version name (versionName) and version code (versionCode) into the APK filename, which facilitates easier management and identification of different build versions. The following steps explain how to achieve this.

First, confirm that your project uses Gradle for building. Navigate to your Android project and locate the build.gradle file under the app module. This file manages the application's build configuration.

Within the android block, you can define the version name and version code. For example:

groovy
android { ... defaultConfig { ... versionCode 1 versionName "1.0" } }

Next, to incorporate versionName into the APK filename, configure applicationVariants in the build.gradle file. This enables customization of the APK output filename. Below is an example implementation:

groovy
android { ... // Application build configuration applicationVariants.all { variant -> // Customize output filename variant.outputs.each { output -> def outputFile = output.outputFile if (outputFile != null && outputFile.name.endsWith('.apk')) { // Set new filename def fileName = "${variant.productFlavors[0].name}-${variant.buildType.name}-v${defaultConfig.versionName}.apk" output.outputFile = new File(outputFile.parent, fileName) } } } }

In this example, applicationVariants.all is used to iterate through all build variants (including different flavors and build types), then customize the name of each output APK file. Here, the filename incorporates the flavor name, build type, and versionName in the format flavor-buildType-vversionName.apk.

Be aware that depending on your project's specific configuration, adjustments may be necessary. For instance, if your project does not use product flavors, the code to retrieve the flavor name should be adapted.

By doing this, each generated APK file will include the relevant version information, enabling easier version control and tracking. This is particularly useful when developing and testing multiple versions concurrently.

2024年8月16日 23:38 回复

你的答案