加速Android Studio/Gradle构建

    |     2016年5月25日   |   开发环境   |     0 条评论   |    1505

用 Android Studio 一年多,项目变大、依赖变多,构建越来越慢,release 包最慢要 6 分钟。网上这些配置能明显加快,这里汇总分享。

20140731144525904006


一、开启 Gradle 守护进程

在用户目录创建 gradle.properties:

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

写入:

org.gradle.daemon=true

项目下的 gradle.properties 也可以一起优化:

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -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
# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true

同样参数也可以写到用户目录的 gradle.properties,那样对所有项目生效,不限于当前工程。核心就三件事:加大 Gradle 的 JVM、独立守护进程、允许并行。环境说明见 http://www.gradle.org/docs/current/userguide/build_environment.html;并行只适合解耦的多模块工程,见 http://www.gradle.org/docs/current/userguide/multi_project_builds.html。


二、修改 Android Studio 配置

在 IDE 里开 Offline,并改运行模式和 VM。内容和上面那段一样,但只对 IDE 构建生效,命令行构建不会带上。


三、命令行构建

基于上面的配置,命令后面加上 --daemon --parallel --offline。


四、依赖尽量用 aar

第三方库尽量用 aar,可在 maven http://gradleplease.appspot.com/ 或 github https://github.com/Goddchen/mvn-repo 搜。自己的库模块也可以打 aar,参考 stormzhang:http://www.stormzhang.com/android/2015/03/01/android-reference-local-aar/。

手段 作用 范围
org.gradle.daemon=true 少启动 JVM 用户目录或项目 properties
jvmargs -Xmx2048m 加大堆,少 GC 同上
parallel + configureondemand 并行、按需配置 解耦的多模块项目
IDE Offline 不每次拉依赖 仅 Android Studio
–daemon –parallel –offline 命令行同样加速 命令行
aar 代替源码模块 少编译自己的库 依赖声明

五、后记

原来 4、5 分钟的构建,现在大约 30 秒。若还是慢,该换电脑了:SSD、更大内存是必须的。原文地址:http://blog.isming.me/2015/03/18/android-build-speed-up/

一句话总结:加速构建先开 daemon、加大 JVM、并行和 Offline,依赖改 aar;还慢就上 SSD 和内存。

转载请注明来源:加速Android Studio/Gradle构建
本文链接地址:https://ai.zhousir.top/?p=1588
回复 取消