AndroidStudio build.gradle说明

组成

AS一个项目中可以有多个模块。build.gradle也就由两个层级组成,项目根目录的build.gradle配置所有模块公用的需求。模块build.gradle配置仅模块需要的。

项目根目录build.gradle

基本组成

/**
 * 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.
 */
// 配置gradle相关依赖,用来编译。
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.
     *
     * New projects created using Android Studio 3.0 and higher also include
     * Google's Maven repository.
     */
    // 配置编译项目,gradle下载依赖的资源的仓库。资源库可以是本地的,也可以是自定义的远端库。
    repositories {
        google()
        jcenter()
    }

    /**
     * The dependencies block configures the dependencies Gradle needs to use
     * to build your project. The following line adds Android plugin for Gradle
     * version 3.3.2 as a classpath dependency.
     */
    // 配置gradle编译项目需要依赖的工具,如com.android.tools.build、gradle:3.3.2
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
    }
}

/**
 * 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. However, you should configure module-specific dependencies in
 * each module-level build.gradle file. For new projects, Android Studio
 * includes JCenter and Google's Maven repository by default, but it does not
 * configure any dependencies (unless you select a template that requires some).
 */
// 配置项目所有模块依赖的第三方插件或者库。依赖文件库可以是本地的,也可以是自定义的远端库
allprojects {
   repositories {
       google()
       jcenter()
   }
}

配置项目范围的属性

对于包含多个模块的 Android 项目,在项目级别定义某些属性,并在所有模块间共享这些属性可能会非常有用。 为此可以将 额外属性 添加到顶级 build.gradle 文件的 ext 代码块中。

buildscript {...}

allprojects {...}

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

要从相同项目中的模块访问这些属性,请在模块的 build.gradle 文件(您可以在以下部分了解有关此文件的详细信息)中使用以下语法。

android {
  // Use the following syntax to access properties you defined at the project level:
  // rootProject.ext.property_name
  compileSdkVersion rootProject.ext.compileSdkVersion
  ...
}
...
dependencies {
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    ...
}

额外属性

在gradle可以使用自定义的额外属性,比如:projects, tasks, and source sets。额外属性可以被add、read或者通过ext属性定义。一个ext块中至少可以定义一个属性。

plugins {
    id 'java'
}

ext {
    springVersion = "3.1.0.RELEASE"
    emailNotification = "[email protected]"
}

sourceSets.all { ext.purpose = null }

sourceSets {
    main {
        purpose = "production"
    }
    test {
        purpose = "test"
    }
    plugin {
        purpose = "production"
    }
}

task printProperties {
    doLast {
        println springVersion
        println emailNotification
        sourceSets.matching { it.purpose == "production" }.each { println it.name }
    }
}

Output of gradle -q printProperties

> gradle -q printProperties
3.1.0.RELEASE
[email protected]
main
plugin

参考资料

Android官网文档:https://developer.android.google.cn/studio/build
深入学习自定义属性:https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties 学习Extra properties节。
Android build中使用gradle:参照https://google.github.io/android-gradle-dsl/current/index.html
全面学习gradle:https://gradle.org/guides/#getting-started

模块级构建文件

模块级 build.gradle 文件位于各 project/module/ 目录中,用于配置适用于其所在模块的构建设置。 可以通过配置这些构建设置来提供自定义打包选项(例如附加构建类型和产品风格),以及替换 main/ 应用清单或顶级 build.gradle 文件中的设置。

此 Android 应用模块 build.gradle 文件示例概括了应了解的某些基本 DSL 元素和设置。

/**
 * 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.
 */
// 告诉gradle编译该模块需要的Android插件,使后面的android块可以访问特定的编译选项
apply plugin: 'com.android.application'

/**
 * The android block is where you configure all your Android-specific
 * build options.
 */
// 配置Android编译选项
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.
   */

  compileSdkVersion 28

  /**
   * 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.
   *
   * This property is optional because the plugin uses a recommended version of
   * the build tools by default.
   */

  buildToolsVersion "28.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 15

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

    // 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 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 splits block is where you can configure different APK builds that
   * each contain only code and resources for a supported screen density or
   * ABI. You'll also need to configure your build so that each APK has a
   * different versionCode.
   */
// apk切分规则。如下:使不同分辨率设备使用对应的apk,配置编译出和设备分辨率相同的apk,减小apk大小,节省设备空间
  splits {
    // Settings to build multiple APKs based on screen density.
    density {

      // Enable or disable building multiple APKs.
      enable false

      // Exclude these densities when building multiple APKs.
      exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi"
    }
  }
}

/**
 * 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 'com.android.support:appcompat-v7:28.0.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

猜你喜欢

转载自blog.csdn.net/mcsbary/article/details/88773850