Search code examples
androidandroid-studiobuildandroid-gradle-pluginandroid-build

Android studio compile takes forever


My Android Studio compiles are taking forever. Min 10 mins and quite often longer than that.

This started with the upgrade of gradle plugin to 7.0.4

This is my build.gradle at the ap level:

buildscript {
    ext.kotlin_version = "1.6.0"
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.4'
        classpath 'com.google.gms:google-services:4.3.10'
        classpath "io.realm:realm-gradle-plugin:6.0.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' }
        maven { url 'https://jitpack.io' }

        maven {
            url 'https://maven.wefi.com/repository/wefi-release-repo'
            artifactUrls 'https://maven.wefi.com/repository/wefi-release-repo'
        }
        configurations.all {
            resolutionStrategy {
                force 'org.xerial:sqlite-jdbc:3.34.0'
            }
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is the build.gradle for the library module that is causing the problem:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'realm-android'
apply from: '../../WeFiBuild/common/dependencies.gradle'

ext.versionMajor = 0
ext.versionMinor = 0
ext.versionBuild = 0
ext.versionRevision = 0
ext.playStoreVersionCode = 0

def computeVersionName() {
    def branch = gitBranch()
    if (branch == "master")
        return "${versionMajor}.${versionMinor}.${versionRevision}"
    else 
        return "${versionMajor}.${versionMinor}.${versionRevision}.${versionBuild}.rc${versionBuild}"
}

def computeVersionCode() {
    computeBuildVersion()
    return playStoreVersionCode
//    return (versionMajor * 10_000_000) + (versionMinor * 100_000) + (versionBuild * 1_000) + versionRevision
}

def versionPropsFile = file('./../../WeFi/app/version.properties')

ext.computeBuildVersion = {
    if (versionPropsFile.canRead()) {
        Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))
        versionMajor = versionProps['VERSION_MAJOR'].toInteger()
        versionMinor = versionProps['VERSION_MINOR'].toInteger()
        versionBuild = versionProps['VERSION_BUILD'].toInteger()
        versionRevision = versionProps['VERSION_REVISION'].toInteger()
    } else {
        throw new FileNotFoundException("Could not read version.properties!")
    }

    return computeVersionName()
}

android {
    compileSdkVersion 31
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 30

        versionCode computeVersionCode()
        versionName computeVersionName()
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resConfigs "en", "es" ,"pt"


        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }


    buildTypes {
        debug {
        }

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        freeCompilerArgs = ['-Xjvm-default=compatibility']
    }
}

dependencies {
    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

    //Don't change it back to implementation else we will not be able to get it's jar from the intermediates/compile_library_classes
    api project(path: ':WeFiUtil')
    api project(path: ':WeFiUtilExt')
    api project(path: ':WeFiKeepAliveLibs')
    api project(path: ':WeFiOsDataPollingLibs')
    api project(path: ':WeFiDataCollectLibs')

    implementation files('../cauchoHessian/cauchoHessian.jar')
    implementation files('../WeFiSupportLibrary/WeFiSupportLibrary.jar')
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    compileOnly "com.google.code.gson:gson:$gsonVersion"
    implementation 'com.google.firebase:firebase-crashlytics:18.2.6'
    implementation 'com.google.firebase:firebase-analytics:20.0.2'

    compileOnly "com.google.android.gms:play-services-location:$playServicesVersion"
    compileOnly "com.google.firebase:firebase-analytics:$firebaseAnalyticsVersion"
    implementation "com.google.firebase:firebase-messaging:23.0.0"

    implementation "com.android.installreferrer:installreferrer:2.2"


    implementation "androidx.room:room-runtime:2.4.1"
    kapt "androidx.room:room-compiler:2.4.1"

    implementation "androidx.core:core-ktx:1.7.0"
    implementation 'androidx.preference:preference-ktx:1.1.1'

    // Excel support
    implementation 'org.apache.poi:poi:3.17'

    def moshiVersion = "1.13.0"
    implementation("com.squareup.moshi:moshi:$moshiVersion")
    implementation("com.squareup.moshi:moshi-kotlin:$moshiVersion")
    kapt("com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion")

    api "com.android.volley:volley:1.2.1"

}
repositories {
    mavenCentral()
}

def gitBranch() {
    def branch = ""
    def proc = "git rev-parse --abbrev-ref HEAD".execute()
    proc.in.eachLine { line -> branch = line }
    proc.err.eachLine { line -> println line }
    proc.waitFor()
    println "branch name = " + branch
    branch
}

gradle.properties

    # 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.
#org.gradle.jvmargs=-Xmx1Fg536m
# Increase memory allotted to JVM
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -Dfile.encoding=UTF-8 -XX:+UseParallelGC


# 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

#android.enableSeparateAnnotationProcessing=true
android.useAndroidX=true
android.enableJetifier=true
android.injected.testOnly = false
org.gradle.caching=true


org.gradle.daemon=true
# Enable Configure on demand
org.gradle.configureondemand=true
kotlin.incremental=true

# positive value will enable caching
# use the same value as the number of modules that use kapt
kapt.classloaders.cache.size=5

# disable for caching to work
kapt.include.compile.classpath=false

gradle-wrapper.properties

    #Wed Jan 12 11:49:46 MSK 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

The Build Analyzer shows the following two tasks that are causing the problems:

enter image description here

enter image description here


Solution

  • Try set org.gradle.jvmargs setting in gradle.properties like the following:

    org.gradle.jvmargs=-Xmx3g
    

    Please pay attention that the first build of a big project after cleanup can take up to 10 mins or even a little more.

    Some other tips:

    • update Android Gradle Plugin to the latest stable version (currently 7.1.3) and Gradle Version (currently 7.2). Refer to this document.

    • update Kotlin version to 1.6.10 or later.

    • update Android Studio and Build-Tools.

    • use JavaVersion.VERSION_11 for sourceCompatibility and targetCompatibility:

      compileOptions {
         sourceCompatibility JavaVersion.VERSION_11
         targetCompatibility JavaVersion.VERSION_11
      }
      
      kotlinOptions {
          jvmTarget = "11"
          ...
      }
      
    • set android.enableJetifier=false in grade.properties.