I am trying to extract and use the architecture of the artifact to compose the output file name:
void defineDefaultVariantsAPK(String appName) {
defineVariantsAPK({ variant, output ->
def versionName = variant.versionName
def versionCode = "-(${variant.versionCode}"
def buildLetter = variant.buildType.name == "release" ? "-R" : "-D"
def flavor = variant.productFlavors.size() > 0 ? "-${variant.productFlavors[0].name}" : ""
def architecture = "-" + output.getFilter(com.android.build.OutputFile.ABI)
"v${versionName}${versionCode}${buildLetter}${flavor}${architecture}--${appName}.apk"
})
}
void defineVariantsAPK(Closure nameBuild) {
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.outputFile = new File((String) output.outputFile.parent, nameBuild(variant, output))
}
}
}
}
for some reason many posts says that that is the solution, but my gradle fails on:
> Could not get unknown property 'com' for project ':app' of type org.gradle.api.Project.
I've tried to use import:
unable to resolve class com.android.build.OutputFile
configuration:
com.android.tools.build:gradle:2.3.3
Gradle version 3.5
So I really wonder, what am I doing different that it doesn't work?
Beggining with Gradle 3.0.0 you can do it like this:
applicationVariants.all { variant ->
variant.outputs.all { output ->
def appName = "AppName_"
def buildType = variant.variantData.variantConfiguration.buildType.name
def architecture = output.getFilter(com.android.build.OutputFile.ABI)
def newName
if (buildType == 'debug') {
newName = "${appName}debug_${defaultConfig.versionName}_${architecture}.apk"
} else {
newName = "${appName}release_${defaultConfig.versionName}_${architecture}.apk"
}
outputFileName = newName
}
}
*put this in your module(app) build.gradle file.
This code works for me with gradle 3+ for android
android.applicationVariants.all { variant ->
variant.outputs.all { output ->
def architecture = output.filters[0].identifier
outputFileName = "myapp-${architecture}-${variant.versionName}.apk"
}
}
Where did you define this function? Try to move it you your app/build.gradle file as that is where buildscript is and gradle loads classes from it into classpath.
So following #blazsolar suggestion I've moved the method to the app build gradle file, the move itself was not the solution, when I tried to add the import:
import com.android.build.OutputFile
for some reason the IDE (Android studio) has decided to delete the import..
but once I've this import:
import com.android.build.OutputFile.FilterType
it was just fine!
but that is not the end of it... I want the method to be in a common gradle file, that all my project can reuse.
once I've added the last import to the common gradle file... the import figging disappeared again..
I am left with yet another question
update:
So I've update Android plugin and gradle version to 3.0.1 and 4.1 respectively, and now... things have change.. now there is no
com.android.build.OutputFile.FilterType
Now you need to use:
com.android.build.VariantOutput.ABI
Just in case anyone wonder...
Related
Gradle changed it's behavior when I updated from 5.0 to 5.1.
Lets assume that we have an android project with single module named library.
On Gradle 5.0 (and previous versions) when I executed ./gradlew assembleRelease or ./gradlew assembleDebug generated output was library-release.aar or library-debug.aar respectively.
After I updated to Gradle 5.1 (I also tried 5.1.1) it generates only library.aar for any build type without any build-type classifier in output file name.
So my question is: how can I force Gradle 5.1 to set correct output file naming for different build types like it was before? Below is my library module's build.gradle.kts, but I doesn't think that there is something wrong with it:
import org.jetbrains.kotlin.config.KotlinCompilerVersion
plugins {
id("com.android.library")
id("kotlin-android")
id("maven-publish")
}
val libraryVersion = "1.5.0"
android {
compileSdkVersion(28)
defaultConfig {
minSdkVersion(16)
targetSdkVersion(28)
versionCode = 1
versionName = libraryVersion
}
lintOptions {
isAbortOnError = false
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
}
dependencies {
implementation(fileTree(mapOf("include" to listOf("*.jar"), "dir" to "libs")))
implementation(kotlin("stdlib-jdk7", KotlinCompilerVersion.VERSION))
}
UPDATE:
If I add a following code to build.gradle.kts:
afterEvaluate {
android.libraryVariants.forEach { libraryVariant ->
libraryVariant.outputs.forEach { output ->
println(output.outputFile.name)
}
}
}
It will print:
library-debug.aar
library-release.aar
Now it starts looking like a bug in gradle 5.1
So as we can see in https://github.com/gradle/gradle/issues/8328, it is a bug which is fixed in Android Gradle Plugin 3.4.
libraryVariants.all { variant ->
variant.outputs.all { output ->
def filePrefix = "$buildDir/outputs/aar/$archivesBaseName"
outputFileName = "${archivesBaseName}-${version}.aar"
def fileSuffix = "aar"
def originalFile = file("$filePrefix-${variant.buildType.name}.$fileSuffix")
def renamedFile = "$filePrefix-${variant.buildType.name}-$version.$fileSuffix"
tasks.named("assemble").configure {
doLast {
originalFile.renameTo(renamedFile)
}
}
}
}
where archivesBaseName and version can defined in default block of libraries build.gradle
applicationVariants.all { variant ->
variant.outputs.each { output ->
//noinspection GroovyAssignabilityCheck
output.outputFile = new File(output.outputFile.parent,
output.outputFile.name.replace(".apk", "-${variant.versionName}.apk"))
}
}
Need a clarification about the above code.
Did the only purpose to rename generated .apk file?
Why do I need to add this line //noinspection GroovyAssignabilityCheck ?
Would the above line be cause for run-time crash or any issue ?
What else can I do with applicationVariants.all {} ?
1 Yes, only rename
2 Not sure. outputFile is read-only - this code shouldn't work on newest Gradle
3 No, Gradle doesn't affect to runtime
4 Every Gradle action
Your above code is not working in Android studio 3.2.1.
If want to rename the APK and want to extract proguard mapping file.
applicationVariants.all { variant ->
if (variant.buildType.name == "release") {
def formattedDate = new Date().format('ddMMMyy_HH_mm')
variant.outputs.all { output ->
def formattedName = "${"SampleName" + variant.productFlavors.get(0).name.concat("_")}" +
"${variant.buildType.name[0].toUpperCase().concat("_v")}${variant.versionName.concat("_" + formattedDate)}"
outputFileName = new File("${"v"+variant.versionName.concat("/")}" +formattedName+".apk")
if (variant.getBuildType().isMinifyEnabled()) {
copy {
from variant.mappingFile
into output.outputFile.parent
rename { String fileName ->
formattedName + "_mapping.txt"
}
}
}
}
}
}
Above code will give the apk with /BuildVariant/vVersionName/ SampleName_BuildVariant_BuildType_vVersionName_DDMMMYY_HH_mm.apk and mapping file.
You can also set do all above thing only on release build
In my android library project I used to do this:
android.libraryVariants.all { variant ->
def flavourName = variant.productFlavors.get(0).name
def buildTypeName = variant.buildType.name
def buildVersion = calculateVersion( flavourName, buildTypeName )
variant.mergedFlavor.versionName = buildVersion
}
And this worked fine up until gradle plugin 3.1.3. Now I am trying out 3.2.0-beta04 (as its much much faster when using vanilla cmake) and I am getting this error:
versionName cannot be set on a mergedFlavor directly.
versionNameOverride can instead be set for variant outputs using the following syntax:
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.versionNameOverride = "6.12.0"
}
}
}
OK, I apply the suggestion:
android.libraryVariants.all { variant ->
def flavourName = variant.productFlavors.get(0).name
def buildTypeName = variant.buildType.name
def buildVersion = calculateVersion( flavourName, buildTypeName )
variant.outputs.each { output ->
output.versionNameOverride = buildVersion
}
}
and now I get this error:
Could not set unknown property 'versionNameOverride' for object of type com.android.build.gradle.internal.api.LibraryVariantOutputImpl.
It appears that versionNameOverride property is implemented only for application variants, not for the library variants. Does that mean that support for setting Android AAR version is now deprecated? Or is there another way to achieve that?
EDIT: Note that setting versionName field in defaultConfig section works for my library project - it just does not work setting up programmatically with the method described above.
Try to change variant.productFlavors.get(0).name to def flavor = variant.mergedFlavor, than set name and version code for flavour like that
flavor.versionName = versionName
flavor.versionCode = versionCode
variant.outputs.all { output ->
output.setVersionNameOverride(versionName)
output.setVersionCodeOverride(versionCode)
}
I have this code in my build.gradle to rename de apk but since Android Studio update to version 2.2 is no longer working.
apply plugin: 'com.android.application'
def getDate() {
def date = new Date()
def formattedDate = date.format('yyMMdd')
return formattedDate
}
def gitBranch() {
def branch = ""
def proc = "git rev-parse --abbrev-ref HEAD".execute()
proc.in.eachLine { line -> branch = line }
proc.err.eachLine { line -> println line }
proc.waitFor()
branch
}
android {
// defaultConfig, buildTypes, etc.
android.applicationVariants.all { variant ->
def versionName = variant.versionName.replaceAll('\\.', '_')
def date = getDate()
def versionCode = variant.versionCode
def branch = gitBranch()
variant.outputs.each { output ->
def newApkName
if (output.zipAlign) {
newApkName = "APP${versionName}D${date}VC${versionCode}-${branch}.apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
}
}
I added some println to see if the newApk Name was OK, and I see no problem. Do you ,people , know any alternatives to accomplish this. I will be eternally grateful.
Improves build performance by adopting a new default packaging pipeline which handles zipping, signing, and zipaligning in one task. You can revert to using the older packaging tools by adding android.useOldPackaging=true to yourgradle.properties file. While using the new packaging tool, the zipalignDebug task is not available. However, you can create one yourself by calling the createZipAlignTask(String taskName, File inputFile, File outputFile) method.
From release notes:
https://developer.android.com/studio/releases/gradle-plugin.html#revisions
I have a project with several modules in it one of which is a Android Library named (poorly) as sdk. When I build the project it outputs an AAR named sdk.aar.
I haven't been able to find anything in the Android or Gradle documentation that allows me to change the name of the AAR output. I would like it to have a basename + version number like the Jar tasks do, but I can't work out how to do the same for the AAR because all the config for it seems to be hidden in the android.library plugin.
Renaming the module isn't an option at this stage and that still wouldn't add the version number to the final AAR.
How can I change the name of the AAR generated by com.android.library in Gradle?
Gradle solution
defaultConfig {
minSdkVersion 9
targetSdkVersion 19
versionCode 4
versionName '1.3'
testFunctionalTest true
project.archivesBaseName = "Project name"
project.version = android.defaultConfig.versionName
}
As mentioned in comments below and another answer, the original answer here doesn't work with Gradle 3+. Per the docs, something like the following should work:
Using the Variant API to manipulate variant outputs is broken with the
new plugin. It still works for simple tasks, such as changing the APK
name during build time, as shown below:
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
OLD ANSWER:
I am unable to get archivesBaseName & version to work for me w/ Android Studio 0.8.13 / Gradle 2.1. While I can set archivesBaseName and version in my defaultConfig, it doesn't seem to affect the output name. In the end, adding the following libraryVariants block to my android {} scope finally worked for me:
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${archivesBaseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
For Android Studio 3 with Gradle 4 and Android Plugin for Gradle 3.0.0 you have to change the answer of qix to the following:
android {
...
libraryVariants.all { variant ->
variant.outputs.all { output ->
if (outputFile != null && outputFileName.endsWith('.aar')) {
outputFileName = "${archivesBaseName}-${version}.aar"
}
}
}
}
In my case, ${version} result in "unspecified", finnally I found ${defaultConfig.versionName} works.
android {
...
libraryVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${defaultConfig.versionName}.aar"
}
}
}
with the build-plugin 1.5.0 it is now possible to use archivesBaseName in the defaultConfig
For the latest version of Gradle 5+, this is the best answer following #frouo answer:
defaultConfig {
...
versionName "some-version-name-or-number"
setProperty("archivesBaseName", "${archivesBaseName}-$versionName")
...
}
AAR extension will be added automatically.
In addition to qix answer here the info that you can add multiple output paths by this method by an regular string as well:
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${archivesBaseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
output.outputFile = new File("/home/pepperonas/IdeaProjects/Libraries/Base/testapp/libs", fileName)
}
}
}
(Upvotes belong to qix - I just wrote this as an answer because of the readability).
Using Gradle 6+ and AGP 4+, an alternative answer that allows full control of the name is:
afterEvaluate {
android.libraryVariants.all { variant ->
variant.variantData.outputFactory.apkDataList.each { apkData ->
if (apkData.outputFileName.endsWith('.aar')) {
apkData.outputFileName = "${project.name}-${buildType.name}-anything-you-want.aar"
}
}
}
}
For Gradle 5+:
android.libraryVariants.all { variant ->
variant.variantData.outputFactory.output.apkDatas.each { apkData ->
apkData.outputFileName = "YourNewFileName.aar"
}
}
For Gradle 4+:
android.libraryVariants.all { variant ->
variant.outputs.each { output ->
output.outputFileName = "YourNewFileName.aar"
}
}
For Gradle 2+ and Gradle 3+:
android.libraryVariants.all { variant ->
variant.outputs.each { output ->
output.outputFile = new File(file.parent, "YourNewFileName.aar")
}
}