본문 바로가기
User Guide

빌드 컨피규어 하기 Configure Your Build (27)

by 각종 잡상식 지식 모음 2016. 6. 10.
반응형

빌드 컨피규어 하기  Configure Your Build

VIDEO

The New Android SDK Build System

안드로이드 빌드시스템은 app 자원과 소스 코드를 컴파일한 다음, 테스트, 설치, 서명, 배포될, APK로 패키지합니다.
안드로이드 스튜디오는 빌드 프로세스를 자동화하고 관리하기 위하여 Gradle(고급 빌드 툴킷)을 사용하는데, Gradle로 
사용자 맞춤형 빌드 구성을 유연하게 정의할 수 있습니다.
app의 모든 버전에서 공통 부품을 재사용할 수 있으며, 각 빌드 구성은 사용자 자신의 코드 및 자원 세트를 정의 할 수 있습니다.
Gradle용 안드로이드 플러그인은 안드로이드 애플리케이션의 빌딩과 테스팅에 특정된 프로세스와 구성 가능한 셋팅을 제공하기 위하여
빌드 툴킷과 같이 작업합니다. 
Android build system compiles app resources and source code, and packages them into APKs that you can test, deploy, sign, and distribute. Android Studio uses Gradle, an advanced build toolkit, to automate and manage the build process, while allowing you to define flexible custom build configurations. Each build configuration can define its own set of code and resources, while reusing the parts common to all versions of your app. The Android Plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications.

Gradle과 Android plugin는 안드로이드 스튜디오와 독립적으로 실행됩니다.
이것은 Android apps을 Android Studio내에서, 사용자 머신 또는 Android Studio가 설치되지 않는 머신(continuous 통합서버와 같은)의 커맨드 라인에서 빌드할 수 있음을 의미합니다.
Android Studio를 사용하지 않는 경우, command line에서 app을 빌드하고 실행하는 방법을 배울 수 있습니다.
The output of the build is the same whether you are building a project from the command line, on a remote machine, or using Android Studio.
Gradle and the Android plugin run independent of Android Studio. This means that you can build your Android apps from within Android Studio, the command line on your machine, or on machines where Android Studio is not installed (such as continuous integration servers). If you are not using Android Studio, you can learn how to build and run your app from the command line. The output of the build is the same whether you are building a project from the command line, on a remote machine, or using Android Studio.

Note: Because Gradle and the Android plugin run independently from Android Studio, you need to update the build tools separately. Read the release notes to learn how to update Gradle and the Android plugin.

The flexibility of the Android build system enables you to perform custom build configurations without modifying your app's core source files. This section helps you understand how the Android build system works, and how it can help you customize and automate multiple build configurations. If you simply want to learn more about deploying your app, see Building and Running from Android Studio. To start creating custom build configurations right away using Android Studio, see Configuring Build Variants.

빌드 프로세스     The Build Process


빌드 프로세스는 프로젝트를 Android Application Package (APK)로 변환시키는 많은 도구와 프로세스와 관련되어 있습니다.
build process는 매우 유연하기 때문에, 속에서 무엇이 발생되는지를 이해하는 것이 유용합니다.
The build process involves many tools and processes that convert your project into an Android Application Package (APK). The build process is very flexible, so it's useful to understand some of what is happening under the hood.

Figure 1. The build process of a typical Android app module.

전형적인 안드로이드 app모듈의 빌드 프로세스는 그림1과 같이 아래와 같은 일반적 절차를 따릅니다:
The build process for a typical Android app module, as shown in figure 1, follows these general steps:

  1. 컴파일러는 소스 코드를 DEX (Dalvik 실행가능) 파일로 변환시키는데, 안드로이드 장치에서 실행되는 바이트 코드, 컴파일된 리소스에 다른 모든 것을 포함되어 있습니다.
    The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  2. APK Packager는 DEX files과 compiled resources를 단일 APK로 결합합니다.
    어쨌든 app이 Android 장치에 설치되고 디플로이 될 수 있기 전에, APK는 서명되어야 합니다.
    The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  3. The APK Packager signs your APK using either the debug or release keystore:
    1. If you are building a debug version of your app, that is, an app you intend only for testing and profiling, the packager signs your app with the debug keystore. Android Studio automatically configures new projects with a debug keystore.
    2. If you are building a release version of your app that you intend to release externally, the packager signs your app with the release keystore. To create a release keystore, read about Signing your app in Android Studio.
  4. Before generating your final APK, the packager uses the zipalign tool to optimize your app use less memory when running on a device.

At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Custom Build Configurations


Gradle and the Android plugin help you configure the following aspects of your build:

Build Types
빌드 타입은 app을 구축하고 패키징할 때, Gradle이 사용하는 특정 속성을 정의하고, 일반적으로 개발 라이프 사이클의 여러 단계에 대하여 구성됩니다.
예를 들어, 디버그 빌드 타입은 디버그 옵션을 가능하게 하고, 디버그 키를 사용하여 APK에 서명하며,
릴리스 빌드 타입은 분포를 위한 배포 키를 갖고 APK를 응축하고, 모호하게 하고 서명합니다.
app을 만들기 위하여 최소한 1개의 빌드 타입을 정의해야 하는데 - 안드로이드 Studio는 기본적으로 디버그 및 배포 빌드 타입을 만듭니다.
앱을 위한 패키징 셋팅을 사용자 맞춤으로 시작하기 위하여 빌드 타입 구성하는 방법을 배워야 합니다.
Build types define certain properties that Gradle uses when building and packaging your app, and are typically configured for different stages of your development lifecycle. For example, the debug build type enables debug options and signs the APK with the debug key, while the release build type may shrink, obfuscate, and sign your APK with a release key for distribution. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default. To start customizing packaging settings for your app, learn how to Configure build types.
Product Flavors
Product flavors represent different versions of you app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually. To start creating different versions of your app, learn how to Configure product flavors.
Build Variants
A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants. To learn how to create and manage build variants, read the Configure build variants overview.
Manifest Entries
You can specify values for some properties of the manifest file in the build variant configuration. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version. When multiple manifests are present, Gradle merges manifest settings.
Dependencies
build system은 사용자의 로컬 filesystem으로부터 그리고 remote repositories로부터의 프로젝트 dependencies를 관리합니다.
이것으로 dependencies의 바이너리 패키지를 수작업으로 사용자자의 프로젝트 디렉토리로 search, download, copy하는 것이 방지됩니다.
To find out more, learn how to Declare dependencies.
The build system manages project dependencies from your local filesystem and from remote repositories. This prevents you from having to manually search, download, and copy binary packages of your dependencies into your project directory. To find out more, learn how to Declare dependencies.
Signing
The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate using known credentials to avoid a password prompt at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build. If you do not have a release key, you can generate one as described in Signing your applications.
ProGuard
The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.

Build Configuration Files


사용자 맞춤형 build configurations을 만들려면 1개 이상의 build configuration files 또는 build.gradle files을 변경시켜야 합니다.
이들 plain text files은 Groovy를 사용하여 비즈니스 로직을 서술하고 조작하기 위하여 Domain Specific Language (DSL)을 사용하는데, 이것은 Java Virtual Machine (JVM)용 다이나믹 언어입니다.
Android Plugin for Gradle이 필요한 대부분의 DSL elements를 도입하기 때문에 빌드를 위한 컨피규어링을 시작하기 위한 Groovy를 배울 필요가 없습니다.
Android plugin DSL에 대한 보다 상세한 내용은, DSL reference documentation를 읽으세요.
Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don’t need to know Groovy to start configuring your build because the Android Plugin for Gradle introduces most of the DSL elements you need. To learn more about the Android plugin DSL, read the DSL reference documentation.

When starting a new project, Android Studio automatically creates some of these files for you, as shown in figure 2, and populates them based onsensible defaults.

Figure 2. The default project structure for an Android app module.

There are a few Gradle build configuration files that are a part of the standard project structure for an Android app. Before you can start configuring your build, it is important to understand the scope and purpose of each of these files, and the basic DSL elements they should define.

The Gradle Settings File

The gradle.settings file, located in the root project directory, tells Gradle which modules it should include when building your app. For most projects, the file is simple and only includes the following:

include ‘:app

However, multi-module projects need to specify each module that should go into the final build.

The Top-level Build File

The top-level build.gradle file, located in the root project directory, defines build configurations that apply to all modules in your project. By default, the top-level build file uses the buildscript {} block to define the Gradle repositories and dependencies that are common to all modules in the project. The following code sample describes the default settings and DSL elements you can find in the top-level build.gradle after creating a new project.

/**
 * The buildscript {} block is where you configure the repositories and
 * dependencies for Gradle itself--meaning, you should not include dependencies
 * for your modules here. For example, this block includes the Android plugin for
 * Gradle as a dependency because it provides the additional instructions Gradle
 * needs to build Android app modules.
 */


buildscript
{

   
/**
     * The repositories {} block configures the repositories Gradle uses to
     * search or download the 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
     * JCenter as the repository Gradle should use to look for its dependencies.
     */


    repositories
{
        jcenter
()
   
}

   
/**
     * The dependencies {} block configures the dependencies Gradle needs to use
     * to build your project. The following line adds Android Plugin for Gradle
     * version 2.0.0 as a classpath dependency.
     */


    dependencies
{
        classpath
'com.android.tools.build:gradle:2.0.0'
   
}
}

/**
 * The allprojects {} block is where you configure the repositories and
 * dependencies used by all modules in your project, such as third-party plugins
 * or libraries. Dependencies that are not required by all the modules in the
 * project should be configured in module-level build.gradle files. For new
 * projects, Android Studio configures JCenter as the default repository, but it
 * does not configure any dependencies.
 */


allprojects
{
   repositories
{
       jcenter
()
   
}
}

The Module-level Build File

The module-level build.gradle file, located in each <project>/<module>/ directory, allows you to configure build settings for the specific module it is located in. Configuring these build settings allows you to provide custom packaging options, such as additional build types and product flavors, and override settings in the main/ app manifest or top-level build.gradle file.

This sample Android app module build.gradle file outlines some of the basic DSL elements and settings that you should know.

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


apply plugin
: 'com.android.application'

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


android
{

 
/**
   * compileSdkVersion 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.
   *
   * buildToolsVersion specifies the version of the SDK build tools, command-line
   * utilities, and compiler that Gradle should use to build your app. You need to
   * download the build tools using the SDK Manager.
   */


  compileSdkVersion
23
  buildToolsVersion
"23.0.3"

 
/**
   * 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
{

   
/**
     * applicationId uniquely identifies the package for publishing.
     * However, your source code should still reference the package name
     * defined by the package attribute in the main/AndroidManifest.xml file.
     */


    applicationId
'com.example.myapp'

   
// Defines the minimum API level required to run the app.
    minSdkVersion
14

   
// Specifies the API level used to test the app.
    targetSdkVersion
23

   
// 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 Proguard settings 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 allows you to create different versions of your app that can
   * override defaultConfig {} 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.
   */


  productFlavors
{
    free
{
      applicationId
'com.example.myapp.free'
   
}

    paid
{
      applicationId
'com.example.myapp.paid'
   
}
 
}
}

/**
 * The dependencies {} block in the module-level build configuration file
 * only specifies dependencies required to build the module itself.
 */


dependencies
{
    compile project
(":lib")
    compile
'com.android.support:appcompat-v7:22.0.1'
    compile fileTree
(dir: 'libs', include: ['*.jar'])
}

Gradle Properties Files

Gradle also includes two properties files, located in your root project directory, that you can use to specify settings for the Gradle build toolkit itself:

gradle.properties
This is where you can configure project-wide Gradle settings, such as the Gradle daemon's maximum heap size. For more information, seeConfiguring the build environment.
local.properties
Configures local environment properties for the build system, such as the path to the SDK installation. Because the content of this file is automatically generated by Android Studio and is specific to the local developer environment, you should not modify this file manually or check it into your version control system.

Syncing Project with Gradle Files

When you make changes to the build configuration files in your project, Android Studio requires that you sync your project files so that it can import your build configuration changes and run some checks to make sure your configuration won't create build errors.

To sync your project files, click Sync Now in the notification bar that appears when you make a change, as shown in figure 3, or click Sync Project from the menu bar. If Android Studio notices any errors with your configuration, for example, your source code uses API features that are only available in an API level higher than your compileSdkVersion, the Messages window appears to describe the issue.

Figure 3. Syncing the project with build configuration files in Android Studio.

Source Sets

Android Studio logically groups source code and resources for each module into source sets. A module’s main/ source set includes the code and resources used by all its build variants. Additional source set directories are optional, and Android Studio does not automatically create them for you when you configure new build variants. However, creating source sets, similar to main/, helps organize files and resources that Gradle should only use when building certain versions of your app:

src/main/
This source set includes code and resources common to all build variants.
src/<buildType>/
Create this source set to include code and resources only for a specific build type.
src/<productFlavor>/
Create this source set to include code and resources only for a specific product flavor.
src/<productFlavorBuildType>/
Create this source set to include code and resources only for a specific build variant.

For example, to generate the "fullDebug" version of your app, the build system merges code, settings, and resources from following source sets:

  • src/fullDebug/ (the build variant source set)
  • src/debug/ (the build type source set)
  • src/full/ (the product flavor source set)
  • src/main/ (the main source set)

Note: When you create a new file or directory in Android Studio, using the File > New menu options, you can create it for a specific source set. The source sets you can choose from are based on your build configurations, and Android Studio automatically creates the required directories if they don't already exist.

If different source sets contain different versions of the same file, Gradle uses the following priority order when deciding which file to use (source sets on the left override the files and settings of source sets to the right):

build variant > build type > product flavor > main source set > library dependencies

This allows Gradle to use files that are specific to the build variant you are trying to build while reusing activities, application logic, and resources that are common to other versions of your app. When merging multiple manifests, Gradle uses the same priority order, so each build variant can define different components or permissions in the final manifest. To learn more about creating custom source sets, go to Create source sets for build variants.

반응형

댓글