[android] Android Studio gradle takes too long to build

My Android Studio project used to build faster but now it takes a long time to build. Any ideas what could be causing the delays? I have tried https://stackoverflow.com/a/27171878/391401 but no effect. I haven't any Anti virus running which could interrupt the builds. My app is not that big in size as well (around 5MB) and it used to build within few seconds but not sure what has changed.

10:03:51 Gradle build finished in 4 min 0 sec  
10:04:03 Session 'app': running  
10:10:11 Gradle build finished in 3 min 29 sec  
10:10:12 Session 'app': running  
10:20:24 Gradle build finished in 3 min 42 sec  
10:28:18 Gradle build finished in 3 min 40 sec  
10:28:19 Session 'app': running  
10:31:14 Gradle build finished in 2 min 56 sec   
10:31:14 Session 'app': running  
10:38:37 Gradle build finished in 3 min 30 sec  
10:42:17 Gradle build finished in 3 min 40 sec  
10:45:18 Gradle build finished in 3 min 1 sec  
10:48:49 Gradle build finished in 3 min 30 sec  
10:53:05 Gradle build finished in 3 min 22 sec  
10:57:10 Gradle build finished in 3 min 19 sec  
10:57:11 Session 'app': running  

This question is related to android android-studio build gradle build.gradle

The answer is


I had the same problem, even the gradle build ran for 8 hours and i was worried. But later on i changed the compile sdk version and minimum sdk version in build.gradle file like this.

Older:

android {
compileSdkVersion 25
buildToolsVersion "29.0.2"

defaultConfig {
    applicationId "com.uwebtechnology.salahadmin"
    minSdkVersion 9
    targetSdkVersion 25
}

New (Updated):

android 
{
  compileSdkVersion 28
   buildToolsVersion "25.0.2"

 defaultConfig {
    applicationId "com.uwebtechnology.salahadmin"
    minSdkVersion 15
    targetSdkVersion 28
 }

In Android Studio, above Version 3.6, There is a new location to toggle Gradle's offline mode To enable or disable Gradle's offline mode.

To enable or disable Gradle's offline mode, select View > Tool Windows > Gradle from the menu. In the top bar of the Gradle window, click Toggle Offline Mode (near settings icon).

enter image description here

It's a little bit confusing on the icon, anyway offline mode is enabled when the toggle button is highlighted. :)


Enabling Java 8 features caused deadly slow build

gradle

 jackOptions {
        enabled true
  }

  compileOptions {
    targetCompatibility 1.8
    sourceCompatibility 1.8
}

After deleting above lines, it builds in seconds.

There is issue Compiling with Jack takes very long time

Project Manager's Answer

We're aware that build times are an issue with Jack right now. We have improvements in the 2.4 Gradle plugin that should be a significant improvement for incremental builds.

As of now, latest Gradle version i can find is 2.3.0-beta4


In Android Studio go to File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle

(if on mac) Android Studio -> preferences... -> Build, Execution, Deployment -> Build Tools -> Gradle

Check the 'Offline work' under 'Global Gradle settings'

Note: In newer version of Android studio, View->Tool Windows->Gradle->Toggle button of online/offline

It will reduce 90% gradle build time.

check this to reduce build time

if you just added a new dependency in your gradle you will have to uncheck the offline work or gradle will not be able to resolve the dependencies. After the complete resolving then you you can check the offline work for a faster build


In your build.gradle, if you have minifyEnabled for debug, remove it. I had it in my project and it took ~2-3 minutes to build. After looking at build progress, I found this as culprit, so deleting the commented line below, my issue was fixed.

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

Check disk usage in Windows OS ...

The problem can be related to this, in my case I had Windows 8 OS consuming a 100% disk usage.

Especially the Windows Search service, can be the most consuming. Disable it with:

cmd (Admin)

net.exe stop "Windows search"

Check this link 4 Tips to Fix 100% Disk Usage & Improve Windows Performance


The second thing i did was Uninstall my Anti-Virus software (AVG Antivirus) {sounds crazy but, i had to}. it reduced gradle build time upto 40%

The first thing i did was enable offline mode (1. click on Gradle usually on the right side of the editor 2. click on the connection button to toggle) it reduced the gradle build time for upto 20%

so my Gradle build time was reduced for upto 60% by doing these two things


In the beta version of Android studio 2.0, they've rolled out a feature called Instant Run. It reduces the build time by a big factor. The core concept is, Android Studio only pushes the small changes made into an already running app.

It classifies the changes we make in our code to three parts: hot swap, warm swap and cold swap, based on how much load would the change would put on the build. After that, it simply swaps the code in the already running app and we get could see the changes running a few seconds. See their doc for more information.

Here you can download Android Studio 2.0 preview.

PS: There are a few issues with this feature. They've listed it out at the docs. Check it out before installation.


Check your Internet connection. If internet speed is very slow gradle build will also take long time to build. I check by change my wifi internet connection with another one good speed connection. Now build time is normal. Please try this before you go to other solutions. somebody will take wrong decision to reinstall or change settings. I hope it will help. Thanks and regards.


I had the same issue in kotlin. Updating the outdated kotlin runtime solved it for me


You could try the tips in this post Why your Android Studio takes forever to build - Part 2 One of the tips recommmends "Enable offline mode" among other things.


1) My build time severely increased after i added some new library dependencies to my gradle file, what turned out that i need to use multidex after that. And when i set up multidex correctly then my build times went up to 2-3 minutes. So if you want faster build times, avoid using multidex, and as far as possible, reduce the number of library dependencies.

2) Also you can try enabling "offline work" in android studio, like suggested here, that makes sense. This will not refetch libraries every time you make a build. Perhaps slow connection or proxy/vpn usage with "offline work" disabled may lead to slow build times.

3) google services - as mentioned here, dont use the whole bundle, use only the needed parts of it.


  1. Go to File->Setting-->Gradle-->Set it to offline mode and check

I had a similar issue on my computer. Windows Defender was blocking some part of Gradle Building. I've disabled it, worked fine after that.


Following the steps will make it 10 times faster and reduce build time 90%

First create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true

org.gradle.parallel=true

Recommended Reading: How I save 5h/week on Gradle builds!

According to this excellent post you should try to optimized the following:

  • Gradle Daemon
  • Parallel Project Execution
  • Configure projects on demand
  • Modules are expensive...

I had issues like this especially when debugging actively through my phone; at times it took 27 minutes. I did the following things and take note of the explanation under each - one may work for you:

  1. Changed my gradle.properties file (under Gradle scripts if you have the project file view under Android option OR inside your project folder). I added this because my computer has some memory to spare - you can assign different values at the end depending on your computer specifications and android studio minimum requirements (Xmx8000m -XX:MaxPermSize=5000m) :

org.gradle.daemon=true

org.gradle.configureondemand=true

org.gradle.parallel=true

android.enableBuildCache=true

org.gradle.caching=true

org.gradle.jvmargs=-Xmx8000m -XX:MaxPermSize=5000m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

  1. This did not completely solve my issue in my case. Therefore I also did as others had suggested before - to make my builds process offline:

File -> Settings/Preferences -> Build, Execution, Deployment -> Gradle

Global Gradle Settings (at the bottom)

Mark the checkbox named: Offline Work.

  1. This reduced time substantially but it was erratic; at times took longer. Therefore I made some changes on Instant Run:

File -> Settings/Preferences -> Build, Execution, Deployment -> Instant Run

Checked : Enable Instant Run to hot swap code...

Checked: restart activity on code changes ...

  1. The move above was erratic also and therefore I sought to find out if the problem may be the processes/memory that ran directly on either my phone and computer. Here I freed up a little memory space in my phone and storage (which was at 98% utilized - down to 70%) and also on task manager (Windows), increased the priority of both Android Studio and Java.exe to High. Take this step cautiously; depends on your computer's memory.

  2. After all this my build time while debugging actively on my phone at times went down to 1 ~ 2 minutes but at times spiked. I decided to do a hack which surprised me by taking it down to seconds best yet on the same project that gave me 22 - 27 minutes was 12 seconds!:

Connect phone for debugging then click RUN

After it starts, unplug the phone - the build should continue faster and raise an error at the end indicating this : Session 'app': Error Installing APKs

Reconnect back the phone and click on RUN again...

ALTERNATIVELY

If the script/function/method I'm debugging is purely JAVA, not JAVA-android e.g. testing an API with JSONArrays/JSONObjects, I test my java functions/methods on Netbeans which can compile a single file and show the output faster then make necessary changes on my Android Studio files. This also saves me a lot of time.

EDIT

I tried creating a new android project in local storage and copied all my files from the previous project into the new one - java, res, manifest, gradle app and gradle project (with latest gradle classpath dependency). And now I can build on my phone in less than 15 seconds.


Found an easy and best way to build gradle

go to your app >> open your gradle.properties and change few lines from it [remove #]

else you may copy paste my below snippet as well

    # Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx2048m -XX:MaxPermSize=512m
 org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
 org.gradle.parallel=true

it worked for me earlier it take almost 2-3 minutes now it is taking only 5-6 second

in above scenario my mac machine have 8GB ram so i assigned 4gb for gradle


@AndroidDev solution worked for me. I had included the whole lib in gradle.

compile 'com.google.android.gms:play-services:8.4.0'

Changing to solved the problem. From 4 min to 1 min.

compile 'com.google.android.gms:play-services-ads:8.4.0'
compile 'com.google.android.gms:play-services-analytics:8.4.0'

Thnx


If you are using Google Play services, make sure you aren't using this in your Gradle build script:

compile 'com.google.android.gms:play-services:8.3.0'

Only use those Google APIs that your app is really using. If all you are using is Google Maps, you would use this:

com.google.android.gms:play-services-maps:8.3.0

When I did this, my compile time went from over 2 minutes to around 25 seconds. For a list of the Google apis that you can selectively compile against, see:

https://developers.google.com/android/guides/setup


I was facing the same problem for a long time but I solved it by adjusting the settings in gradle.

Step 1:In Module app add dependency in BuildScript

buildscript {
 dependencies {
         classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
}
}

Step 2: Add dexOption and give the following heapSize

  dexOptions {
    incremental = true;
    preDexLibraries = false
    javaMaxHeapSize "4g"
}

Step 3: Add productFlavors

    productFlavors {
    dev {
        minSdkVersion 23
        applicationId = "com.Reading.home"
    }
    prod {
        minSdkVersion 15
        applicationId = "com.Reading.home" // you don't need it, but can be useful

    }
}

This should reduce your build time.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

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 build

error: This is probably not a problem with npm. There is likely additional logging output above Module not found: Error: Can't resolve 'core-js/es6' WARNING in budgets, maximum exceeded for initial How can I change the app display name build with Flutter? Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0) Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation' Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details Component is part of the declaration of 2 modules Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

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 build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK