Android Studio编译时间太长

3
我的Android Studio编译时间太长了,最少需要10分钟,而且经常更长。

这个问题是gradle插件升级到7.0.4后开始出现的。

这是我在应用程序层级别的build.gradle文件内容:
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
}

这是导致问题的库模块的build.gradle文件:
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

构建分析器显示以下两个任务导致问题:

在此输入图片描述

在此输入图片描述


请显示gradle.properties文件。 - Sergio
@Sergey 已添加它并 gradle-wrapper.properties - theblitz
2个回答

1

尝试在gradle.properties中设置org.gradle.jvmargs,如下所示:

org.gradle.jvmargs=-Xmx3g

请注意,在清理后的大型项目的第一次构建可能需要长达10分钟甚至更长时间。
其他提示:
  • 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.


保留其他参数吗? - theblitz
1
尝试删除“-XX:MaxPermSize = 512m”,如果不起作用,请删除其他参数(-Dfile.encoding = UTF-8 -XX:+ UseParallelGC)。 - Sergio
尝试过了,还是不行 :( - theblitz
1
@theblitz请查看我回答中提供的其他提示。 - Sergio
非常感谢!现在运行得很好。我做了所有的事情(除了Gradle插件),现在非常棒。 - theblitz

0
通过添加
kotlin.incremental=true

通过 gradle.properties,我的构建时间从23秒缩短到了1秒。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接