Skip to content

Gradle-Jenkins story in Android

Published: at 15 min read

Table of contents

Open Table of contents

Explore about Build Tool

buildTool

Examples of Build Tools : Ant, Maven, Gradle, and NAnt, Make, CMake, npm etc

Purposes of Build Tools

  1. Compilation: Build tools compile source code into executable code or machine-readable instructions (e.g., bytecode).

  2. Dependency Management: Build tools manage project dependencies, including libraries, frameworks, and external modules.

  3. Automated Testing: Run automated tests (e.g., unit tests, integration tests, and acceptance tests) to verify the correctness and quality of the software.

  4. Packaging: They package the compiled code and resources into deployable artifacts, such as executable files, JAR files, WAR files, or APK files, depending on the platform and technology stack.

  5. Versioning: Build tools can automatically generate version numbers or timestamps for the built artifacts for proper versioning and tracking of software releases.

  6. Optimization: To improve performance and reducing final distribution size, some build tools perform code optimization and resource compression.

  7. Documentation Generation: Build tools can generate documentation from code comments or documentation files, helping developers maintain up-to-date documentation for their projects.

  8. Continuous Integration (CI) and Continuous Deployment (CD): Build tools are often integrated with CI/CD pipelines to automate the build and deployment processes whenever changes are pushed to version control repositories.

What is Groovy

What is Maven

Lighten the word - Gradle

gradle

Gradle - Features

Gradle is an open-source project, and it is licensed under the Apache Software License (ASL).

Following are some of the features:

The Gradle Wrapper allows to execute Gradle builds on machines where Gradle is not installed.

Advantages of Gradle over Maven

Gradle and Maven are both popular build automation tools used in software development, especially in the Java ecosystem.

  1. Groovy and Kotlin DSL Support: Gradle allows build scripts to be written in either Groovy or Kotlin, providing more flexibility and expressiveness compared to Maven’s XML-based POM files.

  2. Performance: Gradle is known for its highly optimized, improved performance, handling large multi-module projects. It only rebuilds if a changes has happened since the last build and significantly speed up the build process.

  3. Dynamic Dependency Resolution: Gradle can resolve and download dependencies at runtime based on specific configurations and which is useful for managing different build variants or flavours.

  4. Gradle Wrapper: Gradle includes a “wrapper” feature, which allows to specify the Gradle version for the project ensuring that all team members are using the same Gradle version, reducing compatibility issues.

  5. Integrated Testing Framework: Gradle provides an integrated testing framework (Gradle TestKit) for writing and running tests against build logic.

Gradle Configuration Files

The Gradle build has the following three configuration files:

  1. The Gradle build script (build.gradle) specifies a project and its tasks.

  2. The Gradle properties file (gradle.properties) is used to configure the properties of the build.

  3. The Gradle Settings file (settings.gradle) is optional in a build which has only one project. If Gradle build has more than one project, it is necessary as it explains which projects engage to the build. Each multi-project build should include a settings file in the project hierarchy’s root project.

build.gradle :

Gradle Plugins

A Gradle plugin works as an extension to Gradle. It extends the project’s capabilities when applied to a project. Gradle comes with several plug-ins, and one can create custom plug-ins.

Example: Java plug-in adds tasks to a project that permits to create a JAR file, run unit tests and compile Java source code.

Example: The entry apply plugin:‘com.android.application’ makes the Android plug-in available for a Gradle build.

Gradle also provides a registry for plug-ins via https://plugins.gradle.org/

Types of Plugin

Script Plugins :

Script plugins are an effective way to modularize and share common build logic and configurations across multiple projects or modules. They help keep build scripts clean, promote consistency, and reduce the need to duplicate code in multiple build.gradle files.

  1. They are additional build scripts.
  2. They follow a declarative approach to manipulate the build.
  3. They are applied from a script on the local filesystem or at a remote location.

Example: Applying a script plugin

apply from: 'other.gradle'

Binary Plugins :

In Gradle, a “binary plugin” typically refers to a plugin that provides binary artifacts for use in other projects, such as libraries, frameworks, or executables. Binary plugins are distributed as JAR files or other binary artifacts, and they can be applied to Gradle projects to extend their functionality.

  1. They are classes that implement the plugin interface.
  2. They follow a programmatic approach to manipulate the build.
  3. They occupy within a build script/project hierarchy/externally in a plugin jar.

Example: Applying a binary plugin

apply plugin: 'java'

Applied using a unique plugin id (in the above case - ‘java’)

Java Plugins :

In Gradle, the Java Plugin is one of the core plugins that provides a set of tasks and configurations for building and managing Java projects. This plugin simplifies the process of compiling Java source code, managing project dependencies, and creating JAR files for distribution.

To work with the Java plugin:

  1. Create a Java source file
  2. Use the tasks of the plugin to build the source file.

Example: Using the Java plugin

apply plugin: 'java'

The above code is included in the build script to use Java plugin. By default, the plugin searches for Java source file in the directory src/main/java, relative to the project directory.

Jenkins - all you want to know

jenkins

Features of Jenkins

  1. Automation: Jenkins allows developers to automate repetitive tasks, such as building code, running tests, and deploying applications, reducing the human error and saves time.

  2. Integration: Jenkins integrates with a wide range of version control systems, build tools, testing frameworks, and deployment platforms, making it adaptable to various software development environments.

  3. Plugins: Jenkins offers a rich ecosystem of plugins, covering various use cases, including source code management, build tools, notifications, and reporting.

  4. Continuous Integration (CI): Jenkins supports CI by automatically building and testing code changes as they are committed to version control repositories.

  5. Continuous Delivery (CD): Jenkins can automate the deployment process, enabling continuous delivery of applications to various environments, such as development, staging, and production.

  6. Pipeline as Code: Jenkins provides a feature called “Pipeline as Code” (Jenkinsfile) that allows to define the build and deployment pipelines using code. This approach promotes consistency and reproducibility in your CI/CD processes.

  7. Security: Jenkins offers security features, including user authentication, role-based access control (RBAC), and integration with authentication providers like LDAP and Active Directory.

Workflow of Jenkins

This workflow represents a typical CI/CD pipeline in Jenkins, but the exact steps and configurations can vary depending on the project’s requirements and complexity. Jenkins offers flexibility in defining and customizing these workflows to meet specific needs. Pipeline scripts (Jenkinsfiles) provide a powerful way to describe more complex and customizable workflows in code.

jenkinWorkflow

Step 1 : Version Control Integration -> Developers commit code changes to a version control system (e.g., Git, SVN) hosted on a remote repository server.

Step 2 : Webhook or Polling -> Jenkins can be configured to either poll the version control system at regular intervals or use webhooks to detect changes automatically.

Step 3 : Triggering a build -> When Jenkins detects a code change or is triggered manually, it initiates the build process. This is often the first step in a CI/CD pipeline.

Step 4 : Workspace preparation -> Jenkins creates a workspace for the build, which is a directory where it will perform all build-related operations. This workspace is isolated for each build to prevent interference between different builds.

Step 5 : Build Environment Setup -> Depending on the project’s requirements, Jenkins may set up a build environment that includes the necessary build tools, dependencies, and configurations. This can be achieved using build agents, Docker containers, or virtual machines.

Step 6 : Build Process -> Jenkins executes the build process, which can involve compiling source code, running unit tests, performing code analysis, generating artifacts, and more. The specific tasks depend on the project’s build script or configuration.

Step 7 : Artifact Generation -> If the build is successful, Jenkins generates artifacts such as JAR files, WAR files, or other binaries that are ready for deployment.

Step 8 : Testing -> Jenkins can run automated tests on the built artifacts, including unit tests, integration tests, and end-to-end tests. It records test results and generates reports.

Step 9 : Quality Assurance -> Code quality checks and static code analysis tools can be integrated into the workflow to ensure code quality and compliance with coding standards.

Step 10 : Artifact Archiving and Storage -> Successful build artifacts and test results are archived and stored for future reference and deployments. Jenkins can also publish these artifacts to a repository manager (e.g., Nexus, Artifactory).

Step 11 : Deployment -> Depending on the project’s deployment strategy, Jenkins can automate the deployment of artifacts to different environments, such as development, staging, and production.

Step 12 : Notification and Reporting -> Jenkins can send notifications via email, slack messages and integration with collaboration tools to relevant stakeholders about the build status, test results, and deployment outcomes.

Step 13 : Monitoring Logging and Reporting -> Jenkins provides monitoring capabilities to track build and deployment progress. It also generates logs for debugging and auditing purposes.

Step 14 : Post Build Action -> After the build and deployment are complete, Jenkins can perform additional actions, such as triggering downstream builds, archiving build artifacts, and cleaning up resources.

Step 15 : Pipeline Visualization -> Jenkins provides visualization tools to monitor the progress of the pipeline and see the status of each stage and task.

Jenkins Installation

Jenkins Configuration

Configure the following plugins for Jenkins:

jenkinsConfig

The Jenkins welcome page is shown above.

This adds Gradle build execution capability to the Jenkins server.

To configure these settings:

Create the First Gradle Build Job ~

Jobs are the unit of execution in Jenkins. A build job can perform compilation, run automated tests, package and deployment related tasks.

Steps:

  1. Go to Jenkins home page and click Create new jobs.
  2. Choose a category of jobs (Freestyle project) that can be created in Jenkins.
  3. Type a name for the project and then click OK.

In the next page, the following details have to be configured:

  1. Source code management location to download the project.
  2. Build step for the project.
  3. Schedule the Build task (daily, hourly, after every commit, etc.).
  4. Put in any post build action to perform.

After saving the configurations, the project will be displayed on the dashboard.

Execute Job ~

Gradle - Linking with Android Studio

gradle-android

Android Studio creates :

  1. build.gradle for the parent project
  2. individual build.gradle files for the subprojects.
  3. creates settings.gradle file that includes all the subprojects.

Android Studio also adds Gradle Wrapper. So, Android project can be built on a machine where Gradle is not installed.

The build.gradle file of the app folder is used to build the Android application. The below configurations helps to get build with Gradle.

apply plugin: 'com.android.application'
android {
  compileSdkVersion 34
  buildToolsVersion "22.0.1"

  defaultConfig {
    applicationId "ch10.androidsampleapp"
    minSdkVersion 30
    targetSdkVersion 22
    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:22.1.1'
}

Explanation of gradle file in Android studio

  1. Project-level Gradle File (build.gradle in the project root directory): This Gradle file, located in the root directory of your Android project, configures settings that apply to the entire project. It mainly deals with the Gradle plugin version and repositories.
buildscript {
    repositories {
        google() // Google's Maven repository
        jcenter() // JCenter repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0' // Android Gradle Plugin version
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
  1. Module-level Gradle File (build.gradle in the “app” module directory): This Gradle file, located in the “app” module directory (e.g., app/build.gradle), configures settings that apply specifically to the Android app module, including dependencies, build types, flavours, and more.
apply plugin: 'com.android.application'
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 16
        targetSdkVersion 30
        // ...
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    // ...
}
dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    // ...
}

One can customize both build and release build types and also extend the build types by adding your own build types, as follows:

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

  staging.initWith(buildTypes.release)
  staging {
    debuggable true
  }

  productFlavors {
        free {
            // Flavor-specific configurations
        }
        paid {
            // Flavor-specific configurations
        }
    }
}

In this above example, one more build type staging is added and configured it to be a copy of the release build type and added debuggable true.

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

Summary

Gradle has become the standard build tool for Android app development, and many Android projects use Gradle for managing dependencies, building APKs, and customizing build processes. Gradle’s flexibility and extensibility make it a powerful choice for a wide range of software projects beyond Android development as well.

Share :
Written by:Parita Dey

Interested in Writing Blogs, showcase yourself ?

If you're passionate about technology and have insights to share, we'd love to hear from you! Fill out the form below to express your interest in writing technical blogs for us.

If you notice any issues in this blog post or have suggestions, please contact the author directly or send an email to hi@asdevs.dev.