In 2013, Google Io, in order to better reuse code and customize the compilation process, Google introduced AndroidStudio and a new compilation system, Gradle. AndroidStudio can use Gradle to compile, but Gradle can be deployed and compiled separately. It’s easier to do CI. If you’re not already using AndroidStudio you can download it from the Android Developer WebSite. In this chapter, we will learn the following:

  • Understand the Android Studio
  • Understand Gradle basic concepts
  • Create a new Gradle based project
  • Using Gradle wrapper
  • How to convert an Eclipse project to a Gradle project

Android Studio

Android Studio was released in May 2013 (as a preview) and also supports Gradle. Android Studio is based on JetBrains’ IntelliJ IDEA, but has been customized for Android development. Available for free on Linux, Mac OS X, and Microsoft Windows, Android Studio is referred to AS AS.

Android Studio has several advantages over Eclipse: an improved user interface editor; Better memory monitor; Good editor character translation; Android Lint alerts and more features customized for Android developers. In addition to the regular Project and Packages views in IntelliJ IDEA, AS also has a special Project structure view for Android, which groups Gradle scripts, drawables, and other resources in a convenient way. With the release of stable version 1.0 of Android Studio, Google no longer maintains the Android Developer Tools (ADT) for Eclipse and recommends that all developers switch to Android Studio. This means that Google will no longer provide new functionality for Eclipse, and that all IDE-related tool development is now focused on Android Studio. If you’re still using Eclipse, it’s time to change.

Update the AS

AndroidStudio has four different update channels

  • Canary this channel is the latest update, but it may cause bugs
  • Dev This channel is updated once a month
  • The Beta channel is used for the release of new features after they are complete, but can be buggy
  • Stable Default option. Stable version of the added functionality after testing

By default, the AS checks each startup for available updates and pops up an update notification box. When you first launch Android Studio, it launches a wizard to set up your environment and make sure you have the latest Android SDK and the necessary Google Library. AS also offers the option to create An Android Virtual device (AVD) so you can run your application on the emulator.

Know Gradle basics

When building an Android project with Gradle, you need to set up a build script. The script name is usually build.gradle. You’ll notice that when we learn the basics of Gradle, a lot of Gradle syntax is common conventions, and default values are often provided in configuration files. This makes it easier to get started with Gradle than with a build system like Ant or Maven, which has long been the Android project build system.

Gradle build scripts are not written in traditional XML, but in a domain-specific language (DSL) based on Groovy, which is a dynamic language of the Java Virtual Machine (JVM). The team behind Gradle believes that using a declarative DSL-style approach based on a dynamic language has significant advantages over the more programmatic, free-floating Ant or any XML-based approach used by many other build systems.

This doesn’t mean you need to learn Groovy before you can start writing build scripts. Because Groovy is easy to read, the learning curve is even less steep if you already know Java. If you want to create your own Gradle Tasks and plugins (which we’ll discuss in a later section), learning more about Groovy will help you get a deeper understanding. On the other hand, because Groovy is based on the JVM, you can write code for custom plug-ins in Java or any other JVM-based language.

Projects and Tasks

Gradle has two important concepts: projects and tasks. Gradle Build consists of at least one project, and each project contains one or more tasks. Each build.gradle file represents a project. Tasks are defined in the build.gradle build script. When initializing the build process, Gradle assembles Project and Task objects based on the build file. Task objects consist of a list of Action objects in the order they need to be executed. An Action object is a block of code that is executed, similar to a method in Java.

The Build Lifecycle

Executing a Gradle build is the simplest form of executing actions on tasks that depend on other tasks. To simplify the build process, the build tool creates a dynamic model of the workflow as a directed acyclic graph (DAG). This means that all tasks are processed one after the other, and loop execution is impossible. Once the task is executed, it is not called again. Tasks with no dependencies will always run before other tasks. The dependency graph is generated during the configuration phase of the build. Gradle builds in three phases:

  • Initialization: This is the stage during which Gradle creates project instances. If you have multiple modules, each module is initialized in its own build.gradle file, creating multiple projects.
  • Configuration: In this phase, build scripts are executed to create and configure all tasks for each project object.
  • Execution: This is where Gradle determines which tasks should be executed. Which tasks should be performed depends on the parameters passed to start the build and the current run directory.

Build profile

In order for Gradle to build a project, you always need a build. Gradle file. An Android build file has several required elements:

buildscript {
    repositories {
		jcenter()
	}
	dependencies {
        classpath 'com. Android. Tools. Build: gradle: 1.2.3'}}Copy the code

The code above is where the actual configuration is built. The repositories in * * {… }** In the code block, configure JCenter Repository as the source of dependencies for the build script. JCenter is a pre-built Maven repository for Gradle. Gradle is already configured by default. No additional Settings are required. Gradle also has several built-in repositories, and Gradle also supports adding its own local or remote repositories.

Build script **dependencies{… }** The code block also defines a dependency on Android Build Tools, which is called an Android plugin. The Android plug-in provides everything you need to build and test your application. Every Android project needs to apply the Android plugin, which looks like this:

 apply plugin: 'com.android.application'
Copy the code

Plugins extend the functionality of Gradle build scripts. Applying a plug-in to a project enables your build script to define properties and use tasks defined in the plug-in.

If you are building a Library module, then you need to use com.android. Library instead of com.android.application in the module’s build.gradle file. Also, you can’t use both in the same module, as this will cause a build error. A module can be an Android Application or an Android Library, but not both.

After applying the Android Plugin, you can configure the properties associated with the Android build. The Android plugin defines ** Android {… }** Code block, as shown below, you can add android configuration to your project build.grade file

Android {compileSdkVersion 22 buildToolsVersion "22.0.1"}Copy the code

In the above code, the Android plug-in provides a DSL that fits the needs of Android. The only required properties are compileSdkVersion and buildToolsVersion. CompileSdkVersion specifies the SDK version of the compiled application. It is best to use the latest Version of the Android API as compileSdkVersion.

Project directory structure

The folder structure of Android projects has changed a lot compared to the old Eclipse projects. Here is the common file structure of Gradle applications:

Gradle projects usually have an extra level in the Project root path. This makes it easier to add additional modules later. All the source code for the application will go into the App folder. This folder is also the name of the module. By default, it does not have to be named app. For example, if you are using an Android Studio phone app or an Android Wear smartwatch app for your project, by default, it will be called Application and Wearable respectively.

Gradle has a concept of a source set. Official Gradle documentation describes a source set as a set of source files that are compiled and executed together. For Android projects, the main directory is the Source set that contains all the source code and resources for the default version of the application. When you start writing tests for an Android application, you need to put the test source code in a separate source set called androidTest, which contains only the test code.

The following is the corresponding table of Android related resource directories:

directory Android content
/src/main/java Application source code
/src/main/res Application resource code layout, drawable, values, etc
/libs The referenced JAR or AAR
/build The output of the build, such as apK or test reports

Using Grade Wrapper

Gradle is constantly updated, and new versions can break backward compatibility. Using the Gradle Wrapper is a good way to avoid problems and ensure a stable build.

Gradle Wrapper provides batch files on Windows platforms and shell scripts on other operating systems. When running the script, Gradle downloads the required version if it does not exist and automatically uses it for the build. This means that each developer or automated system (such as CI) that needs to build the application will simply run the Wrapper, which will handle compatibility issues such as Gradle version, rather than having to manually install the correct version of Gradle or build the server on the development machine itself each time. Therefore, it is recommended to add the wrapper file to the version control system (Git or SVN, etc.).

Running Gradle Wrappter is no different than running Gradle directly. You only need to run GradLew on Linux and Mac OS X, and gradlew. Bat on Windows instead of the regular Gradle command.

Access to Gradle Wrapper

For convenience, every new Android project includes the Gradle Wrapper by default, so when you create a new project, you don’t have to do anything. Of course, it is also possible to manually install Gradle on your computer and apply it directly to your project via the Gradle command, but this can create the Gradle compatibility issues discussed earlier. Gradle Wrapper can perform all Gradle operations and use the correct Gradle version. So, there is no reason to work with Gradle alone without using a wrapper.

You can check for the existence of Gradle wrapper in your project by running./gradlew -v from the terminal and going to the project root directory or running gradlew. Bat -v from Windows CMD. Running this command displays the version of Gradle and some additional information about the Settings. If the project is converted from an Eclipse project, the wrapper is not installed by default. In this case, you can use Gradle to generate it, but you need to install Gradle first to get the wrapper.

The Gradle download page has links to binaries and source code, and if you are on Mac OS X, you can use package managers such as Homebrew. All installation instructions are provided on the installation page.

After you have downloaded and installed Gradle and added it to your PATH, create a build. Gradle file that contains the following three lines:

Task Wrapper (type: wrapper) {gradleVersion = '2.4'}Copy the code

After that, run gradle Wrapper to generate the wrapper file. In the latest version of Gradle, you can also run the Wrapper task without modifying the build. Gradle file to add the above code, as it is already included as a task by default. In this case, you can specify the version directly with the –gradle-version parameter, as shown below:

$gradle Wrapper -- Gradle -version 2.4Copy the code

If the version number is not specified, the wrapper is configured to use the version of Gradle that is executing the task. These are all the files generated by the Wrapper task:

myapp/
|----gradlew
|----gradlew.bat
|----gradle/wrapper/
        |----gradle-wrapper.jar
        |----gradle-wrapper.properties
Copy the code

The Gradle Wrapper has three parts:

  • A batch file to run on Windows and a shell script to run on Linux/Mac OS X
  • A JAR package that bat and shell will call
  • A Properties file

The gradle-wrapper.properties file is the file that contains the configuration and tries to determine which version of Gradle to use. It looks like this:

#Sat May 30 17:41:49 CEST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
Copy the code

If you want to use a custom Gradle version, you can change the distributionUrl. This also means that any application or library module you use may have a different Gradle distribution address, so it is a good idea to check whether the distributionUrl can be trusted before running the wrapper.

Android Studio displays notifications when the version of Gradle you are using in your project is not the latest and recommends that you update it automatically. Essentially, Android Studio realizes that changing the distributionUrl configuration in Gradle-Wrapper triggers a rebuild to download the latest version.

Running the build Task

From a terminal or command prompt, go to the project root and run tasks using the grade Wrapper command:

$ gradlew tasks
Copy the code

This will print out a list of all available tasks. If you add the –all parameter, you get a more detailed description of each task’s dependencies and so on.

On Windows, you need to run gradlew. Bat. On Linux and Mac OS X, the complete command is./gradle. For brevity, all subsequent related commands are abbreviated to gradlew

To build a project package for Android development and debugging, run the assemble debug task:

$ gradlew assembleDebug
Copy the code

This task will generate a debug version of APK. By default, the Gradle Android plugin to save APK in MyApp/app/build/outputs/APK directory.

The abbreviated task name

To avoid heavy typing in the terminal, Gradle also provides an abbreviated hump named task name as a shortcut. For example, you can execute assembleDebug by running GradLew assDeb or even GradLew aD from the command line interface. There is a caveat here. As long as the camel case abbreviation is unique, it will work fine, but once another task has the same abbreviation, the abbreviated name will not work.

In addition to the assemble mission, there are three other types of missions:

  • Check tasks: Mainly use error checking, such as running unit tests or UI integration tests
  • Build task: Set out assemble and Check tasks at the same time
  • Clean task: Clean up all outputs during build

Migrate the project from Eclipse

There are two ways to migrate from an Eclipse project to a Gradle-based project:

  • The migration is handled automatically using the import wizard in Android Studio
  • Add the Gradle script to your Eclipse project and set everything manually

Most projects are simple enough that the AS import wizard automatically converts everything. If there is something that the import wizard cannot determine, AS can give you a hint and you can manually modify it.

However, some projects can be very complex and require manual conversion. If you have a complex, large project and you prefer to convert the project gradually rather than all at once, you can perform Ant tasks or even complete Ant builds from Gradle. By doing this, you can convert as fast as you like and slowly convert all the components.

Use the AS import wizard

To start the Import wizard, you need to open Android Studio, click on the File menu, and then click Import Project… , or on the Android Studio Start screen, click Import Non-Android Studio Project.

If you use JAR files or other libraries in your Eclipse project, the import wizard will suggest replacing them with Gradle dependencies. These dependencies can come from native Android SDKS (such as the Android Support package) or even from known online Repositories. If no matching local or online dependency is found, the JAR file is used again, just as before. The import wizard creates at least one module for the transformed project. If your project has source code libraries, those libraries will also be converted to modules.

The import wizard prompts are as follows:

Turning around AS creates a new folder to ensure that nothing is lost during the conversion, and you can easily compare the results of the import wizard with the original files. When the transformation is complete, THE AS opens the project and displays an import summary.

Summary lists all files that the import wizard decides to ignore and that are not copied to the new project. If you still want to include these files, you must manually copy them into the new project. Below the ignored files, a summary shows all JAR files that the import wizard can replace with Gradle dependencies. The AS will try to find these dependencies on JCenter. If you use the Support package, which is now included in Google Repository, you’ll need to download it to your computer via the SDK Manager, rather than using the JAR file directly. Finally, a summary lists all the files that the import wizard has moved, showing their source and destination.

The import wizard also adds three Gradle files to the project root directory: Gradle and settings.gradle, add another build.gradle to the module, and if you have any libraries that contain source code, the import wizard will also convert them into Gradle projects and combine everything together as needed.

The project should now build without any problems, but keep in mind that you may need to connect online to download some of the necessary dependencies.

More complex projects may require additional work, so next we’ll look at how to do the transformation manually.

Eclipse Export Wizard

Eclipse also has an export wizard, but it is completely obsolete because Google Android’s Android tools group discontinued Eclipse’s Android development tools. Therefore, it is recommended that you always use the import wizard in Android Studio.

Manual switch

There are several ways to manually migrate to Gradle based Android projects. It doesn’t need to change to a new directory structure, and you can even run Ant scripts from Gradle scripts. This makes the migration process very flexible, and it can make the transformation of large projects easier.

We’ll see Ant tasks in action in Chapter 9, “Custom Advanced Builds.”

Keep the old project structure

If you don’t want to move files, you can keep the Eclipse folder structure in your project. To do this, you need to change the configuration of the Source set. We mentioned the Source set when we talked about the project structure. Gradle and Android plug-ins have their default values, but these configurations can be overridden.

The first thing you need to do is create a build.gradle file in your project directory. This file should apply the Android plugin and define the properties required for Gradle and the Android plugin. In its simplest form, it should look like this:

Dependencies buildscript {repositories {jcenter ()} {the classpath 'com. Android. View the build: gradle: 1.2.3'}} the apply Plugin: 'com.android.application' android {compileSdkVersion 22 buildToolsVersion "22.0.1"}Copy the code

You can then override the Source set to match the Eclipse project structure, as follows:

android {
    sourceSets {
        main {
        	manifest.srcFile 'AndroidManifest.xml'
        	java.srcDirs = ['src']
        	resources.srcDirs = ['src']
        	aidl.srcDirs = ['src']
        	renderscript.srcDirs = ['src']
        	res.srcDirs = ['res']
        	assets.srcDirs = ['assets']
		}

    androidTest.setRoot('tests')
	}
}
Copy the code

In the Eclipse file structure, all source files reside in the same folder, so you need to tell Gradle that all these components can be found in the SRC folder. Therefore, you only need to include all the components from your project, and you don’t have to worry about the bad effects of adding everything to it.

If you have any dependencies on JAR files, you need to tell Gradle where the dependencies are. Assuming that the JAR file is in a folder named libs, the configuration looks like this:

dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar'])
}
Copy the code

The above code means that every file with the.jar extension in the libs directory is a dependency.

Transform to the new project structure

If you decide to manually convert the project to the new project structure, you will need to create several folders and move some files around. The following table shows an overview of some of the most important files and folders and the new project structure where you need to move them for conversion:

The original location The new location
src/ app/src/main/java/
res/ app/src/main/res/
assets/ app/src/main/assets/
AndroidManifest.xml app/src/main/AndroidManifest.xml

If you have any unit tests, you need to move the source code to **app/ SRC /test/ Java/and have Gradle recognize them automatically. Functional tests belong to the app/SRC/androidTest/Java / * * folder.

The next step is to create a settings.gradle file in the root directory of your project. This file needs to contain only one line. Its purpose is to tell Gradle to include the application module in the build:

include: ':app'
Copy the code

Gradle files. The first belongs to the project root directory (at the same level as settings.gradle) and is used to define the Settings for the project scope:

Dependencies buildscript {repositories {jcenter ()} {the classpath 'com. Android. View the build: gradle: 1.2.3'}}Copy the code

The main purpose of the above code is to set a few generic properties for all modules in the project. The second build.gradle is placed in the app folder and contains the Settings related to the application module:

Apply plugin: 'com.android.application' Android {compileSdkVersion 22 buildToolsVersion "22.0.1"}Copy the code

These are basic configurations. If you have a simple Android application that doesn’t rely on third-party code, that’s enough. However, if you have any third-party dependencies in your project, you will need to migrate them to Gradle dependencies.

Transform the Library project

If your project is a third party Android Library referenced by other people’s projects, the conversion steps are the same for most of the above Settings, except that you need to use the Android Library plugin instead of the Android Application plugin. The details of this process are discussed in Chapter 5, “Managing multi-module builds.”

conclusion

Let’s start this chapter by looking at the benefits of Gradle and why it makes more sense than any other build system currently in use. We took a quick look at Android Studio and how it helps us generate build files.

After the introduction, we took a look at the Gradle Wrapper, which makes it easier to maintain and share projects. We have created a new project in Android Studio, and now you know how to automatically and manually migrate Eclipse projects to Android Studio and Gradle. You can also build projects using Gradle in Android Studio or directly from the command line interface.

In the next few chapters, we’ll discuss how to customize builds to further automate the build process and make maintenance easier. We’ll first examine all the standard Gradle files, explore the basic build tasks, and then customize the build section in the next chapter.