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

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

As you can see, this is an English book. Since the domestic Gradle translation materials are incomplete, I have specially opened a column to translate the book Gradle for Android, and at the same time add my own experience and actual work experience. I hope you will like it.

If you are a new Android developer, or a newbie switching from eclipse to Android studio, then I strongly recommend you to follow my article, as shown on the cover, to use the gradle build tool to automatically build your Android project. Without further ado, let's get started.

Today I will mainly introduce the use of Android studio tools, as well as the basics of cradle, the use of cradle wrapper and how to migrate from eclipse to Android studio.

This article was written on December 30, 2015. The official version of Android studio has been developed to 1.5, and the preview version has reached 2.0, so let's switch to Android studio.

When you first open Android studio, there is a view that shows you the environment you are about to create and makes sure you are using the latest Android SDK and the necessary Google dependencies. It also lets you choose whether to create an AVD so that you can use the emulator. A few more words here:

  1. Try to use Android studio 2.0, because it is really faster, and the speed of its emulator has also increased a lot. I have used it so far and have not found any bugs, so there is no need to worry at all.
  2. If you use an emulator to develop Android, try to use the Genymotion emulator. Although its current Android 6.0 still has many bugs, its speed is still very fast in its lower versions. Using the emulator for development and installing a folder browser for the virtual machine is a powerful tool for timely viewing SQLite table files. You can google for specific operating methods.
  3. Try to use the latest build version 23.0.0 or above.

Understanding basic Gradle

If you want to create an Android project based on gradle, you must write a build script, which is usually called build.grade. You may have noticed that when we look at this script, gradle will provide us with a lot of default configurations and common default values, which greatly simplifies our work. For example, when using ant and maven, we need to write a lot of configuration files, which is disgusting. And gradle has default configurations. If you need to use your own configuration, you can simply rewrite them.

The Gradle script is not like a traditional XML file, but a dynamic DSL based on Groovy, which is a dynamic language based on JVM.

You don't have to worry at all. When using gradle, you still need to learn the Groovy language. The language is easy to read, and if you have already learned java, learning Groovy will not be difficult. If you want to start creating your own tasks and plug-ins, then you'd better have a deeper understanding of Groovy. However, since it is based on JVM, it is entirely possible for you to develop your own plug-ins through pure Java code or any other JVM-based language. As for plug-in development, we will have relevant introduction later.

Projects and tasks

There are two important concepts in grade, namely project and tasks. Each build is completed by at least one project, so the project in Android studio is not the same concept as the project in Gradle. Each project has at least one task. Each build.grade file represents a project. Tasks are defined in build.gradle. When initializing the build process, gradle will gather all projects and tasks based on the build file. A task contains a series of actions, which will then be executed in sequence. An action is a piece of code that is executed, much like a method in Java.

Build lifecycle

Once a task is executed, it will not be executed again. Tasks that do not contain dependencies are always executed first. A build will go through the following three stages:

  • Initialization phase: The project instance is created here. If there are multiple modules, that is, multiple build.gradle files, multiple projects will be created.
  • Configuration phase: During this phase, the build.gradle script will be executed to create and configure all tasks for each project.
  • Execution phase: In this phase, Gradle will decide which tasks will be executed. Which tasks will be executed depends entirely on the parameters passed in when starting the build and the current folder location.

Configuration file for build.gradle

Projects built based on grade usually have at least one build.gradle, so let's take a look at Android's build.gradle:

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

This is where the actual build begins. In the repository address, we have used JCenter. JCenter is similar to Maven repository and does not require any additional configuration. Grade also supports several other repositories, both remote and local.

The build script also defines an Android build tool, which is where the Android plugin comes in. The Android plugin provides everything you need to build and test your application. Every Android application needs a plugin like this:

  1. apply plugin: 'com.android.application'  

Plugins are used to extend the capabilities of gradle scripts. Plugins are used in a project so that the build script of the project can define the properties defined by the plugin and the tasks that use it.

Note: When you are developing a dependent library, then you should use 'com.android.library', and you cannot use both of them at the same time, it will cause build failure, a module either uses Android application or Android library plugin, not both.

When using the Android plugin, the Android tag will be available, as shown below:

  1. android {
  2. compileSdkVersion 22
  3. buildToolsVersion "22.0.1"  
  4. }

We will discuss more properties in Chapter 2.

Project Structure

Compared with Eclipse, the structure built by Android studio is very different:

  1. MyApp
  2. ├── build.gradle
  3. ├── settings.gradle
  4. └── app
  5. ├── build.gradle
  6. ├── build
  7. ├── libs
  8. └── src
  9. └── main
  10. ├── java
  11. │ └── com.package.myapp
  12. └── res
  13. ├── drawable
  14. ├── layout
  15. └── etc.

The grade project usually contains a build.gradle in the root folder, and the code used is in the app folder. This folder can also be named other than app. For example, when you use Android studio to create a project for a mobile application and an Android wear application, the modules will be called application and wearable by default.

Gradle uses a concept called source set. The official explanation is: a source set is a set of resource files that will be compiled and executed. For Android projects, main is a source set, which contains all the resource code. When you start writing test cases, you usually put the code in a separate source set, called androidTest, which only contains tests.

Getting started with the Gradle Wrapper

Grade is just a build tool, and new versions are always updated, so using Gradle Wrapper will be a good choice to avoid problems caused by Gradle version updates. Gradle Wrapper provides a windows batch file and other system shell files. When you use these scripts, the current gradle version will be downloaded and automatically used in the project build, so each developer only needs to use Wrapper when building their own app. So developers do not need to install any gradle version for your computer. On Mac, you only need to run gradlew, and on Windows, you only need to run gradlew.bat.

You can also use the command line ./gradlew -v to view the current gradle version. The following is the folder of wrapper:

  1. myapp/
  2. ├── gradlew
  3. ├── gradlew.bat
  4. └── gradle/wrapper/
  5. ├── gradle-wrapper.jar
  6. └── gradle-wrapper.properties

You can see a bat file for Windows, a shell script for Mac, a jar file, and a configuration file. The configuration file contains the following information:

  1. #Sat May 30 17:41:49 CEST 2015
  2. distributionBase=GRADLE_USER_HOME
  3. distributionPath=wrapper/dists
  4. zipStoreBase=GRADLE_USER_HOME
  5. zipStorePath=wrapper/dists
  6. distributionUrl=https\://services.gradle.org/distributions/
  7. gradle-2.4-all.zip

You can change the url to change your gradle version.

Using basic build commands

Using your command line, navigate to your project and type:

  1. $ gradlew tasks

This command will list all the runnable tasks. You can also add the --all parameter to see all tasks. When you are developing, to build the project, you need to run the assemble task through the debug configuration:

  1. $ gradlew assembleDebug

This task will create a debug version of the app, and the Android plugin will save it in the MyApp/app/build/outputs/apk directory.

In addition to assemble, there are three basic commands:

  • check runs all checks, which means running all tests on the connected device or simulator.
  • build is a combination of check and assemble.
  • clean Clear the output files of the project.

Keep old eclipse file structure

This article will not describe how to import eclipse projects into Android studio.

  1. android {
  2. sourceSets {
  3. main {
  4. manifest.srcFile 'AndroidManifest.xml'  
  5. java.srcDirs = [ 'src' ]
  6. resources.srcDirs = [ 'src' ]
  7. aidl.srcDirs = [ 'src' ]
  8. renderscript.srcDirs = [ 'src' ]
  9. res.srcDirs = [ 'res' ]
  10. assets.srcDirs = [ 'assets' ]
  11. }
  12. androidTest.setRoot( 'tests' )
  13. }
  14. }

Configuring this in the grade file will preserve the eclipse directory structure. Of course, if you have any dependent jars, you need to tell gradle where they are. Assuming the jars are in a folder called libs, you should configure it like this:

  1. dependencies {
  2. compile fileTree(dir: 'libs' , include: [ '*.jar' ])
  3. }

This line means: treat all jar files in the libs folder as dependent packages.

Summarize

Through this article, we can learn the advantages of gradle and why we should use gradle. We took a brief look at Android studio and how it helps us generate build files.

At the same time, we learned about Gradle Wrapper, which makes it easier for us to maintain and share projects. We know how to create a new project in Android studio, and how to migrate from eclispe to Android studio and keep the directory structure.

At the same time, we learned the most basic gradle tasks and command line commands. In the next article, we will customize our own build files.

<<:  Android login page imitation hook effect, you will always need it!

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

Recommend

What exactly is a tower company?

Not long ago, China Mobile, China Unicom and China...

If you go to Altay, you must see this river

recent Produced by CCTV The TV series "My Al...

How to develop a successful online event planning plan?

This article mainly talks about how to develop a ...

In 2020, new marketing innovation breakthrough!

First, I would like to talk about the two dimensi...

Mars' leopard print may be the most powerful evidence of life

NASA 's Perseverance rover has discovered pos...

How long will it take for humans to hibernate? Not far away!

For some species, when external conditions become...

Is lying really related to the nose? Everyone is Pinocchio!

I believe everyone has heard of the fairy tale &q...

CCTV 3.15 exposed that Nikon was politically suppressed: Who believes it?

During the 3.15 period this year, CCTV's 3.15 ...

Is it possible for humans to travel across the Earth?

Today I want to talk to you about a question that...