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:
- 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
- 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.
- 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 ...
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.
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.