Gradle for Android Part 2 (Getting Started with Build.gradle)

Gradle for Android Part 2 (Getting Started with Build.gradle)

In this chapter, we will learn the following:

  • Understanding Gradle files
  • Writing a simple build task
  • Homemade build scripts

Understanding Gradle scripts

Of course, all the content we are discussing now is based on Android studio, so please download the relevant tools first. When we create a new project, Android studio will create three gradle files for us by default, two build.gradle files and one settings.gradle file. The build.gradle files are placed in the root directory and the module directory respectively. The following is the structure of the gradle file:

  1. MyApp
  2. ├── build.gradle
  3. ├── settings.gradle
  4. └── app
  5. └── build.gradle

setting.gradle parsing

When your app has only one module, your setting.gradle will look like this:

  1. include ':app'  

The setting.gradle file will be executed during the initialization period. For the initialization period, you can refer to the previous blog, and it defines which module will be built. For example, the above setting.gradle includes the app module. Setting.gradle is for multi-module operations, so a single module project can completely delete this file. After that, Gradle will create a Setting object for us and include the necessary methods for it. You don't need to know the details of the Settings class, but you can at least know the concept.

Build.gradle in the root directory

This gradle file defines the common properties of all modules in this project. It contains two methods by default:

  1. buildscript {
  2. repositories {
  3. jcenter()
  4. }
  5. dependencies {
  6. classpath 'com.android.tools.build:gradle:1.2.3'  
  7. }
  8. }
  9. allprojects {
  10. repositories {
  11. jcenter()
  12. }
  13. }

The buildscript method defines global properties, and repositories defines jcenter as a repository. A repository represents the source of your dependency packages, such as a maven repository. Dependencies are used to define the build process. This means that you should not define submodule dependency packages in this method, you only need to define the default Android plugin, because this plugin allows you to execute related Android tasks.

The allprojects method can be used to define default properties for each module. You are not limited to the default configuration. In the future, you can create your own tasks in the body of the allprojects method, and these tasks will be visible in all modules.

build.gradle in module

The gradle file in the module only works for that module, and it can override any parameters from the gradle file in the root directory. The module file should be like this:

  1. apply plugin: 'com.android.application'  
  2. android {
  3. compileSdkVersion 22
  4. buildToolsVersion "22.0.1"  
  5. defaultConfig {
  6. applicationId "com.gradleforandroid.gettingstarted"  
  7. minSdkVersion 14
  8. targetSdkVersion 22
  9. versionCode 1
  10. versionName "1.0"  
  11. }
  12. buildTypes {
  13. release {
  14. minifyEnabled false  
  15. proguardFiles getDefaultProguardFile
  16. ( 'proguard-android.txt' ), 'proguard-rules.pro'  
  17. }
  18. }
  19. }
  20. dependencies {
  21. compile fileTree(dir: 'libs' , include: [ '*.jar' ])
  22. compile 'com.android.support:appcompat-v7:22.2.0'  
  23. }

Plugins

The first line of the file is the Android application plug-in, which we have introduced in the previous blog. It is a plug-in written by Google's Android development team and can provide all the building, packaging and testing of Android applications and dependent libraries.

Android

This method contains all Android properties, and the only required properties are compileSdkVersion and buildToolsVersion:

  • compileSdkVersion: The API version you want to use when compiling the app.
  • buildToolsVersion: The version number of the build tools.

The build tools include many useful command line commands, such as aapt, zipalign, dx, etc. These commands can be used to generate a variety of applications. You can download these build tools through the SDK Manager.

The defaultConfig method contains the core properties of the app, which will override the corresponding properties in AndroidManifest.xml.

  1. defaultConfig {
  2. applicationId "com.gradleforandroid.gettingstarted"  
  3. minSdkVersion 14
  4. targetSdkVersion 22
  5. versionCode 1
  6. versionName "1.0"  
  7. }

The first attribute is applicationId, which overrides the package name in the AndroidManifest file.

name, but about applicationId and package

Before gradle was used as the Android build tool, package

name has two functions in AndroidManifest.xml: it serves as a unique identifier for an app, and it is used as the package name of the R resource file.

Gradle makes it easy to build different versions of an app using build variants. For example, it is easy to create a free version and a paid version of an app. The two versions require separate identifiers, so they can appear as different apps in major app stores, and of course they can be installed on the same phone at the same time. The resource code and the R file must have the same package name, otherwise your resource code will need to be changed, which is why the Android development team split the two major functions of the package name. The package name defined in the AndroidManifest file is still used as the package name and the package name of the R file. The applicationid will be used as a unique identifier in the device and major app stores.

Next will be minSdkVersion and targetSdkVersion. These two are very similar to <uses-sdk> in AndroidManifest. minSdkVersion is defined as the minimum supported API.

versionCode will be used as the version number, and versionName has no effect.

All attributes override the attributes in the AndroidManifest file, so you don't need to define these attributes in AndroidManifest.

The buildTypes method defines how to build different versions of the app, which we will introduce in the next blog.

Dependencies

The dependency module is one of the default properties of gradle (which is why it is placed outside of Android), which defines all the dependent packages for your app. By default, we depend on all the jar files in the libs folder, including the AppCompat aar file. We will discuss the issue of dependencies in the next blog.

Let’s start with tasks

If you want to know how many tasks you have available, run gradlew tasks directly, which will show you all the available tasks. When you create an Android project, it will include Android tasks, build tasks, build setup tasks, help tasks, install tasks, verification tasks, etc.

Basic tasks

The android plugin depends on the Java plugin, and the Java plugin depends on the base plugin.

The base plugin has basic tasks lifecycle and some common properties.

The base plugin defines tasks such as assemble and clean, and the Java plugin defines check and build tasks, which are not defined in the base plugin.

The agreed meanings of these tasks are:

  • assemble: assemble all output
  • clean: clear all output
  • check: execute all checks, usually unit tests and instrumentation tests
  • build: execute all assemble and check

The Java plugin also adds the concept of source sets.

Android tasks

Android plugins inherit these basic tasks and implement their own behaviors:

  • assemble creates an apk for each version
  • clean deletes all build tasks, including apk files
  • check performs Lint checks and can stop script execution if Lint detects errors
  • build executes assemble and check

By default, assemble tasks define assembleDebug and assembleRelease, but you can define more build versions. In addition to these tasks, the android plugin also provides some new tasks:

  • connectedCheck executes all test tasks on the test machine
  • deviceCheck executes all tests on the remote device
  • installDebug and installRelease install a specific version on the device
  • All install tasks have corresponding uninstall tasks

The build task depends on the check task, but does not depend on connectedCheck or deviceCheck. Using Lint to execute the check task will generate some related files. These reports can be viewed in app/build/outputs:

Android Studio tasks

You don't have to execute gradle scripts in the command line, Android studio has its own tool:

In this interface, all you have to do is double-click. Of course, you can also open the command line in Android studio and execute related commands. The specific operations will not be introduced here.

Custom Build

When you customize the gradle file in Android studio, you need to update the project:

In fact, this button executes the generateDebugSources tasks, which generates all necessary classes files.

BuildConfig and resources

  1. android {
  2. buildTypes {
  3. debug {
  4. buildConfigField "String" , "API_URL" ,
  5. "\"http://test.example.com/api\""  
  6. buildConfigField "boolean" , "LOG_HTTP_CALLS" , "true"  
  7. }
  8. release {
  9. buildConfigField "String" , "API_URL" ,
  10. "\"http://example.com/api\""  
  11. buildConfigField "boolean" , "LOG_HTTP_CALLS" , "false"  
  12. }
  13. }

Similar to these defined constants, once these properties are defined, you can use them in your code: BuildConfig.API_URL and BuildConfig.LOG_HTTP

Recently, the Android tools team also made it possible to define strings in it:

  1. android {
  2. buildTypes {
  3. debug {
  4. resValue "string" , "app_name" , "Example DEBUG"  
  5. }
  6. release {
  7. resValue "string" , "app_name" , "Example"  
  8. }
  9. }
  10. }

You can use these strings in your code. The "" is not required.

Global Settings

If you have many modules in one project, you can define your project file like this.

  1. allprojects {
  2. apply plugin: 'com.android.application'  
  3. android {
  4. compileSdkVersion 22
  5. buildToolsVersion "22.0.1"  
  6. }
  7. }

This will only work if all your modules are Android apps. You need to add the Android plugin to access Android tasks. A better approach is to define some properties in the global gradle file and then apply them to the module. For example, you can define it like this in the root directory:

  1. ext {
  2. compileSdkVersion = 22
  3. buildToolsVersion = "22.0.1"  
  4.    

Then you can use these attributes in submodules:

  1. android {
  2. compileSdkVersion rootProject.ext.compileSdkVersion
  3. buildToolsVersion rootProject.ext.buildToolsVersion
  4. }

Project properties file

The above method is one way, of course there are many ways:

  • ext method
  • gradle.properties file
  • -p parameter
  1. ext {
  2. local = 'Hello from build.gradle'  
  3. }
  4. task printProperties << {
  5. println local // Local extra property
  6. println propertiesFile // Property from file
  7. if (project.hasProperty( 'cmd' )) {
  8. println cmd // Command line property
  9. }
  10. }

Of course you can define it in gradle.properties:

  1. propertiesFile = Hello from gradle.properties

You can also type in the command line:

  1. $ gradlew printProperties -Pcmd= 'Hello from the command line'  
  2. :printProperties
  3. Hello from build.gradle
  4. Hello from gradle.properties
  5. Hello from the command line

Summarize

In this blog, we have carefully looked at the three gradle files generated by Android studio. Now you should be able to create your own gradle files. We have also learned the most basic build tasks and learned about the Android plugin and its tasks.

In the next few years, the Android development ecosystem will explode and many interesting dependencies will be available for everyone to use. In the next blog post, we will look at several ways we can add our dependencies so that we can avoid reinventing the wheel.

<<:  Gradle for Android Part 1 (Starting with Gradle and AS)

>>:  Getting started with Android Studio jni development——Just look at me!

Recommend

Tianyu Cangqiong game gold-making project, claiming to have 50+ orders per day

Tianyu Cangqiong game gold-making project, claimi...

Xiaohongshu Comprehensive Promotion and Traffic Guide

The four words "promotion and traffic genera...

How to quickly create a small program? How to create your own mini program?

How to quickly create a small program? How to cre...

How to build a brand at zero cost?

For those of us who work in marketing, the shocks...

The 4 user quadrants of product promotion!

When we promote our products , the first thing we...

Want to do brand marketing without a prototype? Stop kidding!

As a brand, if you want to enter the hearts of us...

Build a developer community operation strategy from scratch!

The author of this article starts from user portr...

How does a new media director write a promotion plan?

Today’s topic is how to write a promotion plan fo...

Mother's Day copywriting is here, here is a secret to seduce your mom!

This Sunday, May 13th is Mother's Day . In ad...