Skip to content

Instantly share code, notes, and snippets.

@ychescale9
Last active June 5, 2024 22:56
Show Gist options
  • Save ychescale9/fffef60e49de36375698997b277fab9d to your computer and use it in GitHub Desktop.
Save ychescale9/fffef60e49de36375698997b277fab9d to your computer and use it in GitHub Desktop.
Customizing APK file name with new AGP variant APIs
android {
onVariantProperties {
val mainOutput = outputs.single { it.outputType == VariantOutputConfiguration.OutputType.SINGLE }
tasks.register<CreateRenamedApk>("createRenamedApkFor${name}") {
this.originalApkFolder.set(artifacts.get(ArtifactType.APK))
this.builtArtifactsLoader.set(artifacts.getBuiltArtifactsLoader())
this.newApkFolder.set(layout.buildDirectory.dir("outputs/renamed_apk/${[email protected]}"))
this.versionCode.set(mainOutput.versionCode)
this.versionName.set(mainOutput.versionName)
}
}
}
abstract class CreateRenamedApk : DefaultTask() {
@get:InputFiles
abstract val originalApkFolder: DirectoryProperty
@get:OutputDirectory
abstract val newApkFolder: DirectoryProperty
@get:Internal
abstract val builtArtifactsLoader: Property<BuiltArtifactsLoader>
@get:Input
abstract val versionCode: Property<Int>
@get:Input
abstract val versionName: Property<String>
@TaskAction
fun taskAction() {
val builtArtifacts = builtArtifactsLoader.get().load(originalApkFolder.get()) ?: throw RuntimeException("Cannot load APKs")
File(builtArtifacts.elements.single().outputFile).copyTo(
File(newApkFolder.asFile.get(), "MyApp-${versionName.get()}-${versionCode.get()}.apk")
)
}
}
@ychescale9
Copy link
Author

New Variant APIs introduced in AGP 4.1+ won't allow renaming APK (e.g. by setting archivesBaseName).

The gist above creates createRenamedApkFor<BuildVariant> tasks, which copies the original APK file with the new path / name app/build/outputs/renamed_apk/<buildVariant>/MyApp-<versionName>-<versionCode>.apk.

For more context see ReactiveCircus/app-versioning#9.

@ychescale9
Copy link
Author

Updated to not do a transform of the APK which always happens when deploying from Studio. Instead we do a simple copy of the APK file.

@koolfreak
Copy link

Any updated solutions? thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment