빌드 구성

Android 빌드 시스템은 앱 리소스 및 소스 코드를 컴파일하고 개발자가 테스트, 구축, 서명 및 배포할 수 있는 APK 또는 Android App Bundle로 패키징합니다.

Android 스튜디오는 고급 빌드 툴킷인 Gradle을 사용하여 빌드 프로세스를 자동화하고 관리하는 한편, 개발자가 유연한 맞춤형 빌드 구성을 정의하도록 허용합니다. 각 빌드 구성에서는 모든 앱 버전에 공통되는 부분을 재사용하면서 자체 코드 및 리소스 세트를 정의할 수 있습니다. Android Gradle 플러그인은 빌드 툴킷과 함께 작동하여 Android 앱을 빌드하고 테스트하는 데 필요한 특정 프로세스와 구성 가능한 설정을 제공합니다.

Gradle과 Android Gradle 플러그인은 Android 스튜디오와 독립적으로 실행됩니다. 즉, Android 스튜디오 내에서, 컴퓨터의 명령줄에서, 또는 Android 스튜디오가 설치되지 않은 컴퓨터(예: 지속적 통합 서버)에서 Android 앱을 빌드할 수 있습니다.

Android 스튜디오를 사용하지 않는 경우에는 명령줄에서 앱을 빌드하고 실행하는 방법에 관해 알아볼 수 있습니다. 프로젝트를 명령줄에서 빌드하는 경우, 원격 컴퓨터에서 빌드하는 경우, Android 스튜디오를 사용하여 빌드하는 경우 모두 빌드의 출력은 동일합니다.

참고: Gradle과 Android Gradle 플러그인은 Android 스튜디오와 독립적으로 실행되므로, 이들 빌드 도구는 각각 업데이트해야 합니다. Gradle 및 Android Gradle 플러그인의 업데이트 방법에 관한 자세한 내용은 출시 노트를 참고하세요.

Android 빌드 시스템은 유연성이 탁월하므로 앱의 핵심 소스 파일을 수정하지 않고도 맞춤 빌드 구성을 만들 수 있습니다. 이 페이지에서는 Android 빌드 시스템의 작동 방식과 여러 개의 빌드 구성을 맞춤설정하고 자동화하는 방법에 관해 설명합니다. 앱 배포에 관해 자세히 알아보려면 앱 빌드 및 실행을 참고하세요. Android 스튜디오를 사용하여 즉시 맞춤 빌드 구성을 만들려면 빌드 변형 구성을 참고하세요.

빌드 프로세스

빌드 프로세스에는 프로젝트를 Android 애플리케이션 패키지(APK) 또는 Android App Bundle(AAB)로 변환하는 여러 가지 도구와 프로세스가 포함됩니다.

Android Gradle 플러그인은 대부분의 빌드 프로세스를 수행하지만 빌드 프로세스의 특정 측면을 이해하여 빌드를 요구사항에 맞게 조정하는 것이 유용할 수 있습니다.

프로젝트마다 빌드 목표가 다를 수 있습니다. 예를 들어 서드 파티 라이브러리가 Android 보관 파일 (AAR) 또는 자바 보관 파일 (JAR)을 생성함 제공합니다 그러나 앱은 가장 일반적인 프로젝트 유형이며, 앱 프로젝트용 빌드는 외부 사용자에게 배포, 테스트 또는 출시할 수 있는 앱의 디버그나 출시 APK 또는 AAB를 생성합니다.

이 페이지에서는 앱 개발에 중점을 두지만 대다수의 빌드 단계와 개념은 대부분의 빌드 유형에 공통적입니다.

Android 빌드 용어집

Gradle과 Android Gradle 플러그인을 사용하여 다음과 같은 빌드 요소를 구성할 수 있습니다.

빌드 유형

빌드 유형은 앱을 빌드하고 패키징할 때 Gradle이 사용하는 일부 속성을 정의합니다. 또한 일반적으로 개발 수명 주기의 다양한 단계에 맞춰 구성됩니다.

예를 들어, 디버그 빌드 유형은 디버그 옵션을 사용 설정하고 디버그 키로 앱에 서명하는 반면, 출시 빌드 유형은 배포를 위해 앱을 축소, 난독 처리하고 출시 키로 서명할 수도 있습니다.

앱을 빌드하려면 최소 하나 이상의 빌드 유형을 정의해야 합니다. Android 스튜디오는 기본으로 디버그 빌드 유형 및 출시 빌드 유형을 생성합니다. 앱의 패키징 설정을 맞춤설정하려면 빌드 유형 구성 방법을 알아보세요.

제품 버전
제품 버전은 무료 및 유료 버전과 같이 사용자에게 출시할 수 있는 앱의 여러 버전을 의미합니다. 제품 버전을 맞춤설정하여 다양한 코드와 리소스를 사용하면서 앱의 모든 버전에 공통되는 부분을 공유 및 재사용할 수 있습니다. 제품 버전은 선택사항이고 수동으로 만들어야 합니다. 다양한 버전의 앱을 생성하려면, 제품 버전 구성 방법에 관해 알아보세요.
빌드 변형
빌드 변형은 빌드 유형과 제품 버전의 크로스 프로덕트이며 앱을 빌드하기 위해 Gradle에서 사용하는 구성입니다. 빌드 변형을 사용하면 개발 중에 제품 버전의 디버그 버전을 빌드하거나 배포용 제품 버전의 서명된 출시 버전을 빌드할 수 있습니다. 개발자가 빌드 변형을 직접 구성하는 것은 아니며, 빌드 변형을 형성하는 빌드 유형과 제품 버전을 구성하는 것입니다. 빌드 유형이나 제품 버전을 추가로 생성하면 빌드 변형도 추가로 생성됩니다. 빌드 변형을 생성하고 관리하는 방법에 관한 자세한 내용은 빌드 변형 구성 개요를 참고하세요.
매니페스트 항목
빌드 변형 구성에서 매니페스트 파일의 일부 속성 값을 지정할 수 있습니다. 이 빌드 값은 매니페스트 파일의 기존 값을 재정의합니다. 이는 여러 개의 앱 변형을 생성하려는 경우 각 애플리케이션의 이름이 다르거나, 최소 SDK 버전 또는 타겟 SDK 버전이 다를 때 유용합니다. 여러 개의 매니페스트가 존재하는 경우 매니페스트 병합 도구는 매니페스트 설정을 병합합니다.
종속 항목
빌드 시스템은 로컬 파일 시스템과 원격 저장소에서 프로젝트 종속 항목을 관리합니다. 따라서 종속 항목의 바이너리 패키지를 수동으로 검색, 다운로드하거나 프로젝트 디렉터리에 복사할 필요가 없습니다. 자세한 내용은 빌드 종속 항목 추가를 참고하세요.
서명
빌드 시스템을 사용하여 빌드 구성에서 서명 설정을 지정할 수 있으며 빌드 프로세스 중에 앱에 자동으로 서명할 수 있습니다. 빌드 시스템은 알려진 사용자 인증 정보를 사용하여 기본 키와 인증서로 디버그 버전에 서명합니다. 이렇게 하면 빌드 시에 비밀번호를 묻는 메시지가 나타나지 않습니다. 이 빌드의 서명 구성을 명시적으로 정의하지 않는 한, 빌드 시스템은 출시 버전에 서명하지 않습니다. 출시 키가 없는 경우에는 앱 서명에 설명된 대로 출시 키를 생성할 수 있습니다. 대부분의 앱 스토어를 통해 앱을 배포하려면 서명된 출시 빌드가 필요합니다.
코드 및 리소스 축소
빌드 시스템을 사용하여 각 빌드 변형을 위한 다양한 ProGuard 규칙 파일을 지정할 수 있습니다. 앱을 빌드할 때 빌드 시스템은 R8과 같이 기본 제공되는 축소 도구를 사용하여 코드와 리소스를 축소하는 데 적절한 규칙 세트를 적용합니다. 코드와 리소스를 축소하면 APK 또는 AAB 크기를 줄일 수 있습니다.
다중 APK 지원
빌드 시스템으로 특정 화면 밀도나 Application Binary Interface(ABI)에 필요한 코드와 리소스만 포함된 다양한 APK를 자동으로 빌드할 수 있습니다. 자세한 내용은 다중 APK 빌드를 참고하세요. 하지만 단일 AAB를 출시하는 것이 좋습니다. 화면 밀도와 ABI 외에도 언어별 분할을 제공하면서 Google Play에 여러 아티팩트를 업로드할 필요가 없기 때문입니다. 2021년 8월 이후에 제출된 모든 신규 앱은 AAB를 사용해야 합니다.

Android 빌드의 Java 버전

소스 코드가 Java, Kotlin 또는 둘 다로 작성되었는지와 관계없이 JDK 또는 Java 언어를 선택해야 하는 곳이 여러 곳 있습니다. 새 버전이 생성됩니다 Android 빌드의 Java 버전을 참고하세요. 참조하세요.

빌드 구성 파일

맞춤 빌드 구성을 생성하려면 하나 이상의 더 많은 빌드 구성 파일을 사용할 수 있습니다 이러한 일반 텍스트 파일은 DNS (도메인별 언어)를 사용하여 빌드 로직을 조작하여 Kotlin 스크립트 이는 Kotlin 언어의 맛입니다. 또한 Groovy는 Java 가상 머신 (JVM)용 동적 언어를 사용하여 빌드를 구성할 수 있습니다.

구성 작업을 시작하기 위해 Kotlin 스크립트나 Groovy를 몰라도 됩니다. Android Gradle 플러그인에서 대부분의 DSL 요소를 도입하기 때문이지요. 알 수 있습니다. Android Gradle 플러그인 DSL에 관한 자세한 내용은 DSL 참조 문서. Kotlin 스크립트는 또한 기본 Gradle Kotlin DSL을 사용합니다.

새 프로젝트를 시작할 때 Android Studio는 자동으로 적절한 기본값을 기반으로 파일을 채웁니다. 프로젝트 파일 구조의 레이아웃은 다음과 같습니다.

└── MyApp/  # Project
    ├── gradle/
    │   └── wrapper/
    │       └── gradle-wrapper.properties
    ├── build.gradle(.kts)
    ├── settings.gradle(.kts)
    └── app/  # Module
    │   ├── build.gradle(.kts)
    │   ├── build/
    │   ├── libs/
    │   └── src/
    │        └── main/  # Source set
    │            ├── java/
    │            │   └── com.example.myapp
    │            ├── res/
    │            │   ├── drawable/
    │            │   ├── values/
    │            │   └── ...
    │            └── AndroidManifest.xml

Android 앱의 표준 프로젝트 구조의 일부인 Gradle 빌드 구성 파일이 있습니다. 빌드 구성을 시작하기 전에 이러한 각 파일의 범위 및 목적과 파일에서 정의해야 하는 기본 DSL 요소를 이해하는 것이 중요합니다.

Gradle 래퍼 파일

Gradle 래퍼 (gradlew)는 Gradle 자체를 다운로드하고 실행하는 소스 코드입니다. 따라서 보다 일관된 빌드 실행이 가능합니다. 개발자는 애플리케이션 소스를 만들고 gradlew를 실행합니다. 그러면 필요한 Gradle이 다운로드됩니다. Gradle을 시작하여 애플리케이션을 빌드합니다.

gradle/wrapper/gradle-wrapper.properties 파일 특정 버전의 애플리케이션을 설명하는 distributionUrl 속성을 Gradle은 빌드를 실행하는 데 사용됩니다.

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Gradle 설정 파일

settings.gradle.kts 파일 (Kotlin DSL용) 또는 settings.gradle 파일 (Groovy DSL용)은 루트에 있습니다. 프로젝트 디렉터리에 있습니다 이 설정 파일은 프로젝트 수준 저장소를 정의합니다. 애플리케이션을 빌드할 때 어떤 모듈을 포함해야 하는지 Gradle에 알려줍니다. 있습니다. 다중 모듈 프로젝트에서는 확인할 수 있습니다

대부분의 프로젝트에서 파일은 기본적으로 다음과 같습니다.

Kotlin

pluginManagement {

    /**
      * The pluginManagement.repositories block configures the
      * repositories Gradle uses to search or download the Gradle plugins and
      * their transitive dependencies. Gradle pre-configures support for remote
      * repositories such as JCenter, Maven Central, and Ivy. You can also use
      * local repositories or define your own remote repositories. The code below
      * defines the Gradle Plugin Portal, Google's Maven repository,
      * and the Maven Central Repository as the repositories Gradle should use to look for its
      * dependencies.
      */

    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {

    /**
      * The dependencyResolutionManagement.repositories
      * block is where you configure the repositories and dependencies used by
      * all modules in your project, such as libraries that you are using to
      * create your application. However, you should configure module-specific
      * dependencies in each module-level build.gradle file. For new projects,
      * Android Studio includes Google's Maven repository and the Maven Central
      * Repository by default, but it does not configure any dependencies (unless
      * you select a template that requires some).
      */

  repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
  repositories {
      google()
      mavenCentral()
  }
}
rootProject.name = "My Application"
include(":app")

Groovy

pluginManagement {

    /**
      * The pluginManagement.repositories block configures the
      * repositories Gradle uses to search or download the Gradle plugins and
      * their transitive dependencies. Gradle pre-configures support for remote
      * repositories such as JCenter, Maven Central, and Ivy. You can also use
      * local repositories or define your own remote repositories. The code below
      * defines the Gradle Plugin Portal, Google's Maven repository,
      * and the Maven Central Repository as the repositories Gradle should use to look for its
      * dependencies.
      */

    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {

    /**
      * The dependencyResolutionManagement.repositories
      * block is where you configure the repositories and dependencies used by
      * all modules in your project, such as libraries that you are using to
      * create your application. However, you should configure module-specific
      * dependencies in each module-level build.gradle file. For new projects,
      * Android Studio includes Google's Maven repository and the Maven Central
      * Repository by default, but it does not configure any dependencies (unless
      * you select a template that requires some).
      */

    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}
rootProject.name = "My Application"
include ':app'

최상위 빌드 파일

최상위 build.gradle.kts 파일 (Kotlin DSL용) 또는 build.gradle 파일 (Groovy DSL용)은 루트에 있습니다. 프로젝트 디렉터리에 있습니다 일반적으로 컨테이너 내에서 사용되는 플러그인의 일반적인 버전을 정의합니다 지정할 수도 있습니다

다음 코드 샘플은 최상위 빌드 스크립트를 추가합니다.

Kotlin

plugins {

    /**
     * Use `apply false` in the top-level build.gradle file to add a Gradle
     * plugin as a build dependency but not apply it to the current (root)
     * project. Don't use `apply false` in sub-projects. For more information,
     * see Applying external plugins with same version to subprojects.
     */

    id("com.android.application") version "8.6.0" apply false
    id("com.android.library") version "8.6.0" apply false
    id("org.jetbrains.kotlin.android") version "1.9.23" apply false
}

Groovy

plugins {

    /**
     * Use `apply false` in the top-level build.gradle file to add a Gradle
     * plugin as a build dependency but not apply it to the current (root)
     * project. Don't use `apply false` in sub-projects. For more information,
     * see Applying external plugins with same version to subprojects.
     */

    id 'com.android.application' version '8.6.0' apply false
    id 'com.android.library' version '8.6.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.9.23' apply false
}

모듈 수준 빌드 파일

모듈 수준 build.gradle.kts (Kotlin DSL용) 또는 build.gradle 파일 (Groovy DSL용)은 각 project/module/ 디렉터리에 있습니다. 이러한 파일을 사용하여 이 파일이 위치하는 특정 모듈의 빌드 설정을 구성할 수 있습니다. 구성 이러한 빌드 설정을 사용하면 다음과 같은 맞춤 패키징 옵션을 제공할 수 있습니다. 빌드 유형 및 제품 버전을 추가하고, main/ 앱 매니페스트 또는 최상위 빌드 스크립트

Android SDK 설정

애플리케이션의 모듈 수준 빌드 파일에는 컴파일, 플랫폼 동작 선택 시 사용되는 Android SDK 버전 애플리케이션이 실행되는 최소 버전 지정

Gradle 빌드의 SDK 사양 개요

compileSdk

compileSdk는 Android 및 Java API가 무엇인지 결정합니다. 사용할 수 있습니다 최신 Android 버전 사용하기 기능을 사용하려면 컴파일할 때 최신 Android SDK를 사용하세요.

일부 Android 플랫폼 API를 사용하지 못할 수 있음 이전 API 수준에는 적용되지 않습니다. 다음과 같은 작업을 할 수 있습니다. <ph type="x-smartling-placeholder"></ph> 최신 기능의 사용을 조건부로 보호하거나 <ph type="x-smartling-placeholder"></ph> AndroidX 호환성 라이브러리를 사용하면 더 낮은 비용으로 최신 기능을 사용할 수 있습니다. Android API 수준

각 Android SDK는 애플리케이션에서 사용할 수 있는 Java API의 하위 집합을 제공합니다. 의 표 Java 또는 Kotlin 소스 코드에서 사용할 수 있는 Java API Android SDK 버전에 따라 사용 가능한 Java API 수준을 보여줍니다. 최신 Java API는 다음을 통해 이전 버전의 Android에서 지원됩니다. 디슈가링은 확인할 수 있습니다

compileSdk가 충돌하면 Android 스튜디오에서 경고를 표시합니다. 현재 버전의 Android 스튜디오, AGP 또는 프로젝트 라이브러리 종속 항목 요구사항을 충족해야 합니다

minSdk

minSdk는 개발자가 실행할 수 있는 가장 낮은 Android 버전을 정의할 수 있어야 합니다 minSdk를 설정하면 모든 기기에서 앱을 설치할 수 있습니다.

더 낮은 버전의 Android를 지원하려면 더 많은 조건부 확인이 필요할 수 있음 AndroidX 호환성 라이브러리를 더 많이 사용할 수 있습니다. 해야 할 일 낮은 버전을 지원하는 유지 관리 비용과 여전히 낮은 버전을 사용 중인 사용자의 비율 자세한 내용은 Android 스튜디오의 New project Wizard 버전 차트 현재 버전 사용 비율을 나타냅니다.

Android 스튜디오에서 코드를 수정하거나 빌드하면 Lint는 사용할 수 없는 API에 관해 경고해 minSdk에 포함 이러한 문제는 <ph type="x-smartling-placeholder"></ph> 새로운 특성을 조건부로 만들거나 <ph type="x-smartling-placeholder"></ph> Appcompat(이전 버전과의 호환성)

targetSdk

targetSdk의 용도는 두 가지입니다.

  1. 애플리케이션의 런타임 동작을 설정합니다.
  2. 테스트한 Android 버전을 증명합니다.

현재 Android 버전보다 더 높은 버전의 Android를 사용하는 기기에서 실행하는 경우 targetSdk, Android는 앱을 호환성 모드로 실행함 하위 버전에 표시된 것과 유사하게 작동하는 targetSdk 예를 들어 API 23에서 런타임을 도입했을 때 모든 앱이 이를 즉시 채택할 준비가 된 것은 아니었습니다. targetSdk를 22로 설정하면 앱이 런타임 권한을 사용하지 않고 기능을 사용할 수 있는 API 23 기기 최신 compileSdk 버전에 포함되어 있습니다. Google Play 배포 정책이 대상 API 수준에 대한 추가 정책을 참조하세요.

targetSdk 값은 작거나 같아야 합니다. compileSdk의 조회수입니다.

참고: compileSdktargetSdk의 값은 같을 필요는 없습니다. 다음 기본 원칙에 유의하세요.

  • compileSdk에서 새 API에 액세스할 수 있습니다.
  • targetSdk는 앱의 런타임 동작을 설정합니다.
  • targetSdk 값은 compileSdk 이하여야 합니다.

샘플 앱 모듈 빌드 스크립트

이 샘플 Android 앱 모듈 빌드 스크립트는 몇 가지 기본 DSL 요소 및 설정을 살펴보겠습니다.

Kotlin

/**
 * The first section in the build configuration applies the Android Gradle plugin
 * to this build and makes the android block available to specify
 * Android-specific build options.
 */

plugins {
    id("com.android.application")
}

/**
 * Locate (and possibly download) a JDK used to build your kotlin
 * source code. This also acts as a default for sourceCompatibility,
 * targetCompatibility and jvmTarget. Note that this does not affect which JDK
 * is used to run the Gradle build itself, and does not need to take into
 * account the JDK version required by Gradle plugins (such as the
 * Android Gradle Plugin)
 */
kotlin {
    jvmToolchain(11)
}

/**
 * The android block is where you configure all your Android-specific
 * build options.
 */

android {

    /**
     * The app's namespace. Used primarily to access app resources.
     */

    namespace = "com.example.myapp"

    /**
     * compileSdk specifies the Android API level Gradle should use to
     * compile your app. This means your app can use the API features included in
     * this API level and lower.
     */

    compileSdk = 33

    /**
     * The defaultConfig block encapsulates default settings and entries for all
     * build variants and can override some attributes in main/AndroidManifest.xml
     * dynamically from the build system. You can configure product flavors to override
     * these values for different versions of your app.
     */

    defaultConfig {

        // Uniquely identifies the package for publishing.
        applicationId = "com.example.myapp"

        // Defines the minimum API level required to run the app.
        minSdk = 21

        // Specifies the API level used to test the app.
        targetSdk = 33

        // Defines the version number of your app.
        versionCode = 1

        // Defines a user-friendly version name for your app.
        versionName = "1.0"
    }

    /**
     * The buildTypes block is where you can configure multiple build types.
     * By default, the build system defines two build types: debug and release. The
     * debug build type is not explicitly shown in the default build configuration,
     * but it includes debugging tools and is signed with the debug key. The release
     * build type applies ProGuard settings and is not signed by default.
     */

    buildTypes {

        /**
         * By default, Android Studio configures the release build type to enable code
         * shrinking, using minifyEnabled, and specifies the default ProGuard rules file.
         */

        getByName("release") {
            isMinifyEnabled = true // Enables code shrinking for the release build type.
            proguardFiles(
                getDefaultProguardFile("proguard-android.txt"),
                "proguard-rules.pro"
            )
        }
    }

    /**
     * The productFlavors block is where you can configure multiple product flavors.
     * This lets you create different versions of your app that can
     * override the defaultConfig block with their own settings. Product flavors
     * are optional, and the build system does not create them by default.
     *
     * This example creates a free and paid product flavor. Each product flavor
     * then specifies its own application ID, so that they can exist on the Google
     * Play Store, or an Android device, simultaneously.
     *
     * If you declare product flavors, you must also declare flavor dimensions
     * and assign each flavor to a flavor dimension.
     */

    flavorDimensions += "tier"
    productFlavors {
        create("free") {
            dimension = "tier"
            applicationId = "com.example.myapp.free"
        }

        create("paid") {
            dimension = "tier"
            applicationId = "com.example.myapp.paid"
        }
    }

    /**
     * To override source and target compatibility (if different from the
     * toolchain JDK version), add the following. All of these
     * default to the same value as kotlin.jvmToolchain. If you're using the
     * same version for these values and kotlin.jvmToolchain, you can
     * remove these blocks.
     */
    //compileOptions {
    //    sourceCompatibility = JavaVersion.VERSION_11
    //    targetCompatibility = JavaVersion.VERSION_11
    //}
    //kotlinOptions {
    //    jvmTarget = "11"
    //}
}

/**
 * The dependencies block in the module-level build configuration file
 * specifies dependencies required to build only the module itself.
 * To learn more, go to Add build dependencies.
 */

dependencies {
    implementation(project(":lib"))
    implementation("androidx.appcompat:appcompat:1.7.0")
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
}

Groovy

/**
 * The first line in the build configuration applies the Android Gradle plugin
 * to this build and makes the android block available to specify
 * Android-specific build options.
 */

plugins {
    id 'com.android.application'
}

/**
 * Locate (and possibly download) a JDK used to build your kotlin
 * source code. This also acts as a default for sourceCompatibility,
 * targetCompatibility and jvmTarget. Note that this does not affect which JDK
 * is used to run the Gradle build itself, and does not need to take into
 * account the JDK version required by Gradle plugins (such as the
 * Android Gradle Plugin)
 */
kotlin {
    jvmToolchain 11
}

/**
 * The android block is where you configure all your Android-specific
 * build options.
 */

android {

    /**
     * The app's namespace. Used primarily to access app resources.
     */

    namespace 'com.example.myapp'

    /**
     * compileSdk specifies the Android API level Gradle should use to
     * compile your app. This means your app can use the API features included in
     * this API level and lower.
     */

    compileSdk 33

    /**
     * The defaultConfig block encapsulates default settings and entries for all
     * build variants and can override some attributes in main/AndroidManifest.xml
     * dynamically from the build system. You can configure product flavors to override
     * these values for different versions of your app.
     */

    defaultConfig {

        // Uniquely identifies the package for publishing.
        applicationId 'com.example.myapp'

        // Defines the minimum API level required to run the app.
        minSdk 21

        // Specifies the API level used to test the app.
        targetSdk 33

        // Defines the version number of your app.
        versionCode 1

        // Defines a user-friendly version name for your app.
        versionName "1.0"
    }

    /**
     * The buildTypes block is where you can configure multiple build types.
     * By default, the build system defines two build types: debug and release. The
     * debug build type is not explicitly shown in the default build configuration,
     * but it includes debugging tools and is signed with the debug key. The release
     * build type applies ProGuard settings and is not signed by default.
     */

    buildTypes {

        /**
         * By default, Android Studio configures the release build type to enable code
         * shrinking, using minifyEnabled, and specifies the default ProGuard rules file.
         */

        release {
              minifyEnabled true // Enables code shrinking for the release build type.
              proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    /**
     * The productFlavors block is where you can configure multiple product flavors.
     * This lets you create different versions of your app that can
     * override the defaultConfig block with their own settings. Product flavors
     * are optional, and the build system does not create them by default.
     *
     * This example creates a free and paid product flavor. Each product flavor
     * then specifies its own application ID, so that they can exist on the Google
     * Play Store, or an Android device, simultaneously.
     *
     * If you declare product flavors, you must also declare flavor dimensions
     * and assign each flavor to a flavor dimension.
     */

    flavorDimensions "tier"
    productFlavors {
        free {
            dimension "tier"
            applicationId 'com.example.myapp.free'
        }

        paid {
            dimension "tier"
            applicationId 'com.example.myapp.paid'
        }
    }

    /**
     * To override source and target compatibility (if different from the
     * tool chain JDK version), add the following. All of these
     * default to the same value as kotlin.jvmToolchain. If you're using the
     * same version for these values and kotlin.jvmToolchain, you can
     * remove these blocks.
     */
    //compileOptions {
    //    sourceCompatibility JavaVersion.VERSION_11
    //    targetCompatibility JavaVersion.VERSION_11
    //}
    //kotlinOptions {
    //    jvmTarget = '11'
    //}
}

/**
 * The dependencies block in the module-level build configuration file
 * specifies dependencies required to build only the module itself.
 * To learn more, go to Add build dependencies.
 */

dependencies {
    implementation project(":lib")
    implementation 'androidx.appcompat:appcompat:1.7.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

Gradle 속성 파일

또한 Gradle에는 루트 프로젝트 디렉터리에 있는 두 개의 속성 파일이 포함되며 이 파일을 이용하여 Gradle 빌드 툴킷 자체의 설정을 지정할 수 있습니다.

gradle.properties
이 파일에서는 프로젝트 범위의 Gradle 설정을 구성할 수 있습니다(예: Gradle 데몬의 최대 힙 크기). 자세한 내용은 빌드 환경을 참고하세요.
local.properties
다음을 포함하여 빌드 시스템의 로컬 환경 속성을 구성합니다.
  • ndk.dir - NDK 경로. 이 속성은 지원 중단되었습니다. 다운로드한 모든 NDK 버전은 Android SDK 디렉터리의 ndk 디렉터리에 설치됩니다.
  • sdk.dir - Android SDK의 경로입니다.
  • cmake.dir - CMake 경로
  • ndk.symlinkdir - Android 스튜디오 3.5 이상에서 NDK 심볼릭 링크를 만듭니다. 이 링크는 설치된 NDK 경로보다 짧을 수 있습니다.

NDK를 더 짧은 경로로 다시 매핑(Windows 전용)

Windows에서 설치된 NDK 폴더의 도구(예: ld.exe)는 긴 경로를 사용하게 됩니다. 이 도구는 긴 경로를 잘 지원하지 않습니다.

더 짧은 경로를 만들려면 local.properties에서 ndk.symlinkdir 속성을 설정하여 Android Gradle 플러그인이 NDK에 관한 심볼릭 링크를 만들도록 요청합니다. 심볼릭 링크 경로는 기존 NDK 폴더보다 짧을 수 있습니다. 예를 들어 ndk.symlinkdir = C:\는 다음과 같은 심볼릭 링크를 생성합니다. C:\ndk\19.0.5232133

프로젝트를 Gradle 파일과 동기화

프로젝트에서 빌드 구성 파일이 변경되면 Android 스튜디오는 프로젝트 파일을 동기화하도록 요청합니다. 이렇게 하면 빌드 구성 변경사항을 가져올 수 있고 구성에서 빌드 오류가 발생하지 않도록 검사를 실행할 수 있습니다.

프로젝트 파일을 동기화하려면 프로젝트 파일에서 Sync Now를 클릭합니다. 변경 시 나타나는 알림바 그림 1을 클릭하거나 Sync Project 를 클릭합니다. 를 클릭합니다. Android 스튜디오에서 예를 들어, 소스 코드는 소스 코드에만 해당하는 compileSdkVersion보다 높은 API 수준에서 사용 가능 — 메시지 창에 문제가 설명되어 있습니다.

그림 1. Android 스튜디오에서 프로젝트를 빌드 구성 파일과 동기화

소스 세트

Android 스튜디오는 논리적으로 각 모듈의 소스 코드와 리소스를 소스 세트로 그룹화합니다. 새 모듈을 생성하면 Android 스튜디오는 모듈 내에 main/ 소스 세트를 만듭니다. 모듈의 main/ 소스 세트에는 모든 구성 요소에서 사용하는 코드와 리소스가 포함됩니다. 빌드 변형을 생성합니다.

추가적인 소스 세트 디렉터리는 선택사항이며, 새 빌드 변형을 구성할 때 Android 스튜디오가 이 디렉터리를 자동으로 만들지는 않습니다. 그러나 main/과 유사한 소스 세트를 생성하면, Gradle이 특정 앱 버전을 빌드할 때만 사용해야 하는 파일과 리소스를 쉽게 구성할 수 있습니다.

src/main/
이 소스 세트에는 모든 빌드 변형에 공통인 코드와 리소스가 포함됩니다.
src/buildType/
특정 빌드 유형에 관한 코드와 리소스만 포함하려면 이 소스 세트를 생성합니다.
src/productFlavor/
특정 제품 버전에 관한 코드와 리소스만 포함하려면 이 소스 세트를 생성합니다.

참고: 여러 제품 버전을 결합하도록 빌드를 구성하는 경우 버전 차원 간에 제품 버전의 각 조합에 관한 소스 세트 디렉터리를 생성할 수 있습니다(예: src/productFlavor1ProductFlavor2/).

src/productFlavorBuildType/
특정 빌드 변형에 관한 코드와 리소스만 포함하려면 이 소스 세트를 생성합니다.

예를 들어, 'fullDebug' 버전의 앱을 생성하기 위해 빌드 시스템은 다음 소스 세트에서 코드, 설정 및 리소스를 병합합니다.

  • src/fullDebug/(빌드 변형 소스 세트)
  • src/debug/(빌드 유형 소스 세트)
  • src/full/(제품 버전 소스 세트)
  • src/main/(기본 소스 세트)

참고: Android 스튜디오에서 새 파일이나 디렉터리를 만들 경우 File > New 메뉴 옵션을 사용하여 특정 소스 세트의 파일이나 디렉터리를 만들 수 있습니다. 선택할 수 있는 소스 세트는 빌드 구성을 기준으로 하며, 필수 디렉터리가 아직 없는 경우 Android 스튜디오가 자동으로 생성합니다.

서로 다른 소스 세트가 동일한 파일의 서로 다른 버전을 포함하는 경우, Gradle은 다음 우선순위에 따라 사용할 파일을 결정합니다(왼쪽 소스 세트가 오른쪽 소스 세트의 파일 및 설정을 재정의함).

빌드 변형 > 빌드 유형 > 제품 버전 > 기본 소스 세트 > 라이브러리 종속 항목

이렇게 하면 Gradle은 개발자가 빌드하려는 빌드 변형에 해당하는 파일만을 사용할 수 있으며, 앱의 다른 버전에 공통되는 활동, 애플리케이션 로직 및 리소스를 재사용할 수 있습니다.

여러 매니페스트를 병합할 때 Gradle은 동일한 우선순위를 사용하므로, 각 빌드 변형에서 서로 다른 구성 요소나 권한을 최종 매니페스트에 정의할 수 있습니다. 맞춤 소스 세트 만들기에 관해 자세히 알아보려면 소스 세트 만들기를 참고하세요.

버전 카탈로그

빌드에 공통 종속 항목을 가진 모듈이 여러 개 포함되어 있거나 공통 종속 항목을 가진 여러 개의 독립된 프로젝트가 있는 경우 당신이 사용하는 버전 카탈로그 또는 재료명세서 (BOM)를 사용해 지정할 수 있습니다

기타 빌드 시스템

Bazel을 사용하여 Android 앱을 빌드하는 것은 가능하지만 공식적으로는 지원되지 않습니다. Android 스튜디오는 공식적으로 Bazel 프로젝트를 지원합니다

Bazel을 사용한 빌드의 현재 제한사항을 더 자세히 알아보려면 알려진 문제를 참고하세요.