Android

Building Android Applications with Gradle

Gradle is an advanced build system as well as an advanced build toolkit allowing us to create custom build logic through plugins. Gradle can automate our building, testing, deploying tasks and many more and is the next generation build system for Java technologies that includes some advantages from older tools like Ant or Maven systems.

Android Studio uses the power of Gradle, in order to provide all the above advantages, such as build variants and multiple apk file generation.

So, in this example we are going to show some elementary notes regarding building Android applications with Gradle and also how to build and deploy an Android application using the power of Gradle via Android Studio.

For our example will use the following tools in a Windows 64-bit or an OS X platform:

  • JDK 1.7
  • Android Studio 1.3.2
  • Android SDK 5.1

Let’s take a closer look:

1. Goals of the Gradle

The goals of the new build system are:

  • Make it easy to reuse code and resources
  • Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
  • Make it easy to configure, extend and customize the build process
  • Good IDE integration

2. Why to use Gradle?

Here are some of its features that made us choose Gradle:

  • Domain Specific Language (DSL) to describe and manipulate the build logic
  • Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
  • Built-in dependency management through Maven and/or Ivy.
  • Very flexible. Allows using best practices but doesn’t force its own way of doing things.
  • Plugins can expose their own DSL and their own API for build files to use.
  • Good Tooling API allowing IDE integration
  • Let’s see and example now:

    3. Create a New Android Application Project

    Tip
    You may skip project creation and jump directly to the beginning of the example below.

    Open Android Studio and choose “Start a new Android Studio Project” in the welcome screen.

    “Welcome to Android Studio” screen. Choose “Start a new Android Studio Project”.
    “Welcome to Android Studio” screen. Choose “Start a new Android Studio Project”.

    Specify the name of the application, the project and the package.

    “Configure your new project” screen. Add your application name and the projects package name.
    “Configure your new project” screen. Add your application name and the projects package name.

    In the next window, select the form factors your app will run on.

    “Target Android Devices” screen.
    “Target Android Devices” screen.

    In the next window you should choose “Blank Activity”. In our example, we choose to create a project with some basic configuration.

    “Add an activity to Mobile”. Choose: “Blank Activity”.
    “Add an activity to Mobile”. Choose: “Blank Activity”.

    As we can see now, our project has some basic files, such as our value files that contain the strings, the styles and the default dimens. Now, our project has just been created. This is how it looks like in the “Android” project view:

    A new Android Studio project has just been created. This is how it looks like.
    A new Android Studio project has just been created. This is how it looks like.

    4. Creating the layout of the main AndroidGradleExample

    We are going to make a simple layout xml for the AndroidGradleExample.class, that consists of a RelativeLayout that includes a simple TextView.

    Open res/layout/activity_main.xml, go to the respective xml tab and paste the following:

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".AndroidGradleExample">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world"
            android:textColor="@color/textcolor_value"
            android:textSize="50dp" />
    
    </RelativeLayout>
    

    5. Creating the source code of the main AndroidGradleExample Activity

    Open java/com.javacodegeeks.androidgradleexample/AndroidGradleExample.java file and paste the code below.

    AndroidGradleExample.java

    package com.javacodegeeks.androidgradleexample;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    
    public class AndroidGradleExample extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_android_gradle_example, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
    

    6. Android Manifest

    The AndroidManifest.xml of our project is simple and contains the permissions:

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.javacodegeeks.androidgradleexample" >
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".AndroidGradleExample"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    
    

    7. Configuring the flavors and the values

    In this example we need to make two flavors of this application. This means that we are going to make two versions, of the same codebase, but with different values, colors, dimensions and text. Imagine that we have a “demo” and a “production” application, that we want to distinguish, with different application id, different versionNames and versionCodes.

    We need now to add two folders in the same level as the main folder, in order to make our build flavor settings. The first folder is the red folder and the second one the green folder. Inside each folder, we should add a new values folder, with slightly different values, for each flavor.In this example we have added different colors and different strings.

    This is how it looks like in the “Project” project view:

    Added "flavor" folders with different values, colors and strings.
    Added “flavor” folders with different values, colors and strings.

    8. Configuring the build.gradle file

    Now, we are going to configure our build.gradle file, in order to successfully deploy and build one application with two different flavors, the “green” and the “red” flavor. Let’s see:

    build.gradle

    apply plugin: 'com.android.application'
    //build.gradle file "adds" the Android plugin to the project//
    
    android {
        compileSdkVersion 22
        //this shows the Android API version that this project is going to be compiled with//
    
        buildToolsVersion "23.0.1"
        //this shows the API your project is targeting.//
    
        defaultConfig {
            applicationId "com.javacodegeeks.androidgradleexample"
            //this shows the default application id that this app is going to have//
    
            minSdkVersion 14
            //this shows the default minimum API that is required for your project//
    
            targetSdkVersion 22
            //this shows the default API your application targets to//
    
            versionCode 1
            //this shows the default application versionCode//
    
            versionName "1.0"
            //this shows the default application versionName//
        }
    
        buildTypes {
            release {
                minifyEnabled false
    
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                //Gradle runs ProGuard during the build process.//
    
            }
        }
    
        signingConfigs {
            //this shows the signing configs, that should be used to sign the package
    
            //here we have two signing configurations, each one for each product flavor
            red {
                storeFile file('/Desktop/my.keystore')
                storePassword "storePassword1"
                keyAlias "keyAlias1"
                keyPassword "keyPassword1"
            }
            green {
                storeFile file('/Desktop/my.keystore')
                storePassword "storePassword2"
                keyAlias "keyAlias2"
                keyPassword "keyPassword2"
            }
        }
    
        productFlavors {
            //this shows the productFlavors, that should be used to sign the package
    
            //here we have two productFlavors
            red {
    
                applicationId "com.javacodegeeks.androidgradleexample.red"
                //this shows the application id that this app is going to have in this productFlavor//
    
                minSdkVersion 9
                //this shows the minimum API that is required for your project in this productFlavor//
    
                targetSdkVersion 23
                //this shows the API your application targets to in this productFlavor//
    
                versionCode 1
                //this shows the application versionCode in this productFlavor//
    
                versionName "1.0"
                //this shows the application versionName in this productFlavor//
            }
    
            green {
                applicationId "com.javacodegeeks.androidgradleexample.green"
                //this shows the application id that this app is going to have in this productFlavor//
    
                minSdkVersion 9
                //this shows the minimum API that is required for your project in this productFlavor//
    
                targetSdkVersion 23
                //this shows the API your application targets to in this productFlavor//
    
                versionCode 2
                //this shows the application versionCode in this productFlavor//
    
                versionName "1.0.1"
                //this shows the application versionName in this productFlavor//
            }
        }
    
        buildTypes {
            release { //Only use the release key on a release buildType
                productFlavors.red.signingConfig signingConfigs.red
                productFlavors.green.signingConfig signingConfigs.green
            }
        }
    
        dependencies {
            //this shows the dependencies for the current module//
    
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:22.2.1'
        }
    }
    

    9. Deploy and build the application

    Now, we are going to build and run the application. In the Build Variant tab in Android Studio we are going to manage which build variant-flavor we want to deploy and run in our device. If we choose the “greenDebug” we are going to deploy the “green” version in a debug mode.

    The "green" flavor is going to be built.
    The “green” flavor is going to be built.

    So, in our device will have something like this:

    This is the "green" application, with the "green" build variant.
    This is the “green” application, with the “green” build variant.

    But if we want to choose the “redDebug” we are going to deploy the “red” version in a debug mode.

    The "red" flavor is going to be built.
    The “red” flavor is going to be built.

    And in our device will have something like this:

    This is the "red" application, with the "red" build variant.
    This is the “red” application, with the “red” build variant.

    10. Download the Android Studio Project

    This was an example of Android AndroidGradleExample project.

    Download
    You can download the full source code of this example here: AndroidGradleExample

Chryssa Aliferi

Chryssa is a Computer Science graduate from Athens University of Economic and Business. During her studies, Chryssa carried out a great variety of projects ranging from networking to software engineering. She is very keen on front end development especially on mobile technologies and web applications. She has worked as a junior Software Engineer in the telecommunications area and currently works as an Android Developer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button