Gradle Tutorial : Part 6 : Android Studio + Gradle

Welcome to Part 6 of the Gradle Tutorial. In the previous episode i.e. Part 5, we took a look at building / running / deploying App Engine Java Web Applications via Gradle.

LAST UPDATE : January 22, 2015 :
i) Updated Screenshots for latest version of Android Studio 1.0.2
ii) Updated app/build.gradle as per the latest version of Android Studio 1.0.2

In this part of the tutorial, we shall take our first look at Android Studio and understand the Gradle environment in Android Studio. Since you are now aware of the basics of single, multiple Java projects with Gradle, it should become a bit easier to understand what they generate for you.

Along the way, we shall also take a look at various tabs, configuration settings and the terminal inside of Android Studio, so that you can opt to run gradle via the command line/terminal even inside of Android Studio. This will help you use the knowledge that you have gained so far.

Our goal in this episode will only be to familiarize ourselves with the Gradle environment inside Android Studio. It is by no means expected to be an Android tutorial.

as_plus_gradle

This part assumes that you have installed Android Studio on your development machine and that you are familiar with basic Gradle commands, project structure and files as we have seen in the series so far.

I have used Android Studio 1.0.2 on Windows for this blog post. It is not necessary to have the same version or the OS, things should be pretty much similar from a Gradle perspective.

The points that we shall cover in this blog post are as follows:

  • Project Template Gradle Configuration Settings in Android Studio
  • Generate a basic Android Application and understand Project specific settings for Gradle
  • Understand Gradle Project build files generated for a basic Android Application
  • Look at various windows Tabs available for working with Gradle. For e.g. Gradle, Gradle Console and Terminal window tabs.
  • Look at how we can add more dependencies to our Android Project

Project Template Gradle Settings

Go ahead and launch Android Studio. Close all the Projects in case a default one opens up. This should bring you to the Quick Start window that you see below.

part6-1

The Configure option that you see below is an important one and helps you configure almost anything in the Android Studio IDE. And that includes some global Gradle settings. Click on Configure. 

This will bring you to the Configure options as shown below. Some of these will be recognizable now. For e..g the SDK Manager, that allows you to download the required Android SDK libraries. Click on Settings as shown below:

gradle-ep6-2

 

This will bring up the Settings window and you will see a Gradle option as highlighted below. Do not worry about the Linked Gradle Projects, which is empty, once we create a project things will get linked but for now, ignore it.

part6-2

 

Over here you see some global settings as follows:

  • Offline work : If you check this option, Gradle will use things from the cache itself for dependency resolution. In case the files are not there in the cache, then it will result in a build error.
  • The Service Directory Path is the default Gradle Home directory. This is where the cache is maintained, etc.
  • Gradle VM Options can be used to tweak some JVM Settings and/or provide some property files.

Do not worry too much about this but be aware of the Offline setting. This can cause some heartburn in case you have checked it i.e. enabled offline and then after adding some dependency, Gradle is not able to resolve it since it is going to look into the cache itself.

Android Application

All right, lets go ahead and generate our Android Application. We are going to be using the Android Studio Wizard to do that. Nothing fancy.

Click on Start a new Android Studio project in the Quick Start dialog. This should bring up the New Project wizard as shown below. I have stuck to tradition and called my project HelloWorldAndroid 🙂

part6-3

Just take all the defaults as shown in the next screens for the wizard.

gradle-ep6-5

gradle-ep6-6

part6-4

Click on Finish to end the wizard and then it weaves some magic to generate the Android Studio project files for you. Be a bit patient.

Gradle Project Files

The Project is now created and is opened up in Android Studio. Go to File -> Settings and this should bring up the Project settings dialog as shown below:

gradle-ep6-8

This looks similar to the Project Template dialog that we saw earlier. Except that the Project (HelloWorldAndroid) has got linked and there are additional Project-level settings that have got added. I suggest that you stick to the default ones. For e.g. there is a default Gradle distribution that is already shipped and linked up in your project, so that you do not need to separately go ahead and download Gradle and set it up. Choose this in most scenarios.

However, if you wish to be very specific and have requirements that require you to use your own Gradle build, then do provide the local gradle distribution. Click on the Gradle home selector option and point it to the root of your Gradle distribution.

For most of us, the default Gradle Wrapper is recommended and it will suit our needs.

Now, take a look at the Project Files that have got generated. You should have a similar screenshot that I have put below. I have highlighted the Gradle specific files for you to take a look at:

gradle-ep6-9

 

Let us go over these now. The files circled in green are the default gradle wrapper files that you can use from the terminal / command window (we shall see that in a while). They are nothing but a way for the IDE and yourself to launch gradle on your own anytime. We will look at it a little later in this post, but keep in mind that they are the files to run gradle.

In Part 3, we had covered multiple Java projects and how at the root folder, we can specify the settings.gradle and build.gradle files that apply across all the modules. Android Studio follows the same convention. 

In short, what we have is an Android Project and a module (app) inside of it. That module is an Android application that will need to be built as per Android rules and would need the Android Gradle plugin. Simple enough , isn’t it ?

So, let us look at the settings.gradle file at the root:

include ':app'

It includes just the app module, which is how we had seen in Part 3 of this series.

Take a look at the build.gradle file at the root:

// Top-level build file where you can add configuration options 
// common to all sub-projects/modules.

buildscript {
 repositories {
   jcenter()
 }

dependencies {
 classpath 'com.android.tools.build:gradle:1.0.0'

// NOTE: Do not place your application dependencies here; they 
// belong in the individual module build.gradle files
 }
}

allprojects {
  repositories {
    jcenter()
  }
}

This should be understandable too. For allprojects, we are specifying the repository to be used. JCenter is another repository similar to MavenCentral that we had seen earlier. Additionally, we had seen in the earlier episode, how buildscript can be used to specify what is going to be needed to run the script itself. At that time, we had included the App Engine Plugin/SDK and now we have the Gradle library for the Android Tools Project.

Let us now, step inside of the app module. There you will find the module specific build.gradle that is shown below. Remember it is an Android app, so it will utilize the Android plugin and have Android plugin specific closures that make sense when compiling, building , running, packaging the Android application.

The app/build.gradle file is shown below:

apply plugin: 'com.android.application'

android {
  compileSdkVersion 21
  buildToolsVersion "21.1.2"

  defaultConfig {
     applicationId "com.mindstorm.helloworldandroid"
     minSdkVersion 19
     targetSdkVersion 21
     versionCode 1
     versionName "1.0"
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
    }
 }

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile 'com.android.support:appcompat-v7:21.0.3'
}

Some of the important points are:

  • We specify the use of the Android plugin via the apply plugin command
  • Take a look at dependencies closure that we have seen earlier. Currently it simply adds all the JAR Files that you might add to the libs folder. Alternately, you can also add more of your dependencies here as we have seen earlier.
  • The android closure is a standard one that is used for specifying which SDK version to use for compiling, the minimum SDK Version supported, package name, versioning information and pro Guard related stuff. If you have built Android applications, this will be familiar. If not, you need to do a 101 course on Android Development and this stuff will be clear to you.

That’s about it really as far as the Gradle stuff is concerned. You can see easily that it you have dependencies on other JARs, simply drop them into your libs folder. Alternately, you can add to the dependencies closure by specific repository entries for your dependent files.

Gradle Tasks

On the extreme right side of Android Studio, you will find a vertical navigation bar, which has tabs like Maven Projects, Gradle and Commander.

Go ahead and click on the Gradle tab in that navigation bar. You will be presented with the Project -> Module -> All the Gradle tasks that come under this project. Just like how you do a gradle tasks to determine what are the tasks available for the project, this window basically has done that for you and shows you the tasks available.

gradle-ep6-10

 

 

You do need to refer to the documentation for the respective plugin since it will have information on all the tasks and what they can do.

To execute any of the tasks, without the hassle of going to the terminal and execute it, simply double click on the tasks and it will start executing. And the output is what will be visible in the Gradle console, that we shall see next.

Gradle Console

The Gradle console is tucked away in at the right bottom corner. Simply click on it, to bring it up and you shall see a output from Gradle tasks/commands as they are being executed. As a test, you can launch any of the Gradle tasks that we saw earlier via the Gradle Tasks window. Or simply go to the main menu and click on Rebuild Project, Make Project or something like that and it will show you the output from running Gradle.

gradle-ep6-12

This is very handy when you have an error since it is important for you to see what went wrong during the build.

Use the Terminal

Welcome to the Terminal. In the previous episodes, we were running all Gradle stuff directly from the command line or the terminal. The Android Studio developers have made it easier by integrating it within Android Studio itself, so that you do not need to go out.

This is useful , especially if you are perfectly clear on the tasks that you want to launch and prefer launching it yourself rather than some obscure option somewhere on the menu.

gradle-ep6-13

 

To start the Terminal, simply click on the Terminal Option that you will see in the status bar at the bottom. It will launch up a Terminal window for you and the directory will be shown. You can now execute any Gradle tasks. For e.g. since we have mentioned that Gradle wrapper is provided to you by default, notice how I execute the Gradle tool from the command line to display all the tasks. Go ahead and try out a few commands.

See the + sign in the Terminal Window. You can use that to launch multiple terminals and fire different commands from there if you prefer that sort of a developer workflow. For e.g. in a subsequent episode, we shall see how we can use App Engine modules within Android Studio projects and then use two instances of Terminal : one for launching the Development Server and the other for Shutting down the Development Server and so on.

Tip

Typically if you update any of the Gradle files, it is recommended that you click on the Sync Project with Gradle Files option. This will fire off the default task that has been configured for your project. Just make this option your friend.

gradle-ep6-11

Adding Project Dependencies

Finally, a few words on adding additional dependencies in your project. At a high level, there are 2 ways that you can do that:

  1. You can directly modify the build.gradle files and the dependencies closure. Nothing stops you from doing that. These are straight forward files, go ahead and modify them and save them. Once you save your files, do remember the tip above of clicking the Sync Project with Gradle Files.
  2. If you prefer to use the help of a User Interface to fill out the dependencies (either on JARs, Maven Repository JARs or even other modules in the project), you can choose do the following : Right Click on the module (app) and then choose Open Module Settings as shown below:gradle-ep6-14
  3. This will bring up the Dialog as shown below:

    part6-5

    You can notice that you can modify values on any of the Tabs and this will reflect in the build.gradle file accordingly.

  4. Let us specifically look at dependencies. Click on the Dependencies tab. This will show the current values that we have the dependencies closure for the build.gradle file in the app module.

    part6-6

  5. Now, let us look at how to add more dependencies inside of this closure. Simply click on the button. The following options come up:

    part6-7

    a) Library Dependency b) File Dependency and c) Module Dependency. And these are pretty much the different ways of adding dependencies that we have seen in Part 2 and Part 3.

  6. Let us click on Library Dependency. This will bring up the following dialog where we can specify some entry from the central Maven Library or even pick one that we may have locally in our cache. For e.g. Joda Time.gradle-ep6-18
  7. If we click OK, you will find that the dependencies closure of our build.gradle file will be modified accordingly as shown below. The line added is shown in bold.
    dependencies {
    
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:21.0.3'
      compile 'joda-time:joda-time:2.3'
    
    }

    Go ahead and try adding more dependencies either from Maven Repository or even from local files, etc. Remember to always  Sync Project with Gradle Files to kick off the build.

Moving forward

This tutorial helped you understand how Gradle is seamlessly tied into Android Studio and basic understanding of Gradle files, configurations and various tabs.

In the next episode, we shall continue to stay inside of Android Studio. and look at App Engine modules inside of your Android Studio Project.

suggest to read up on the Gradle Plugin User Guide for Android Tools. Since this is the tool that Google wants us to use moving forward for Android Development, it is important to make this user guide your friend.

Till then, Happy Gradling!

References

Advertisements

16 thoughts on “Gradle Tutorial : Part 6 : Android Studio + Gradle

  1. Hi Romin,

    Thanks for the wonderful tutorial.

    I have following queries while developing with android studio 1.1.0

    1.What is the purpose of including “com.android.tools” in the PROJECT top level build.gradle.

    What will happen if we do not include this file ? As far i understand android plugin comes packaged with Android Studio.

    2.Can we not simply use apply plugin: “android” instead of writing the above.

    Is there any specific link where i can find more details on it

    1. Amit — Thanks for the feedback.

      Your question is good and the reason for doing that is “By default, the project-level Gradle file uses buildscript to define the Gradle repositories and dependencies. This allows different projects to use different Gradle versions. Supported repositories include JCenter, Maven Central, or Ivy. This example declares that the build script uses the JCenter repository and a classpath dependency artifact that contains the Android plugin for Gradle version 1.1.0”

      I have taken the above description from the official documentation available here: https://developer.android.com/tools/building/plugin-for-gradle.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s