用 Android Studio 開發一年多,隨著專案膨脹、依賴庫增加,建置時間越拖越長,最糟時打包一個 release 要等上 6 分鐘。翻了些資料後發現,光是調整設定就能有明顯改善,這裡整理出來分享。
在下列目錄建立 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
# https://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
# https://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.
# https://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true
這些參數也可以寫進使用者目錄下的 gradle.properties,差別是作用範圍從單一專案擴大到所有專案。這組設定的作用 basically 是三件事:放大 Gradle 專用 JVM 的記憶體上限、讓編譯跑在獨立行程中、以及讓多模組可以平行處理。
在 Android Studio 的設定中開啟 offline 模式並同步上述參數。此處的設定只在 IDE 內建置時生效,命令列建置不受影響。
若走命令列,在指令後方加上 --daemon --parallel --offline 即可。
引入第三方庫時盡量挑 aar 版本,可到 https://gradleplease.appspot.com/ 或 https://github.com/Goddchen/mvn-repo 搜尋。自己的模組也可以打包成 aar,做法參考 https://www.linuxidc.com/Linux/2015-03/115242.htm。
折騰完這一輪,原本要 4、5 分鐘的建置,現在約 30 秒就能完成。若你照做仍然很慢,那大概該換機器了——SSD 加更大的記憶體,該上的還是得上。
延伸閱讀:
Ubuntu 12.04(64位)安裝Android Studio 全過程 https://www.linuxidc.com/Linux/2013-05/84812.htm
Android Studio v0.1嘗鮮 https://www.linuxidc.com/Linux/2013-05/84681.htm
Android Studio使用教程 https://www.linuxidc.com/Linux/2013-05/84579.htm
Android Studio開發指南 https://www.linuxidc.com/Linux/2013-05/84543.htm
Android Studio設置主題 和 不支持中文的問題解決方法 https://www.linuxidc.com/Linux/2013-05/84488.htm
Android Studio 下載安裝以及不能打開的解決辦法 https://www.linuxidc.com/Linux/2013-05/84409.htm
Android Studio安裝使用圖文教程 https://www.linuxidc.com/Linux/2014-09/106914.htm
Android Studio 的詳細介紹:請點這裡
Android Studio 的下載地址:請點這裡
更多Android相關信息見Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11