[android-studio] What is Gradle in Android Studio?

Gradle is a bit confusing to me, and also for any new Android developer. Can anyone explain what Gradle in Android Studio is and what its purpose is? Why is it included in Android Studio?

The answer is


by @Brian Gardner:

Gradle is an extensive build tool and dependency manager for programming projects. It has a domain specific language based on Groovy. Gradle also provides build-by-convention support for many types of projects including Java, Android and Scala.

Feature of Gradle:

  1. Dependency Management
  2. Using Ant from Gradle
  3. Gradle Plugins
  4. Java Plugin
  5. Android Plugin
  6. Multi-Project Builds

DEFINITION:: Gradle can be described a structured building mechanism where it provides a developer the tools and flexibility to manage the resources of a project to create builds that are smaller in size, targeting specific requirements for certain devices of certain configurations


BASIC CONFIGURATIONS

  1. minimumSdk
  2. maximumSdk
  3. targettedSdk
  4. versionCode
  5. versionName

LIBRARIES:: We can add android libraries or any other third party libraries in addition as per requirements easy which was a tedious task earlier. If the library does not fit for the existing project, The developer is shown a log where the person can find a appropriate solution to make changes to the project so that the library can be added. Its just one line of dependency


GENERATING VARIETIES OF BUILDS

Combining build types with build flavours to get varities of build varients

 ====================                         ====================
|     BuildTypes     |                       |   ProductFlavours  |
 --------------------  ====================== --------------------
|  Debug,Production  |      ||       ||      | Paid,Free,Demo,Mock|
 ====================       ||       ||       ==================== 
                            ||       ||
                            VV       VV
 =================================================================
|           DebugPaid, DebugFree, DebugDemo, DebugMock            |
|  ProductionPaid, ProductionFree, ProductionDemo, ProductionMock |
 =================================================================

REDUCING SIZE

Gradle helps in reducing the size of the generated build by removing the unused resources also unused things from integrated libraries


MANAGING PERMISSIONS

We can Specify certain permissions for certain builds by adding certain permissions in certain scenarios based on requirements


BUILDS FOR CERTAIN DEVICES

We can manage generating build for certain devices that include certain densities and certain api levels. This helps in product deployments in app store according to requirements across multiple types of devices


GOOD REFERENCE

Vogella Tutorials


Gradle = Groovy + Cradle Hans Dockter forum comment

The confusion is a bit unnecessary when it could have just been called "Build" or something in Android Studio.

We like to make things difficult for ourselves in the Development community.


Gradle is what makes it possible to automate the building of complex Android projects that involve 10s of thousands of lines of code from multiple sources, projects, libraries, etc. It can conditionally generate multiple optimized APKs based on a plethora of configuration specifications - if you are interested, the other answers provide more details of this aspect of Gradle.

However, if you're new to Android development, Gradle in 99% of cases is what stops your project from building. It is an inscrutable, complex system that effectively obfuscates the Android build process and essentially renders it unavailable to inexperienced developers, ie in order to build a simple entry-level Android App the unsuspecting newbie might need to study and understand many things that they didn't bargain for such as:

  • Android APK structure and ecosystem
  • Android Studio
  • Java Classpaths and dependencies
  • Groovy
  • Gradle build scripts
  • Many other complex and interesting technologies

All these things are interesting and useful for Android developers to know, but they are far from easy and present a formidable barrier to entry. I suspect that what inspired the OP to ask this question is the feeling of frustration that inevitably hits the neophyte developer after spending way too long trying to get a simple app to build and being continually thwarted by Gradle. The problem is perversely exacerbated by the overwhelming quantity of highly technical documentation that is available for all these technologies. Also for a large amount of development needs, Gradle is overkill.

An alternative is to write a shell script that builds your project by automating the tools available in the Android SDK. The virtues of this approach are many, for starters, it's probably the best way to study and understand the build process and the Android ecosystem, and it allows you to completely control how your app is built. However, this approach is more suitable for deeply irredeemable tech-heads than it is to inexperienced noobs trying out android.

What is conspicuous by its absence (please inform me if there is such a thing) is an entry-level, lightweight IDE with a reduced feature set that simultaneously simplifies the build process while not obscuring it (so not Netbeans or Eclipse) it could possibly still use Gradle (what was wrong with Ant). It should make it easy to generate APKs that conform to a few common configurations and use a project structure that can evolve to a full Android Studio project should you decide to take it that way.


Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins!

Advantages:

  • Dsl - Domain specific language, based on groovy
  • DAG - Directed Acyclic Graph
  • Incremental builds
  • Extensible domain model
  • Gradle is always up to date
  • Before a task is being execute, Gradle takes a snapshot of its task’s input and output.
  • In case the snapshot has changed or it doesn’t exists, Gralde will re- execute this task.

Manifest entries

Through the DSL it is possible to configure the following manifest entries:

Build variant

By default, the Android plugin automatically sets up the project to build both a debug and a release version of the application.

Dependencies

  1. Local Dependencies:

If you have binary archives in your local filesystem that a module depends on, such as JAR files, you can declare these dependencies in the build file for that module.

  1. Remote Dependencies:

First the repository must be added to the list, and then the dependency must be declared in a way that Maven or Ivy declare their artifacts.


Search Results Featured snippet from the web Android | build. gradle. Gradle is a build system (open source) which is used to automate building, testing, deployment etc. ... For example, the simple task to copy some files from one directory to another can be performed by Gradle build script before the actual build process happens.


Gradle is a build system. Build systems are software tools designed to automate the process of program compilation. Build systems come in various forms, and are used for a variety of software build tasks. While their primary goal is to efficiently create executables.

Another related term is Build automation which is the process of automating the creation of a software build and the associated processes including: compiling computer source code into binary code, packaging binary code, and running automated tests.

Few similar build system for other languages are (see complete list here):

  1. Apache Ant & Apache Maven - Java
  2. sbt (Simple Build Tool) - for Scala (Play framework etc)
  3. A-A-P - Python based build tool
  4. Rake (Apache Builder) - Ruby
  5. Leiningen for Clojure

Gradle is a build tool custom and used for building APK or known as application package kit.


Gradle is like a version of make that puts features before usability, which is why you and 433k readers can't even work out that it's a build system.


Gradle is an advanced build toolkit for android that manages dependencies and allows you to define custom build logic. features are like

  • Customize, configure, and extend the build process.

  • Create multiple APKs for your app with different features using the same project.

  • Reuse code and resources.

refer


You can find everything you need to know about Gradle here: Gradle Plugin User Guide

Goals of the new Build System

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

Why Gradle?

Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.

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

It's the new build tool that Google wants to use for Android. It's being used due to it being more extensible, and useful than ant. It is meant to enhance developer experience.

You can view a talk by Xavier Ducrohet from the Android Developer Team on Google I/O here.

There is also another talk on Android Studio by Xavier and Tor Norbye, also during Google I/O here.


Gradle is one type of build tool that builds the source code of the program. So it's an important part of Android Studio, and needs to be installed before starting developing your application.

We do not have to install it separately, because the Android Studio does it for us, when we make our first project.


In Android Studio, Gradle is used for building our android application projects, hence playing the role of a build system. Before Android Studio, in Eclipse we used to compile and build the applications using command line tool which was soon taken over by GUI based steps to build and run Android Applications in eclipse using ANT. Every android application development tool has to compile resources, java source code, external libraries and combine them into a final APK.

Gradle is a build system, which is responsible for code compilation, testing, deployment and conversion of the code into .dex files and hence running the app on the device.

As Android Studio comes with Gradle system pre-installed, there is no need to install additional runtime softwares to build our project. Whenever you click on Run button in android studio, a gradle task automatically triggers and starts building the project and after gradle completes its task, app starts running in AVD or in the connected device.

A build system like Gradle is not a compiler, linker etc, but it controls and supervises the operation of compilation, linking of files, running test cases, and eventually bundling the code into an apk file for your Android Application.

There are two build.gradle files for every android studio project of which, one is for application and other is for project level(module level) build files.

In the build process, the compiler takes the source code, resources, external libraries JAR files and AndroidManifest.xml(which contains the meta-data about the application) and convert them into .dex(Dalvik Executable files) files, which includes bytecode. That bytecode is supported by all android devices to run your app. Then APK Manager combines the .dex files and all other resources into single apk file. APK Packager signs debug or release apk using respective debug or release keystore.

Debug apk is generally used for testing purpose or we can say that it is used at development stage only. When your app is complete with desired features and you are ready to publish your application for external use then you require a Release apk signed using a release keystore.

Now lets shed some light on the gradle files.

setting.gradle The setting.gradle(Gradle setting) file is used to specify all the modules used in your app.

build.gradle (project level) The Top level (module) build.gradle file is project level build file, which defines build configurations at project level. This file applies configurations to all the modules in android application project.

build.gradle (application level) The Application level build.gradle file is located in each module of the android project. This file includes your package name as applicationID, version name(apk version), version code, minimum and target sdk for a specific application module. When you are including external libraries(not the jar files) then you need to mention it in the app level gradle file to include them in your project as dependencies of the application.

Note: If a certain application is developed in variations for individual modules like, Smart Phone, Tablet or TV then separate gradle files must to be created for all. You can even start your gradle system through command line tool. Following commands are used for it:

./gradlew build - (build project)
./gradlew clean build - (build project complete scratch)
./gradlew clean build - (run the test)
./gradlew wrapper - (to see all the available tasks)


The Android Studio build system is based on Gradle, and the Android Gradle plugin adds several features that are specific to building Android apps. Although the Android plugin is typically updated in lock-step with Android Studio, the plugin (and the rest of the Gradle system) can run independent of Android Studio and be updated separately.

For more details you can refer:

  1. https://developer.android.com/studio/releases/gradle-plugin?gclid=Cj0KCQiAlZH_BRCgARIsAAZHSBndmJC_myjKnuCBZbe7u9nyzMjbFGES2SVvedq4nxyqdqJnqq0xxlAaAvGMEALw_wcB&gclsrc=aw.ds
  2. https://gradle.org/

Short and simple answer for that,

Gradle is a build system, which is responsible for code compilation, testing, deployment and conversion of the code into . dex files and hence running the app on the device. As Android Studio comes with Gradle system pre-installed, there is no need to install additional runtime softwares to build our project.


In plain terms, Gradle is a tool provided by Android Studio in order to implement two important processes:

  1. Build our projects
  2. Package AndroidManifest.xml,res folder,and binary code into a specially formatted zip file called APK

Gradle is an automated build toolkit that can integrate into lots of different environments not only for Android projects.

Here are few things that you can do with gradle.

  • Minimal Configuration Required for New Projects because Gradle has defaults configurations for your android studio projects.

  • Dependancy Declaration. You can declare dependency jar files or library files that is hosted in local or remote server.

  • Gradle automatically generates a test directory and a test APK from your project's source.

  • If you add all the necessary information, such as keyPassword and keyAlias, to your Gradle build file, you can use Gradle to generate signed APKs.

  • Gradle can generate multiple APKs with different package and build configurations from a single module.


Gradle is to the Groovy JVM language what ant is to Java. Basically, it's Groovy's build tool. Unlike Ant, it's based on the full Groovy language. You can, for example, write Groovy script code in the Gradle script to do something rather than relying on a specific domain language.

I don't know IntelliJ's specific integration, but imagine you could "extend" Groovy such that you could write specific "build" language primitives and they just became part of the Groovy language. (Groovy's metaprogramming is a whole discussion unto itself.) IntelliJ/Google could use Gradle to build a very high-level build language, yet, it's a language build on an expandable, open standard.


In Android Studio, Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.

APK file (Android Application package) is a specially formatted zip file which contains

  • Byte code
  • Resources (images, UI, xml etc)
  • Manifest file

An apk file gets signed and pushed to the device using ADB(Android Debug Bridge) where it gets executed.


Here is a detailed explanation about what Gradle is and how to use it in Android Studio.

Exploring the Gradle Files

  1. Whenever you create a project in Android Studio, the build system automatically generates all the necessary Gradle build files.

Gradle Build Files

  1. Gradle build files use a Domain Specific Language or DSL to define custom build logic and to interact with the Android-specific elements of the Android plugin for Gradle.

  2. Android Studio projects consists of 1 or more modules, which are components that you can build, test, and debug independently. Each module has its own build file, so every Android Studio project contains 2 kinds of Gradle build files.

  3. Top-Level Build File: This is where you'll find the configuration options that are common to all the modules that make up your project.

  4. Module-Level Build File: Each module has its own Gradle build file that contains module-specific build settings. You'll spend most of your time editing module-level build file(s) rather than your project's top-level build file.

To take a look at these build.gradle files, open Android Studio's Project panel (by selecting the Project tab) and expand the Gradle Scripts folder. The first two items in the Gradle Scripts folder are the project-level and module-level Gradle build files

Top-Level Gradle Build File

Every Android Studio project contains a single, top-level Gradle build file. This build.gradle file is the first item that appears in the Gradle Scripts folder and is clearly marked Project.

Most of the time, you won't need to make any changes to this file, but it's still useful to understand its contents and the role it plays within your project.

Module-Level Gradle Build Files

In addition to the project-level Gradle build file, each module has a Gradle build file of its own. Below is an annotated version of a basic, module-level Gradle build file.

Other Gradle Files

In addition to the build.gradle files, your Gradle Scripts folder contains some other Gradle files. Most of the time you won't have to manually edit these files as they'll update automatically when you make any relevant changes to your project. However, it's a good idea to understand the role these files play within your project.

gradle-wrapper.properties (Gradle Version)

This file allows other people to build your code, even if they don't have Gradle installed on their machine. This file checks whether the correct version of Gradle is installed and downloads the necessary version if necessary.

settings.gradle

This file references all the modules that make up your project.

gradle.properties (Project Properties)

This file contains configuration information for your entire project. It's empty by default, but you can apply a wide range of properties to your project by adding them to this file.

local.properties (SDK Location)

This file tells the Android Gradle plugin where it can find your Android SDK installation.

Note: local.properties contains information that's specific to the local installation of the Android SDK. This means that you shouldn't keep this file under source control.

Suggested reading - Tutsplus Tutorial

I got clear understanding of gradle from this.


Gradle is an easily customizable build system that supports building by a convention model. Gradle is written in Java, but the build language is Groovy DSL (domain spec language). Gradle not only supports multi-project builds, but it also supports dependencies like Ivy and Maven. Gradle also can support building non-Java projects.

https://medium.com/@ravirajdesai501/what-is-gradle-442458dd7ec1


Gradle is a build system running on Android Studio.

In other languages for example:


I refer two tutorial to write the Answer one,two

Gradle is a general purpose, declarative build tool. It is general purpose because it can be used to build pretty much anything you care to implement in the build script. It is declarative since you don't want to see lots of code in the build file, which is not readable and less maintainable. So, while Gradle provides the idea of conventions and a simple and declarative build, it also makes the tool adaptable and developers the ability to extend. It also provides an easy way to customize the default behavior and different hooks to add any third-party features.

Gradle combines the good parts of both tools and provides additional features and uses Groovy as a Domain Specific Language (DSL). It has power and flexibility of Ant tool with Maven features such as build life cycle and ease of use.

Why Gradle? Why Now?

The build tool's response is to add scripting functionality through nonstandard extension mechanisms. You end up mixing scripting code with XML or invoking external scripts from your build logic. It's easy to imagine that you'll need to add more and more custom code over time. As a result, you inevitably introduce accidental complexity, and maintainability goes out the window.

Let's say you want to copy a file to a specific location when you're building the release version of your project. To identify the version, you check a string in the metadata describing your project. If it matches a specific numbering scheme (for example, 1.0-RELEASE), you copy the file from point A to point B. From an outside perspective, this may sound like a trivial task. If you have to rely on XML, the build language of many traditional tools, expressing this simple logic becomes fairly difficult.

Evolution of Java Build Tools

Java build logic has to be described in XML. XML is great for describing hierarchical data but falls short on expressing program flow and conditional logic. As a build script grows in complexity, maintaining the building code becomes a nightmare.

In Ant, you make the JAR target depend on the compile target. Ant doesn't give any guidance on how to structure your project. Though it allows for maximum flexibility, Ant makes each build script unique and hard to understand. External libraries required by your project are usually checked into version control because there is no automated mechanism to pull them from a central location.

Maven 1, released in July 2004, tried to ease that process. It provided a standardized project and directory structure, as well as dependency management. Unfortunately, custom logic is hard to implement

Gradle fits right into that generation of build tools and satisfies many requirements of modern build tools (Figure 1). It provides an expressive DSL, a convention over configuration approach, and powerful dependency management. It makes the right move to abandon XML and introduce the dynamic language Groovy to define your build logic. Sounds compelling, doesn't it?

Gradle combines the best features of other build tools.

enter image description here

Gradle's Compelling Feature Set

enter image description here

Why Build Your Java Projects with Gradle Rather than Ant or Maven?

The default build tool for Android (and the new star of build tools on the JVM) is designed to ease scripting of complex, multi-language builds. Should you change to it, though, if you're using Ant or Maven?

The key to unlocking Gradle's power features within your build script lies in discovering and applying its domain model, as shown in below image. enter image description here

Gradle can't know all the requirements specific to your enterprise build. By exposing hooks into lifecycle phases, Gradle allows for monitoring and configuring the build script's execution behavior.

Gradle establishes a vocabulary for its model by exposing a DSL implemented in Groovy. When dealing with a complex problem domain, in this case, the task of building software, being able to use a common language to express your logic can be a powerful tool.

Another example is the way you can express dependencies to external libraries, a very common problem solved by build tools. Out-of-the-box Gradle provides you with two configuration blocks for your build script that allow you to define the dependencies and repositories that you want to retrieve them from. If the standard DSL elements don't fit your needs, you can even introduce your own vocabulary through Gradle's extension mechanism.

Integration with Other Build Tools

Gradle plays well with its predecessors' Ant, Maven, and Ivy, as shown in the image below.

enter image description here

Automating Your Project from Build to Deployment

enter image description here

In image: Stages of a deployment pipeline.

  • Compiling the code

  • Running unit and integration tests

  • Performing static code analysis and generating test coverage

  • Creating the distribution

  • Provisioning the target environment

  • Deploying the deliverable

  • Performing smoke and automated functional tests

I refer two tutorial to write the Answer one,two


At the risk of being discursive I think behind this is the question of why the Android Studio / Gradle experience is so bad.

Typical Clojure experience :

  • download project with dependencies listed in project.clj.
  • Leiningen gets the dependencies thanks to Clojars and Maven.
  • Project compiles.

Typical Android Studio / Gradle experience :

  • "Import my Eclipse project".
  • OK project imported.
  • Gradle is doing it's thang ... wait ... wait ... wait ... Gradle has finished.
  • Compile ... can't compile because I don't know what an X is / can't find Y library.

I'm not sure this is Gradle's fault exactly. But the "import from Eclipse project" seems pretty flaky. For all of Gradle's alleged sophistication and the virtues of a build-system, Android Studio just doesn't seem to import the build dependencies or build-process from Eclipse very well.

It doesn't tell you when it's failed to import a complete dependency graph. The Android Studio gives no useful help or tips as to how to solve the problem. It doesn't tell you where you can manually look in the Eclipse folders. It doesn't tell you which library seems to be missing. Or help you search Maven etc. for them.

In 2016 things like Leiningen / Clojars, or node's npm, or Python's pip, or the Debian apkg (and I'm sure many similar package managers for other languages and systems) all work beautifully ... missing dependencies are thing of the past.

Except with Android. Android Studio is now the only place where I still seem to experience missing-dependency hell.

I'm inclined to say this is Google's fault. They broke the Android ecosystem (and thousands of existing Android projects / online tutorials) when they cavalierly decided to shift from Eclipse to Android Studio / Gradle without producing a robust conversion process. People whose projects work in Eclipse aren't adapting them to AS (presumably because it's a pain for them). And people trying to use those projects in AS are hitting the same issues.

And anyway, if Gradle is this super-powerful build system, why am I still managing a whole lot of other dependencies in the sdk manager? Why can't a project that needs, say, the ndk specify this in its Gradle file so that it gets automatically installed and built-against when needed? Why is NDK special? Similarly for target platforms? Why am I installing them explicitly in the IDE rather than just checking my project against them and having this all sorted for me behind the scenes?


Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to android-gradle-plugin

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries Invoke-customs are only supported starting with android 0 --min-api 26 error: resource android:attr/fontVariationSettings not found Exception : AAPT2 error: check logs for details Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Examples related to build-automation

What is Gradle in Android Studio? Maven: Non-resolvable parent POM Controlling Maven final name of jar artifact How do I clear my Jenkins/Hudson build history? How can I get CMake to find my alternative Boost installation? Ant: How to execute a command for each file in directory? Xcode variables Why does Maven have such a bad rep? How can I create an executable JAR with dependencies using Maven? Ant task to run an Ant target only if a file exists?