Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Testing an Android Application with Example
Next article icon

How to Build Android Applications with Gradle?

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

There are several contemporary build automation technologies available nowadays that may be utilized to create a quicker build when creating a project. Gradle is one of these modern-day automation technologies. Gradle is now used by Android to automate and control the build process while also defining flexible custom build settings. As a result, it is required to design or build an Android application utilizing such sophisticated build tools as Gradle. 

So, in this article, we'll learn how to use Gradle to boost our builds. In addition, we will study the fundamental syntax in the build.gradle file created by Android Studio. We will learn about gradlew tasks, build variations, and many other uses later in this blog.

What exactly is Gradle?

Before we continue, let's take a brief look at Gradle. Gradle, a sophisticated build toolkit, is used by Android Studio to automate and control the build process while allowing you to design flexible custom build settings. So, with Gradle, you can build, test, and deploy your application, and the files responsible for this sort of automation are the “Build.gradle” files. Gradle build scripts, for example, may do simple tasks such as copying pictures from one location/directory to another before the real build process begins. Gradle is required for Android projects in order to compile source code and resources.

When you create an Android Project in Android Studio, the build.gradle file is automatically produced, and when you hit the run button in Android Studio, the associated Gradle task is called, and the application is started or launched. When you run your source code in Android Studio, it will be transformed into DEX (Dalvik Executable) files. These DEX files contain the bytecode needed to execute the program on Android. APK Packager is used to bundle multiple DEX files with the application's resources. The APK Packager then signs your APK using either the debug or release Keystore, and before creating your final APK, it optimizes your program to remove unnecessary code.

Create Configuration Files

When you create a new project in Android Studio, it generates several files for you. Let us first define the scope and purpose of these files. A typical Android project's project view is as follows:

  1. The Gradle configuration file: The file settings.gradle may be found in the root directory. It is made up of all of the modules included in the app.
  2. The top-level build file is the build.gradle file, which is stored in the root directory. If you wish to use the same configuration for all modules in your project, declare them in this file.
  3. The module-level build file is as follows: The module-level build.gradle file, which can be found in each project/module/ directory, allows us to define build parameters for the module in which it is placed.
  4. Gradle configuration file: You may define parameters for the Gradle toolkit in the Gradle properties file.

Commands for Gradle

We have already covered the fundamentals of Gradle, and now we will look at some of the Gradle commands that may be used to conduct the build process without using Android Studio, i.e. via the command line. You can open gradle and then use the following commands which will help you.

1. Gradle Wrapper: Gradle is still in development, and a new version might arrive at any time. Gradle Wrapper is used to provide a seamless flow while running Gradle instructions. On Mac OS or Linux, the Gradle Wrapper is a shell script named gradlew, while on Windows, it is a batch file called gradlew.bat. So, if you run this script and the specified version of Gradle is not present, it will download the selected version of Gradle for you. 
If you use Android Studio to build an Android project, this Gradle Wrapper will be generated automatically. If you want to make your own Gradle Wrapper, then download Gradle from here and then execute the following command in your project directory:

$ gradle wrapper --gradle-version x.x

2. gradlew: The Gradle wrapper is gradlew. If you used Android Studio to build the Android project, navigate to the root directory of your project on the command line

This will provide a list of things you can perform using Gradle:

> Task :help Welcome to Gradle 5.1.1. To run a build, run gradlew <task> ... To see a list of available tasks, run gradlew tasks To see a list of command-line options, run gradlew --help To see more detail about a task, run gradlew help --task <task> For troubleshooting, visit https://help.gradle.org

3. gradlew responsibilities: This is used to display a list of available jobs. In the command line, type the following command:

> Task :tasks ----------------------------------------------------------- Tasks runnable from root project ----------------------------------------------------------- Android tasks ------------- androidDependencies - Displays the Android dependencies of the project. signingReport - Displays the signing info for the base and test modules sourceSets - Prints out all the source sets defined in this project.  Build tasks ----------- assemble - Assemble main outputs for all the variants. assembleAndroidTest - Assembles all the Test applications. build - Assembles and tests this project. buildDependents - Assembles and tests this project and all projects that depend on it. buildNeeded - Assembles and tests this project and all projects it depends on. bundle - Assemble bundles for all the variants. clean - Deletes the build directory. cleanBuildCache - Deletes the build cache directory. compileDebugAndroidTestSources compileDebugSources compileDebugUnitTestSources compileReleaseSources compileReleaseUnitTestSources  Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files.

4. gradlew lint: The gradlew lint command is used to discover errors across the project, i.e. it will look for different errors, typos, and vulnerabilities. When you are at the root of your project, you can use all these commands

> Task :app:lint Ran lint on variant debug: 30 issues found Ran lint on variant release: 102 issues found Wrote HTML report to file: Wrote XML report to file:

5. gradlew build: To build your project, execute the following command in your root directory:

$ ./gradlew build

6. gradlew clean build: You may use this command to clear and obfusticate your code the build will be rewritten from the ground up.

$ ./gradlew clean build 

7. gradlew examination: Use the following command to perform the application test:

$ ./gradlew test

Other Gradle Characteristics

Gradle, in addition to being useful on command lines, has a plethora of other capabilities. Some of these are as follows:

Manage dependencies version: In a multi-module project, a number of dependencies are utilized, and the most common issue that emerges, as a result, is a conflict in the version of the dependencies, i.e. only if you have the dependency of the server then only they will run. The versions of these dependencies are tough to maintain, however, Gradle provides an ext block where we can declare our common property values and utilize them in dependencies.

apply plugin: 'com.android.application'          android {     defaultConfig{...}     buildTypes{...}     ProductFlavours{...} }  ext {     supportLibraryVersion = '28.1.0'  }  dependencies {     // android supported libraries     implementation "com.android.support:appcompat-v7:$supportLibraryVersion"     implementation "com.android.support:design:$supportLibraryVersion"     implementation "com.android.support:cardview-v7:$supportLibraryVersion"      // google play service     implementation "com.google.android.gms:play-services:$playServiceVersion"     implementation "com.google.android.gms:play-services-fitness:$playServiceVersion"      // your other project files     }

Build types and build flavors

By default, there are two types of builds in Android: debug and release. These building types are used to generate distinct application variants. We imply by "flavor" that the same program might have distinct features for various users. For example, the premium edition of the software should have different features than the free one. You may use the productFlavors closure in your app level build.gradle file to specify multiple flavors. As an example, consider the following:

productFlavors {     paid {         applicationId = "your app id goes here"         versionName = "1.1-paid"     }
free {         applicationId = "your app id"         versionName = "1.0-free"     } }

Creating tasks

As we've seen, the./gradlew tasks command may be used to retrieve a list of available tasks. However, we may also construct our own tasks. For example, we might write a task that instructs Gradle to generate an APK file with the build date in its name. To do so, add the following code to your module-level build.gradle file:

Java
task postTopic() {     android.seeAllVariants.all { here ->         here.outputs.all { output ->             def gfg = new Date().format("dd-yyyy")             def geeksforgeeks = here.name + "_" + date + ".apk"             output.finalName = last         }     } } 

We have one job here called postTopic(), and you are creating a new filename by appending the variable and the build date to it.

Conclusion

We learned how to utilize Gradle in our Android project in this article. We learned several Gradle commands. The whole set of commands is available on the Gradle website.


Next Article
Testing an Android Application with Example
author
therebootedcoder
Improve
Article Tags :
  • Android

Similar Reads

  • How to Build a Photo Viewing Application in Android?
    Gallery app is one of the most used apps which comes pre-installed on many Android devices and there are several different apps that are present in Google Play to view the media files present in your device. In this article, we will be simply creating a Gallery app in which we can view all the photo
    8 min read
  • How to Create a Paint Application in Android?
    We all have once used the MS-Paint in our childhood, and when the system was shifted from desks to our palms, we started doodling on Instagram Stories, Hike, WhatsApp, and many more such apps. But have you ever thought about how these functionalities were brought to life? So, In this article, we wil
    8 min read
  • How to Get the Build Version Number of an Android Application?
    Version Name and Version Code in an Android application tell us about the current app version installed on the user's mobile device. This information is generally used when we prompt users to update to the new version of the older version of the application. In this article, we will look at How to g
    3 min read
  • How to Build a Bitcoin Tracker Android App?
    In this article, we will be building a Bitcoin Tracker Project using Java/Kotlin and XML in Android. The application will display the current rates of Bitcoin in different countries using Bitcoin API. There are many free APIs available and for this project, we will be using API by Coinlayer. The API
    8 min read
  • Testing an Android Application with Example
    Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
    5 min read
  • How to Build a Weather App in Android?
    In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components
    6 min read
  • How to Create Google Lens Application in Android?
    We have seen the new Google Lens application in which we can capture images of any product and from that image, we can get to see the search results of that product which we will display inside our application. What are we going to build in this article? We will be building a simple application in w
    10 min read
  • How to Build and Release Flutter Application in Android Device?
    Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), Web apps from a single codebase. When building applications with Flutter everything towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch
    2 min read
  • How to Build a ChatGPT Like Image Generator Application in Android?
    Chat GPT is nowadays one of the famous AI tools which are like a chatbot. This chatbot answers all the queries which are sent to it. In this article, we will be building a simple ChatGPT-like android application in which we will be able to ask any question and from that question, we will be able to
    5 min read
  • How to Send an Email From an Android Application?
    In this article, we will make a basic Android Application that can be used to send email through your android application. You can do so with the help of Implicit Intent with action as ACTION_SEND with extra fields: email id to which you want to send mail,the subject of the email, andbody of the ema
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences