programing

그래들을 사용하여 APK 파일 이름에서 versionName을 설정하는 방법은 무엇입니까?

goodsources 2023. 8. 24. 22:00
반응형

그래들을 사용하여 APK 파일 이름에서 versionName을 설정하는 방법은 무엇입니까?

Gradle 자동 생성 APK 파일 이름에 특정 버전 번호를 설정하려고 합니다.

은 제이 gradle생 성합니다이를 생성합니다.myapp-release.apk하지만 저는 그것이 뭔가처럼 보이기를 원합니다.myapp-release-1.0.apk.

지저분하게 보이는 옵션의 이름을 변경해 보았습니다.이것을 하는 간단한 방법이 있습니까?

buildTypes {
    release {
       signingConfig signingConfigs.release
       applicationVariants.each { variant ->
       def file = variant.outputFile
       variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" +    defaultConfig.versionName + ".apk"))
    }
}

저는 위의 코드를 시도했지만 실패했습니다.좋은 의견이라도 있나?(그라들 1.6 사용)

버전 이름을 한 곳에서만 변경하면 됩니다.코드도 간단합니다.

아래 예제에서는 MyCompany-MyAppName-1.4.8-debug라는 이름의 pk 파일을 생성합니다.ppk 또는 MyCompany-MyAppName-1.4.8-release를 선택합니다.선택한 빌드 변형에 따라 pk.

솔루션은 APKApp 번들(.aab 파일) 모두에서 작동합니다.

참고 항목:Android 프로젝트의 보호자 매핑 파일 이름을 Gradle로 변경하는 방법

#최근의 Gradle 플러그인을 위한 솔루션

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 14       // increment with every release
        versionName '1.4.8'   // change with every release
        setProperty("archivesBaseName", "MyCompany-MyAppName-$versionName")
    }
}

위 솔루션은 다음 Android Gradle 플러그인 버전에서 테스트되었습니다.

  • 3.6.4 (2020년 8월)
  • 3.5.2 (2019년 11월)
  • 3.3.0(2019년 1월)
  • 3.1.0 (2018년 3월)
  • 3.0.1 (2017년 11월)
  • 3.0.0(2017년 10월)
  • 2.3.2 (2017년 5월)
  • 2.3.1 (2017년 4월)
  • 2.3.0 (2017년 2월)
  • 2.2.3 (2016년 12월)
  • 2.2.2
  • 2.2.0(2016년 9월)
  • 2.1.3 (2016년 8월)
  • 2.1.2
  • 2.0.0(2016년 4월)
  • 1.5.0 (2015/11/12)
  • 1.4.0-12006(2015/10/05)
  • 1.3.1 (2015/08/11)

새로운 버전이 나오면 이 게시물을 업데이트하겠습니다.

#솔루션 테스트 버전 1.1.3-1.3.0 다음 솔루션은 다음 Android Gradle 플러그인 버전에서 테스트되었습니다.

  • 1.3.0 (2015/07/30) - 작동하지 않음, 1.3.1에서 버그 수정 예정
  • 1.2.3 (2015/07/21)
  • 1.2.2 (2015/04/28)
  • 1.2.1 (2015/04/27)
  • 1.2.0 (2015/04/26)
  • 1.2.0-1971(2015/03/25)
  • 1.1.3 (2015/03/06)

앱 그라들 파일:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 14       // increment with every release
        versionName '1.4.8'   // change with every release
        archivesBaseName = "MyCompany-MyAppName-$versionName"
    }
}

은 제했습니다: 이를통문제해: 사용해를 사용하는 것.applicationVariants.allapplicationVariants.each

buildTypes {
      release {
        signingConfig signingConfigs.release
        applicationVariants.all { variant ->
            def file = variant.outputFile
            variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" + defaultConfig.versionName + ".apk")) 
        }
    }       
}

업데이트:

그래서 이것은 0.14 이상 버전의 안드로이드 스튜디오 그래들 플러그인에서는 작동하지 않는 것 같습니다.

이렇게 하면 요령이 생깁니다(이 질문의 참조).

android {
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.outputFile = new File(
                    output.outputFile.parent,
                    output.outputFile.name.replace(".apk", "-${variant.versionName}.apk"))
        }
    }
}

(Android Studio 3.0 및 Gradle 4와 함께 작업하도록 편집됨)

저는 더 복잡한 apk 파일 이름 변경 옵션을 찾고 있었고 다른 사람들에게 도움이 되기를 바라는 마음에서 이것을 썼습니다.다음 데이터로 apk 이름을 변경합니다.

  • 빌드 유형
  • 버전
  • 날짜.

저는 화려한 수업에서 약간의 연구와 다른 답변에서 약간의 복사/붙여넣기를 했습니다.나는 Gradle 3.1.3을 사용합니다.

build.gradle에서:

android {

    ...

    buildTypes {
        release {
            minifyEnabled true
            ...
        }
        debug {
            minifyEnabled false
        }
    }

    productFlavors {
        prod {
            applicationId "com.feraguiba.myproject"
            versionCode 3
            versionName "1.2.0"
        }
        dev {
            applicationId "com.feraguiba.myproject.dev"
            versionCode 15
            versionName "1.3.6"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def project = "myProject"
            def SEP = "_"
            def flavor = variant.productFlavors[0].name
            def buildType = variant.variantData.variantConfiguration.buildType.name
            def version = variant.versionName
            def date = new Date();
            def formattedDate = date.format('ddMMyy_HHmm')

            def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"

            outputFileName = new File(newApkName)
        }
    }
}

오늘(13-10-2016) 10:47에 컴파일하면 선택한 버전 및 빌드 유형에 따라 다음과 같은 파일 이름을 얻을 수 있습니다.

  • dev debug: myProject_dev_debug_1.3.6_131016_1047.apk
  • dev release: myProject_dev_release_1.3.6_131016_1047.apk
  • prod debug : myProject_prod_debug_1.2.0_131016_1047.apk
  • prod release: myProject_prod_release_1.2.0_131016_1047.apk

참고: 정렬되지 않은 버전의 apk 이름은 여전히 기본 이름입니다.

요약하자면, 패키지를 가져오는 방법을 모르는 사람들을 위해build.gradle(나처럼), 다음을 사용합니다.buildTypes,

buildTypes {
      release {
        signingConfig signingConfigs.release
        applicationVariants.all { variant ->
            def file = variant.outputFile
            def manifestParser = new com.android.builder.core.DefaultManifestParser()
            variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" + manifestParser.getVersionName(android.sourceSets.main.manifest.srcFile) + ".apk")) 
        }
    }       
}

편집 =====

이 당신의 정할우를 한다면.versionCode그리고.versionName의 신의에build.gradle: 다과같은파일:

defaultConfig {
    minSdkVersion 15
    targetSdkVersion 19
    versionCode 1
    versionName "1.0.0"
}

다음과 같이 설정해야 합니다.

buildTypes {   
        release {
            signingConfig signingConfigs.releaseConfig
            applicationVariants.all { variant ->
                def file = variant.outputFile
                variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" + defaultConfig.versionName + ".apk"))
            }
        }
}


1 Momentus Studio 1.0으로 ======

Android Studio 1.0을 사용하는 경우 다음과 같은 오류가 표시됩니다.

Error:(78, 0) Could not find property 'outputFile' on com.android.build.gradle.internal.api.ApplicationVariantImpl_Decorated@67e7625f.

은 변해야합다니경▁the▁change를 바꿔야 합니다.build.Types부분적으로:

buildTypes {
        release {
            signingConfig signingConfigs.releaseConfig
            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(".apk", "-" + defaultConfig.versionName + ".apk"))
                }
            }
        }
    }

지정하지 defaultConfig versionName이 됩니다.defaultConfig.versionName으로 결적으로가 될 입니다.null

매니페스트에서 versionName을(를) 가져오려면 build.gradle에 다음 코드를 쓸 수 있습니다.

import com.android.builder.DefaultManifestParser

def manifestParser = new DefaultManifestParser()
println manifestParser.getVersionName(android.sourceSets.main.manifest.srcFile)

그라들 6+

현재 Android Studio 4.0 및 Gradle 6.4에서 다음을 사용하고 있습니다.

android {
    defaultConfig {
        applicationId "com.mycompany.myapplication"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 15
        versionName "2.1.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = "ApplicationName-${variant.name}-${variant.versionName}.apk"
                }
            }
        }
    }
}

그라들 4

4 ( 3 4 (Android Studio 3+)에서 되었습니다.output.outputFileoutputFileName 대답의 아이디어는 다음과 같습니다.

android {
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def newName = outputFileName
            newName.replace(".apk", "-${variant.versionName}.apk")
            outputFileName = new File(newName)
        }
    }
}

저의 경우, 저는 단지 다양한 데이터 생성을 자동화하는 방법을 찾고 싶었습니다.apkrelease그리고.debugㅠㅠㅠㅠㅠㅠㅠㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜandroid:

applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def appName = "My_nice_name_"
        def buildType = variant.variantData.variantConfiguration.buildType.name
        def newName
        if (buildType == 'debug'){
            newName = "${appName}${defaultConfig.versionName}_dbg.apk"
        } else {
            newName = "${appName}${defaultConfig.versionName}_prd.apk"
        }
        output.outputFile = new File(output.outputFile.parent, newName)
    }
}

새로운 Android Gradle 플러그인 3.0.0의 경우 다음과 같은 작업을 수행할 수 있습니다.

 applicationVariants.all { variant ->
    variant.outputs.all {
        def appName = "My_nice_name_"
        def buildType = variant.variantData.variantConfiguration.buildType.name
        def newName
        if (buildType == 'debug'){
            newName = "${appName}${defaultConfig.versionName}_dbg.apk"
        } else {
            newName = "${appName}${defaultConfig.versionName}_prd.apk"
        }
        outputFileName = newName
    }
}

은 다음과 같은.My_nice_name_3.2.31_dbg.apk

또 다른 대안은 다음을 사용하는 것입니다.

String APK_NAME = "appname"
int VERSION_CODE = 1
String VERSION_NAME = "1.0.0"

project.archivesBaseName = APK_NAME + "-" + VERSION_NAME;

    android {
      compileSdkVersion 21
      buildToolsVersion "21.1.1"

      defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode VERSION_CODE
        versionName VERSION_NAME
      }

       .... // Rest of your config
}

그러면 모든 apk 출력에 "appname-1.0.0"이 설정됩니다.

@John 답변에 따라 pk 이름을 변경하는 올바른 방법

defaultConfig {
        applicationId "com.irisvision.patientapp"
        minSdkVersion 24
        targetSdkVersion 22
        versionCode 2  // increment with every release
        versionName "0.2" // change with every release
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //add this line
        archivesBaseName = "AppName-${versionName}-${new Date().format('yyMMdd')}"
    }   

또는 다른 방법으로 동일한 결과를 얻을 수 있습니다.

android {
    ...

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def formattedDate = new Date().format('yyMMdd')
            outputFileName = "${outputFileName.replace(".apk","")}-v${defaultConfig.versionCode}-${formattedDate}.apk"
        }
    }
}

전체 또는 일부 수정 후 정답이 있는 답변이 많이 있습니다.하는 데 에 제 .preBuildtask.task.task.

유사한 접근 방식을 사용하는 경우 다음과 같은 코드가 작동합니다.

project.android.applicationVariants.all { variant ->
    variant.preBuild.doLast {
    variant.outputs.each { output ->
        output.outputFile = new File(
                output.outputFile.parent,
                output.outputFile.name.replace(".apk", "-${variant.versionName}@${variant.versionCode}.apk"))
        }
    }
}

설명하기:첫 번째 작업에서 버전 코드와 이름을 재정의하고 있기 때문입니다.preBuild이 작업의 끝에 파일 이름을 변경해야 합니다.이 경우 그램들은 다음과 같은 역할을 수행합니다.

버전 코드/이름 삽입 -> preBuild 작업 수행 -> pack의 이름 바꾸기

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            output.outputFileName = output.outputFileName.replace(".apk", "-${variant.versionName}.apk")
        }
    }

나의 경우에는 이 오류를 이 방법으로 해결합니다.

디버그 버전에 접미사를 추가합니다. 이 경우 디버그 배포에 "-DEBUG" 텍스트를 추가합니다.

 buildTypes {
        release {

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


        }
        debug {

            defaultConfig {
                debuggable true

                versionNameSuffix "-DEBUG"
            }
        }
    }

최신 그래들 버전의 경우 다음 스니펫을 사용할 수 있습니다.

응용 프로그램 매니페스트 위치를 먼저 설정합니다.

 sourceSets {
        main {
            manifest.srcFile 'src/main/AndroidManifest.xml'
        {
    }

그리고 나중에 build.gradle.

import com.android.builder.core.DefaultManifestParser

def getVersionName(manifestFile) {
    def manifestParser = new DefaultManifestParser();
    return manifestParser.getVersionName(manifestFile);
}

def manifestFile = file(android.sourceSets.main.manifest.srcFile);
def version = getVersionName(manifestFile)

buildTypes {
    release {
       signingConfig signingConfigs.release
       applicationVariants.each { variant ->
       def file = variant.outputFile
       variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" +    versionName + ".apk"))
    }
}

빌드 유형별로 매니페스트가 다른 경우 조정합니다.단 하나밖에 없으니까 저한테 딱 맞는 것 같아요.

Android Studio 1.1.0 이후, 저는 이 조합이 Android 본체에서 작동한다는 것을 발견했습니다.build.gradle파일. 매니페스트 xml 파일 데이터를 가져오는 방법을 찾을 수 없는 경우입니다.Android Studio에서 좀 더 지원했으면 좋겠지만 원하는 apk 이름 출력이 나올 때까지 값을 가지고 놀기만 하면 됩니다.

defaultConfig {
        applicationId "com.package.name"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 6
        versionName "2"
    }
    signingConfigs {
        release {
            keyAlias = "your key name"
        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            signingConfig signingConfigs.release
            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace("app-release.apk", "appName_" + versionName + ".apk"))
                }
            }
        }
    }

여기서 대답했듯이 출력 파일에 버전 이름과 버전 코드를 추가하려면 다음과 같이 하십시오.

applicationVariants.all { variant ->
        variant.outputs.all {
            def versionName = variant.versionName
            def versionCode = variant.versionCode
            def variantName = variant.name
            outputFileName = "${rootProject.name}" + '_' + variantName + '_' + versionName + '_' + versionCode + '.apk'
        }
    }

다음과 같이 형식화된 빌드 시간을 pk 이름에 추가할 수도 있습니다.

setProperty("archivesBaseName", "data-$versionName " + (new Date().format("HH-mm-ss")))

다음은 Kotlin DSL에서 수행할 수 있는 방법입니다.

applicationVariants.all {
    outputs.all {
        this as com.android.build.gradle.internal.api.ApkVariantOutputImpl

        val apkName = outputFileName.replace(".apk", "-" + defaultConfig.versionName + ".apk")

        outputFileName = apkName
    }
}

언급URL : https://stackoverflow.com/questions/18332474/how-to-set-versionname-in-apk-filename-using-gradle

반응형