An advance build toolkit Gradle in Android Part-1


Most of the time we don’t care about the Gradle files. We only add dependencies, modify target and minimum API levels, signing configuration or build types. For complicated thing we just end up copy-pasting mysterious snippets from some website, without understanding how actually they work. So this is the post to understand very basic level of Gradle configuration for a single Android project.

What is build tool?

Build tools are programs that automates and manage the build process like creation of executable applications from source code (.apk), linking and downloading the resources etc.

In other words build automation is the act of scripting or automating a wide variety of tasks like

-        Compiling source code into binary code
-        Downloading dependencies
-        Packaging the binary code
-        Execute test cases


Available build tools

There are various popular build tools available. Some of them are as follows-
Ant, Maven, Gradle, MSBuild, Rake, NAnt etc.

You can find more details here.


How to use?

Android studio wraps the Gradle runtime, hence no additional installation is required so when you create a new project in Android studio, the Gradle build scripts are automatically created and when you run application, Android Studio triggers the corresponding Gradle task.

Gradle wrapper

You can also use a wrapper script created by Gradle. This allows you to run a Gradle build without required any additional installation from the command line.


Gradle command line

To run Gradle from the command line you must have installed Gradle or you use the Gradle wrapper (gradlew) to execute the build. The wrapper downloads Gradle if necessary. Gradle can run multiple tasks with a single command by providing the names of all the tasks to run. The names of the tasks to run should be separated by a space. Below are the some of the common tasks-

Build project (assemble and check task both)
./gradlew build

Clean and build project
./gradlew clean

Clean and build project
./gradlew clean build

Run test cases
./gradlew test

To see all available tasks, use the command-
gradlew wrapper


Gradle Settings File

The settings.gradle file, located in the root project directory. Here you can define which modules to include when building your app like-
include ‘:app’ , ‘:module1’, ‘:module2


Top (project) level build file

The top-level build.gradle file, located in the root project directory, defines build configurations that apply to all modules in your project.

/**

 * The buildscript block is where you configure the repositories and

 * dependencies for Gradle itself--meaning, you should not include dependencies

 * for your modules here. For example, this block includes the Android plugin for

 * Gradle as a dependency because it provides the additional instructions Gradle

 * needs to build Android app modules.

 */

buildscript {

    /**
     * The repositories block configures the repositories Gradle uses to
     * search or download the dependencies. Gradle pre-configures support for remote
     * repositories such as JCenter, Maven Central, and Ivy. You can also use local
     * repositories or define your own remote repositories. The code below defines
     * JCenter as the repository Gradle should use to look for its dependencies.
     */

    repositories {
        jcenter()
    }

    /**
     * The dependencies block configures the dependencies Gradle needs to use
     * to build your project. The following line adds Android plugin for Gradle
     * version 2.3.0 as a classpath dependency.
     */

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
    }
}


/**
 * The allprojects block is where you configure the repositories and
 * dependencies used by all modules in your project, such as third-party plugins
 * or libraries. Dependencies that are not required by all the modules in the
 * project should be configured in module-level build.gradle files. For new
 * projects, Android Studio configures JCenter as the default repository, but it
 * does not configure any dependencies.
 */

allprojects {
   repositories {
       jcenter()
   }
}


Module level Build File

The module-level build.gradle file, located in each project/module/ directory. It allows you to customize your build configuration for the specific module.

/**
 * The first line in the build configuration applies the Android plugin for
 * Gradle to this build and makes the android block available to specify
 * Android-specific build options.
 */

apply plugin: 'com.android.application'

/**
 * The android block is where you configure all your Android-specific
 * build options.
 */

android {
  /**
   * compileSdkVersion specifies the Android API level Gradle should use to
   * compile your app. This means your app can use the API features included in
   * this API level and lower.
   *
   * buildToolsVersion specifies the version of the SDK build tools, command-line
   * utilities, and compiler that Gradle should use to build your app. You need to
   * download the build tools using the SDK Manager.
   */

  compileSdkVersion 25
  buildToolsVersion "25.0.3"

  /**
   * The defaultConfig block encapsulates default settings and entries for all
   * build variants, and can override some attributes in main/AndroidManifest.xml
   * dynamically from the build system. You can configure product flavors to override
   * these values for different versions of your app.
   */

  defaultConfig {
    /**
     * applicationId uniquely identifies the package for publishing.
     * However, your source code should still reference the package name
     * defined by the package attribute in the main/AndroidManifest.xml file.
     */

    applicationId 'com.example.myapp'

    // Defines the minimum API level required to run the app.
    minSdkVersion 15

    // Specifies the API level used to test the app.
    targetSdkVersion 25

    // Defines the version number of your app.
    versionCode 1


    // Defines a user-friendly version name for your app.
    versionName "1.0"

  }


  /**
   * The buildTypes block is where you can configure multiple build types.
   * By default, the build system defines two build types: debug and release. The
   * debug build type is not explicitly shown in the default build configuration,
   * but it includes debugging tools and is signed with the debug key. The release
   * build type applies Proguard settings and is not signed by default.
   */

  buildTypes {

    /**
     * By default, Android Studio configures the release build type to enable code
     * shrinking, using minifyEnabled, and specifies the Proguard settings file.
     */
    release {
        minifyEnabled true // Enables code shrinking for the release build type.
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

  /**
   * The productFlavors block is where you can configure multiple product
   * flavors. This allows you to create different versions of your app that can
   * override the defaultConfig block with their own settings. Product flavors are
   * optional, and the build system does not create them by default. This example
   * creates a free and paid product flavor. Each product flavor then specifies
   * its own application ID, so that they can exist on the Google Play Store, or
   * an Android device, simultaneously.
   */

  productFlavors {
    free {
      applicationId 'com.example.myapp.free'
    }

    paid {
      applicationId 'com.example.myapp.paid'
    }
  }


  /**
   * The splits block is where you can configure different APK builds that
   * each contain only code and resources for a supported screen density or
   * ABI. You'll also need to configure your build so that each APK has a
   * different versionCode.
   */

  splits {
    // Settings to build multiple APKs based on screen density.
    density {

      // Enable or disable building multiple APKs.
      enable false

      // Exclude these densities when building multiple APKs.
      exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi"

    }
  }
}


/**
 * The dependencies block in the module-level build configuration file
 * only specifies dependencies required to build the module itself.
 */

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


Properties Files

Properties are a valuable tool for easily customizing Gradle builds and its environment. Gradle has two properties files, located in your root project directory.

gradle.properties
Here you can configure project-wide Gradle settings like Gradle daemon's maximum heap size.

local.properties
Configures local environment properties for the build system, such as the path to the SDK or NDK installation.

This article is more focused on basic understanding of Gradle. You can also refer Android official site for more details. I will soon come up with more customizable build configuration feature. So stay tune with me.

To find more interesting topics on Software development follow me at https://medium.com/@ankit.sinhal



Comments

Post a Comment

Popular posts from this blog

Android Performance: Avoid using ENUM on Android

Android O: Impact On Running Apps And Developer Viewpoint

Smart way to update RecyclerView using DiffUtil