Gradle Tips for Android Studio

Gradle Tips for Android Studio

Hey Android Devs, in this blog I’m writing some useful tips about using gradle features in Android studio. I hope you find it useful. These tips are tested on Android studio 4.0+ and Gradle version 6+.

What is gradle and why is it used in Android Studio ?

Gradle is a build system (open source) which is used to automate building, testing, deployment etc. “Build. gradle” are scripts where one can automate the tasks. 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.

1. Set custom name for your autogenerated .apk or .aar files

Add the following lines in your build.gradle (app).


2. Multiple Dimensions and flavours

To create multiple types or versions of the App, such as Free and Paid version, we can use productFlavours. We can also define different App name, application id suffix, version suffix and icons for different flavours of the App.

3. Dependency resolution

If multiple libraries are using the same packages, it could create a conflict for the gradle compiler, such as:

// opencv 3.4.5
implementation 'com.quickbirdstudios:opencv:3.4.5'
//javacv library
implementation 'org.bytedeco:javacv:1.5.5'

These dependencies use the same package org.opencv but have different features which you want to use.

To resolve this issue add these code to the end of your build.gradle (app) file:

This method substitutes a module with another specified module to resolve conflict.

4. Exclude package/module

Sometimes you don’t require packages that already exist in Android sdk or are useless for you. To exclude those packages we can use the exclude function in gradle.

5. Signing config

When you are working with a team on the same Android project or generating builds via CI/CD, you need to define a signing config to sign the apk.

Here is how you can do this.
First you need to create Key Store file (i.e build menu > generate signed bundle/apk > create new ).

Note: You must not write password and alias in gradle file for release builds, it should be kept in a separate file.

6. Gradle task

You can create a custom task in the gradle for your specific needs.
For example, I want to fetch the App version from the command line, so I can create a task for that as shown below.

Add In build.gradle (app)

To execute this task in terminal, write :

./gradlew -q printVersionName

As the gradle build system allows you to build and automate your tasks, there are so many features and possibilities to increase your productivity and save time.