빌드 구성

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

프로젝트마다 빌드 목표가 다를 수 있습니다. 예를 들어 서드 파티 라이브러리용 빌드는 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를 사용해야 합니다.

빌드 구성 파일

맞춤 빌드 구성을 생성하려면 하나 이상의 빌드 구성 파일이나 build.gradle 파일을 변경해야 합니다. 이러한 일반 텍스트 파일은 Groovy(자바 가상 머신(JVM)용 동적 언어) 또는 Kotlin 스크립트(Kotlin 언어의 버전)를 사용하는 빌드 로직을 설명하고 조작하기 위해 Domain Specific Language(DSL)를 사용합니다.

Android Gradle 플러그인에서 필요한 대부분의 DSL 요소를 도입하므로 빌드 구성을 시작하기 위해 Groovy 또는 Kotlin 스크립트를 알아야 할 필요는 없습니다. Android Gradle 플러그인 DSL에 관한 자세한 내용은 Groovy의 DSL 참조 문서를 읽어보세요. Kotlin 스크립트는 기본 Gradle Kotlin DSL도 사용합니다.

Android 스튜디오는 새 프로젝트를 시작할 때 그림 1과 같이 일부 파일을 자동으로 만들고, 적절한 기본값으로 파일을 채웁니다.

그림 1. Android 앱 모듈의 기본 프로젝트 구조

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

Gradle 설정 파일

settings.gradle 파일(Groovy용) 또는 settings.gradle.kts 파일(Kotlin 스크립트용)은 루트 프로젝트 디렉터리에 있습니다. 이 설정 파일은 프로젝트 수준의 저장소 설정을 정의하며 앱을 빌드할 때 포함해야 하는 모듈을 Gradle에 알려줍니다. 다중 모듈 프로젝트는 최종 빌드에 들어가야 하는 각 모듈을 지정해야 합니다.

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

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’

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")

최상위 빌드 파일

최상위 build.gradle 파일(Groovy용) 또는 build.gradle.kts 파일(Kotlin 스크립트용)은 루트 프로젝트 디렉터리에 있습니다. 이 파일은 프로젝트의 모든 모듈에 적용되는 종속 항목을 정의합니다. 기본적으로 최상위 빌드 파일은 plugins 블록을 사용하여 프로젝트의 모든 모듈에 공통되는 Gradle 종속 항목을 정의합니다. 또한 최상위 빌드 파일에는 빌드 디렉터리를 정리하는 코드가 포함되어 있습니다.

다음 코드 샘플은 새 프로젝트를 만든 후 최상위 build.gradle 파일의 기본 설정과 DSL 요소를 설명합니다.

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 '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
}

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 "7.4.1" apply false
    id("com.android.library") version "7.4.1" apply false
    id("org.jetbrains.kotlin.android") version "1.8.10" apply false
}

추가 속성을 사용하여 프로젝트 전체의 속성 구성(지원 중단됨)

여러 모듈이 포함된 Android 프로젝트의 경우, 프로젝트 수준에서 특정 속성을 정의하고 이러한 속성을 모든 모듈에서 공유하는 것이 유용할 수도 있습니다. 최상위 build.gradle 파일(Groovy용) 또는 build.gradle.kts 파일(Kotlin 스크립트용)의 ext 블록에 추가 속성을 추가하면 됩니다.

Groovy

// This block encapsulates custom properties and makes them available to all
// modules in the project. The following are only a few examples of the types
// of properties you can define.
ext {
    sdkVersion = 33
    // You can also create properties to specify versions for dependencies.
    // Having consistent versions between modules can avoid conflicts with behavior.
    appcompatVersion = "1.6.1"
    ...
}
...

Kotlin

// This block encapsulates custom properties and makes them available to all
// modules in the project. The following are only a few examples of the types
// of properties you can define.
ext {
    extra["sdkVersion"] = 33
    // You can also create properties to specify versions for dependencies.
    // Having consistent versions between modules can avoid conflicts with behavior.
    extra["appcompatVersion"] = "1.6.1"
    ...
}
...

동일한 프로젝트의 한 모듈에서 이러한 속성에 액세스하려면 모듈의 build.gradle 파일에서 다음과 같은 구문을 사용합니다.

Groovy

android {
    // Use the following syntax to access properties you defined at the project level:
    // rootProject.ext.property_name
    compileSdk rootProject.ext.sdkVersion
    ...
}
...
dependencies {
    implementation "androidx.appcompat:appcompat:${rootProject.ext.appcompatVersion}"
    ...
}

Kotlin

android {
    // Use the following syntax to access properties you defined at the project level:
    // rootProject.extra["property_name"]
    compileSdk = rootProject.extra["sdkVersion"]

    // Alternatively, you can access properties using a type safe delegate:
    val sdkVersion: Int by rootProject.extra
    ...
    compileSdk = sdkVersion
}
...
dependencies {
    implementation("androidx.appcompat:appcompat:${rootProject.ext.appcompatVersion}")
    ...
}

모듈 수준 빌드 파일

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

이 샘플 Android 앱 모듈 build.gradle 파일은 몇 가지 기본 DSL 요소와 설정을 간략히 설명합니다.

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'
}

/**
 * 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'
        }
    }
}

/**
 * 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.6.1'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

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")
}

/**
 * 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"
        }
    }
}

/**
 * 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.6.1")
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
}

Gradle 속성 파일

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

gradle.properties
이 파일에서는 프로젝트 범위의 Gradle 설정을 구성할 수 있습니다(예: Gradle 데몬의 최대 힙 크기). 자세한 내용은 빌드 환경을 참고하세요.
local.properties
다음을 포함하여 빌드 시스템의 로컬 환경 속성을 구성합니다.
  • ndk.dir - NDK 경로. 이 속성은 지원 중단되었습니다. 다운로드한 모든 NDK 버전은 Android SDK 디렉터리의 ndk 디렉터리에 설치됩니다.
  • sdk.dir - 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를 클릭하거나(그림 2 참고) 메뉴 바에서 Sync Project 를 클릭합니다. Android 스튜디오에서 구성 오류가 발견되면(예: 소스 코드에서 compileSdkVersion보다 높은 API 수준에서만 사용할 수 있는 API 기능을 사용함) 메시지 창에 문제에 관한 설명이 표시됩니다.

그림 2. 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은 동일한 우선순위를 사용하므로, 각 빌드 변형에서 서로 다른 구성 요소나 권한을 최종 매니페스트에 정의할 수 있습니다. 맞춤 소스 세트 만들기에 관해 자세히 알아보려면 소스 세트 만들기를 참고하세요.

기타 빌드 시스템

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

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