Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Gradle for Android
Gradle for Android

Gradle for Android: Automate the build process for your Android projects with Gradle

eBook
$26.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Gradle for Android

Chapter 1. Getting Started with Gradle and Android Studio

When Google introduced Gradle and Android Studio, they had some goals in mind. They wanted to make it easier to reuse code, create build variants, and configure and customize the build process. On top of that, they wanted good IDE integration, but without making the build system dependent on the IDE. Running Gradle from the command line or on a continuous integration server will always yield the same results as running a build from Android Studio.

We will refer to Android Studio occasionally throughout the book, because it often provides a simpler way of setting up projects, dealing with changes, and so on. If you do not have Android Studio installed yet, you can download it from the Android developer website (http://developer.android.com/sdk/index.html).

In this chapter, we will cover the following topics:

  • Getting to know Android Studio
  • Understanding Gradle basics
  • Creating a new project
  • Getting started with the Gradle wrapper
  • Migrating from Eclipse

Android Studio

Android Studio was announced and released (as an early access preview) by Google in May 2013, alongside support for Gradle. Android Studio is based on JetBrains' IntelliJ IDEA, but is designed specifically with Android development in mind. It is available for free for Linux, Mac OS X, and Microsoft Windows.

Compared to Eclipse, Android Studio has an improved user interface designer, a better memory monitor, a nice editor for string translation, warnings for possible Android-specific issues and a lot more features aimed at Android developers. It also features a special project structure view for Android projects, besides the regular Project view and Packages view that exist in IntelliJ IDEA. This special view groups Gradle scripts, drawables, and other resources in a convenient way. As soon as the stable version 1.0 of Android Studio was released, Google retired the Android Developer Tools (ADT) for Eclipse and recommended all developers to switch to Android Studio. This means that Google will not provide new features for Eclipse anymore, and all IDE-related tool development is now focused on Android Studio. If you are still using Eclipse, it is time to change if you do not want to be left behind.

This screenshot shows what Android Studio looks like for a simple Android app project:

Android Studio

Staying up to date

There are four different update channels for Android Studio:

  • Canary brings bleeding-edge updates, but might contain some bugs
  • The Dev channel gets an update more or less every month
  • Beta is used feature complete updates that might still contain bugs
  • The Stable channel, which is the default, features thoroughly tested releases that should be bug-free

By default, Android Studio checks every time it starts if there any updates available and notifies you.

When you launch Android Studio for the first time, it starts a wizard to set up your environment and to make sure you have the latest Android SDK and the necessary Google repositories. It also gives you the option to create an Android Virtual Device (AVD), so you can run apps on the emulator.

Understanding Gradle basics

In order for an Android project to be built using Gradle, you need to set up a build script. This will always be called build.gradle, by convention. You will notice, as we go through the basics, that Gradle favors convention over configuration and generally provides default values for settings and properties. This makes it a lot easier to get started with a lot less configuration than that found in systems such as Ant or Maven, which have been the de facto build systems for Android projects for a long time. You do not need to absolutely comply with these conventions though, as it is usually possible to override them if needed.

Gradle build scripts are not written in the traditional XML, but in a domain-specific language (DSL) based on Groovy, a dynamic language for 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 using the more procedural, free-floating style of Ant, or any XML-based approach used by many other build systems.

That does not mean you need to know Groovy to get started with your build scripts. It is easy to read, and if you already know Java, the learning curve is not that steep. If you want to start creating your own tasks and plugins (which we will talk about in later chapters), it is useful to have a deeper understanding of Groovy. However, because it is based on the JVM, it is possible to write code for your custom plugins in Java or any other JVM-based language.

Projects and tasks

The two most important concepts in Gradle are projects and tasks. Every build is made up of at least one project, and every project contains one or more tasks. Every build.gradle file represents a project. Tasks are then simply defined inside the build script. When initializing the build process, Gradle assembles Project and Task objects based on the build file. A Task object consists 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, in its simplest form, just executing actions on tasks, which are dependent on other tasks. To simplify the build process, the build tools create a dynamic model of the workflow as a Directed Acyclic Graph (DAG). This means all the tasks are processed one after the other and loops are not possible. Once a task has been executed, it will not be called again. Tasks without dependencies will always be run before the others. The dependency graph is generated during the configuration phase of a build. A Gradle build has three phases:

  • Initialization: This is where the Project instance is created. If there are multiple modules, each with their own build.gradle file, multiple projects will be created.
  • Configuration: In this phase, the build scripts are executed, creating and configuring all the tasks for every project object.
  • Execution: This is the phase where Gradle determines which tasks should be executed. Which tasks should be executed depends on the arguments passed for starting the build and what the current directory is.

The build configuration file

In order to have Gradle build a project, there always needs to be a build.gradle file. A build file for Android has a few required elements:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

This is where the actual build is configured. In the repositories block, the JCenter repository is configured as a source of dependencies for the build script. JCenter is a preconfigured Maven repository and requires no extra setup; Gradle has you covered. There are several repositories available straight from Gradle and it is easy to add your own, either local or remote.

The build script block also defines a dependency on Android build tools as a classpath Maven artifact. This is where the Android plugin comes from. The Android plugin provides everything needed to build and test applications. Every Android project needs to apply the Android plugin using this line:

apply plugin: 'com.android.application'

Plugins are used to extend the capabilities of a Gradle build script. Applying a plugin to a project makes it possible for the build script to define properties and use tasks that are defined in the plugin.

Note

If you are building a library, you need to apply 'com.android.library' instead. You cannot use both in the same module because that would result in a build error. A module can be either an Android application or an Android library, not both.

When using the Android plugin, Android-specific conventions can be configured and tasks only applicable to Android will be generated. The Android block in the following snippet is defined by the plugin and can be configured per project:

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
}

This is where the Android-specific part of the build is configured. The Android plugin provides a DSL tailored to Android's needs. The only required properties are the compilation target and the build tools. The compilation target, specified by compileSdkVersion, is the SDK version that should be used to compile the app. It is good practice to use the latest Android API version as the compilation target.

There are plenty of customizable properties in the build.gradle file. We will discuss the most important properties in Chapter 2, Basic Build Customization, and more possibilities throughout the rest of the book.

The project structure

Compared to the old Eclipse projects, the folder structure for Android projects has changed considerably. As mentioned earlier, Gradle favors convention over configuration and this also applies to the folder structure.

This is the folder structure that Gradle expects for a simple app:

MyApp
├── build.gradle
├── settings.gradle
└── app
    ├── build.gradle
    ├── build
    ├── libs
    └── src
        └── main
            ├── java
            │   └── com.package.myapp
            └── res
                ├── drawable
                ├── layout
                └── etc.

Gradle projects usually have an extra level at the root. This makes it easier to add extra modules at a later point. All source code for the app goes into the app folder. The folder is also the name of the module by default and does not need to be named app. If you use Android Studio to create a project with both a mobile app and an Android Wear smartwatch app, for example, the modules are called application and wearable by default.

Gradle makes use of a concept called source set. The official Gradle documentation explains that a source set is a group of source files, which are compiled and executed together. For an Android project, main is the source set that contains all the source code and resources for the default version of the app. When you start writing tests for your Android app, you will put the source code for the tests inside a separate source set called androidTest, which only contains tests.

Here is a short overview of the most important folders of an Android app:

Directory

Content

/src/main/java

The source code for the app

/src/main/res

These are app-related resources (drawables, layouts, strings, and so on)

/libs

These are external libraries (.jar or .aar)

/build

The output of the build process

Creating a new project

You can start a new project in Android Studio by clicking on Start a new Android Studio project on the start screen or by navigating to File | New Project… in the IDE itself.

Creating a new project in Android Studio starts with a wizard that helps set everything up. The first screen is for setting up the application name and the company domain. The application name is the name that will be used as the name of the app when it is installed and is used as the toolbar title by default. The company domain is used in combination with the application name to determine the package name, which is the unique identifier for any Android app. If you prefer a different package name, you can still change it by clicking on Edit. You can also change the location of the project on your hard drive.

Creating a new project

No files are generated before going through all the steps in the wizard, because the next few steps will define which files need to be created.

Android does not only run on phones and tablets, but also supports a broad range of form factors, such as TV, watches, and glasses. The next screen helps you set up all the form factors you want to target in your project. Depending on what you choose here, dependencies and build plugins are included for development. This is where you decide if you just want to make a phone and tablet app or whether you also want to include an Android TV module, an Android Wear module, or a Google Glass module. You can still add these later, but the wizard makes it easy by adding all the necessary files and configurations. This is also where you choose what version of Android you want to support. If you select an API version below 21, the Android Support Library (including the appcompat library) is automatically added as a dependency.

Creating a new project

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The following screen suggests adding an activity and provides a lot of options, all of which result in generated code that makes it easier to get started. If you choose to have Android Studio generate an activity for you, the next step is to enter a name for the activity class, the layout file and the menu resource, and also to give the activity a title:

Creating a new project

After you go through the entire wizard, Android Studio generates source code for an activity and a fragment, depending on the choices you made during the wizard. Android Studio also generates the basic Gradle files to make the project build. You will find a file called settings.gradle and one called build.gradle on the top level of the project. Inside the app module folder, there is another build.gradle file. We will go into more detail about the content and the purpose of these files in Chapter 2, Basic Build Customization.

You now have several options to trigger a build from inside Android Studio:

  • Inside the Build menu, you can click on Make Project, or you can use the keyboard shortcut, which is Ctrl + F9 on a PC and Cmd + F9 on Mac OS X
  • The toolbar has a shortcut for the same Make Project
  • The Gradle tool window, which lists all the available Gradle tasks

In the Gradle tool window, you can try to execute assembleDebug to build, or installDebug to install the app on a device or emulator. We will discuss these tasks in the next part of this chapter, which deals with the Gradle wrapper.

Left arrow icon Right arrow icon

Description

If you are an experienced Android developer wanting to enhance your skills with the Gradle Android build system, then this book is for you. As a prerequisite, you will need some knowledge of the concepts of Android application development.

Who is this book for?

If you are an experienced Android developer wanting to enhance your skills with the Gradle Android build system, then this book is for you. As a prerequisite, you will need some knowledge of the concepts of Android application development.

What you will learn

  • Build new Android apps and libraries using Android Studio and Gradle
  • Migrate projects from Eclipse to Android Studio and Gradle
  • Manage the local and remote dependencies of your projects
  • Create multiple build variants
  • Include multiple modules in a single project
  • Integrate tests into the build process
  • Create custom tasks and plugins for Android projects

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 17, 2015
Length: 172 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986828
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 17, 2015
Length: 172 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986828
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 142.97
Gradle for Android
$38.99
Learning Android Application Testing
$54.99
Mastering Gradle
$48.99
Total $ 142.97 Stars icon

Table of Contents

10 Chapters
1. Getting Started with Gradle and Android Studio Chevron down icon Chevron up icon
2. Basic Build Customization Chevron down icon Chevron up icon
3. Managing Dependencies Chevron down icon Chevron up icon
4. Creating Build Variants Chevron down icon Chevron up icon
5. Managing Multimodule Builds Chevron down icon Chevron up icon
6. Running Tests Chevron down icon Chevron up icon
7. Creating Tasks and Plugins Chevron down icon Chevron up icon
8. Setting Up Continuous Integration Chevron down icon Chevron up icon
9. Advanced Build Customization Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(3 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Amazon Customer Dec 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book with clear examples.I am definitely considering purchasing more books from this publisher.This book is great for anyone with Multi module pre-reqs, multi-flavor demands, CI requirements.Great! Great! Great!
Amazon Verified review Amazon
laurynas Aug 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Recommended to android professionals.
Amazon Verified review Amazon
Peter Theill Aug 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book. I've tried to get started with Gradle but it wasn't until I read this book I managed to setup my apps properly. The book gives a great introduction and further expands with some very nice cases to setup a world class build system.Highly recommended.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.