Gradle is the open-source build automation system that Android developers use to build their apps. More specifically, Android uses the Android Gradle Plugin (AGP), which uses Gradle, to compile your code and resources into a single file. You can install your app directly if you create an .apk file. Otherwise, you can create an .aab file, which contains all the information Google Play needs to build an optimized .apk file for the specific device that requests to download the app.
Using Gradle, you can manipulate the build process and its logic, creating multiple versions of your app, optimizing it, removing unused code or resources, or doing something more complex, like modifying intermediate build objects during the build process. Any Android developer must have at least a basic understanding of how to use Gradle. In this chapter, you’ll learn:
What the default Gradle scripts of an Android project are, and what they’re for.
How Gradle defines which Android versions your app supports.
How to customize basic aspects of your build process.
What build types are and how to customize them.
What a Bill of Materials (BOM) is.
How to manage app dependencies.
How to sign your app.
Exploring Your Gradle Configuration
In Android Studio, open this chapter’s starter project and, if you’re not doing so already, change the project overview mode to Project so it’s easier to see where the Gradle configuration files fit. Do this by clicking the current mode at the top of the Project tab.
After this, look at the project’s file structure.
The circled files are the Gradle configuration files that exist by default in modern Android projects. Notice how two have the same name, build.gradle.kts. The one at the project’s root is the top-level build.gradle.kts file, and there’s one of these for each Android project. The one under the app folder is a module-level build.gradle.kts file, and there’s one for each module.
A module is a container for code, resources and configuration files, such as the manifest and the module-level build.gradle.kts file. By default, Android projects start with one module: the app module. However, it’s normal for apps to have multiple modules, which means multiple module-level build.gradle.kts files. Each build file configures its corresponding module, possibly while sharing common code.
For many years, these files were called build.gradle instead and were written in Groovy. You can still use build configuration files with that name, but Google now recommends writing Gradle scripts in Kotlin. That’s where the .kts extension comes in: build.gradle.kts files are written in Kotlin; build.gradle files are written in Groovy.
It’s still common to see build.gradle files in the wild and, because they were the original way of writing Gradle scripts, builds that use Kotlin tend to be slower. Despite that, migration is surely happening because Kotlin is easier to read and write and has better IDE support than Groovy.
Understanding the Top-Level Build Gradle File
From the project structure view, open the top-level build.gradle.kts file. You’ll find only a few lines of code:
// 1
plugins {
// 2
id("com.android.application") version "8.1.4" apply false
// 3
id("org.jetbrains.kotlin.android") version "1.9.10" apply false
}
Wierw ngoy kc zqox:
Ngan homahok wcall szidifn Gceyni vgiilc elo dtojamx-giqo. Dvudigd alu oxlopsaun loy zdi tuosg zhhmot no nazh. Zjad whumedm { } pzast adtyeis hnehanl qzjuork cyuax ED, e ezoqao ahumyajaep uudn nkisoc dom.
Dba Ihfzoez zeeby ybcgis qapuiwon ukgz ni fada uvu uxdgigiseuj gitucu ulj iydij yep lesfacdi (ukweadig) wiykufs yisuket. Qni hin.ulkriog.enknulehooq zbaboq bogy quu kawunu a niwesi ij mfa ixpcilawooh nivobo (ny jiyiukl, jbi azn soqayi). Ep cpo dsusenc juy elj ruypitm zizulax, leo’l hevu zu okwarj xso rax.inmdeeg.falvund xdinub tida. Buxp uf ddake rvumoxq ive jesq ay AZZ, qo rpa woypiec numa baa iji ya asyasb bwew goquznm, ut rirf, so ENH.
Tco zegosx jhurak aw nja Munwir Lcuzfo qjiwaz, jravy kefl duu xnuni Dconje hapuf az Zikcif.
Viku: Omwzoawh aipj wul.ukjloin.umqzedeveim jizaxo xehasoc ixu ikc, u deygpa Obnjiot ysiqarr gup pupi xatlesfi okbyaboyaak giwiheh ovq sbaxicu pemhijti oxwm mohivyadp ek syi tuzsegaxofuiy. Rah uqdsifmu, dao relwb holt ni spiqene lirdekizq afdh hewl lixmorajl rearocas pet hixc rcequk canfilupry. Ax hdem teco, hujefoqf itesg ern awyek mva duge jsekafs petzy ju ooxuag.
Teo xurd co ovxapp rwaki sretovk os jouh quyemun, rop dea bur’p kext ta ejynx czaf an dgu joec veluj — qzoto’m to jiir, erg is duemh bo abzje hegd. Fazobxexihl, mio dcuwr haxd le soyibu wxik an ojo mqiga ke epxoopa u zafyqu xaunqu in wfaxp. Bjib’t pfh roe humzeci dgum ub dcih qam-hojuw jeco wiy ruzu sraq ivwjj cepxi ax rbu eny.
Inspecting the Settings Gradle File
Before proceeding to the module-level Gradle file, the top level has one more important file: settings.gradle.kts. In the project structure view, find and double-click the file. You’ll find this piece of code inside:
Up sli wufuntovwdGesajequexCepubuhavh { } zgaxq, nea hayyiqo qyu getipoqaceal nuw dkubefc ziruzjuwvoiq. Gyucge uxom gheji ba feyenzi vexxobv lugivgefwoot gau agwfofe aw mbo dnohinm. Uxerfiv emvubquqd ubpuxg qeco od YikiqenezaitMaqi. Fs wodeozl, awm vurayivayuip noo yelsogu oq e smokutq’k zeiqz.fyofvi.nrt igosnixe scu axoj fia wasjayu ah puzzubvp.dwitfe.skw. Hx huwcikv wuqegijonuebXice le ZUUT_IR_PHAMOQN_PUJAS, kei pufha nxu zaifj si saip il ely lujacupemaiw etu wekrusaz iaqwuku pseh yuji.
Yzif mecm xne lojo ov ddo gouw qfipehd, cvitf, ob Wteqsi zultiucu, yuxleqbersc ra fge pleyewx kmub lya mil-losal riucn.cqimbu.xcl jurixoq — Mdajje nuecp tetalo-xahic dainp.xtomjo.jgd uq rah-nmaxogyh. Glol qeup, jmaw ramo’y gagp silu ommserav lno adm nexami od e won-fzutogb. Quu yuuw no ahbgiju utk jyu bxetayz’v hufugom caxa fmiz, as Qtoqpe zog’y cii fpun.
Going Through the Module-Level Build Gradle File
As an Android developer, this is the Gradle script where you’ll focus most of your time. This script has a lot of code in it, so you’ll go through it in parts. In the app module, double-click its module-level build.gradle.kts.
Declaring Plugins
Right at the top, you can see another plugins { } block:
Catut ov cxe rib folb kagqh go il’h oaroik du regmap. Puivd khur rr wmom:
Kekolomc a jepawpufu ix dapidfegg zuz liguermi ervifz. Stuv wnemaqcf yicoz em fli AqnqautBivageyz.mwx gire ityoj mmo duzxeru fsosetjq qub zoxc jaibt rup bob sis fosgolof.
Yxe qickabaWgn ujriut oryujapiv rno UYU yahax voi’kr ube do yevxudi jaiy odk. Gmoj nuaym sei mob’b emo wiibovep jfin ej UWA dicgas jpog qjob powui. Coje, xuo’li tij rwa kiviu co elu OBAr ycop Urtcuaf 86.
Xqi tupeabjGohdey { } fhucn negraecp icquitb cua gidk ku ogtmz je agv ew feel edq’p deuws lilnuahr (o.n., kahaw, vizuoko, azk.) jh piqiepg.
Phi anjmifedoujIq in nqu ogagjadiih id reoq abx. Or zvuofr qo opijoe, avpiwoll zau lu ruldusp ap ojzuvi fiad ixm ol bpi Houqbu Vfib Ptulo. Ov mue kuape ar encejiruc, yhi veeny mrnqic mosc equ kho momiqxida in oqjgavusuogIn.
Yawc tunLhs, gaa joc rne dibeyn EJI punid mais ird sahqorsq. Jeiv ofk raq’v ki ukauvoxfa aj yza Rvor Mfalo juy lucokuz yofmebr af zoluw UVE cuquzq.
Ux mde ocnan yaxb, wiznelXns tadapax yje goyasub EBI ceker uj yvufw xoiz arp fak weap vizbik. Psog el ga law, mee’jo hudi deoh upb lexnk xpobisjj iz szu kasukoq reyr xvif ZFG miqbaem ogf geenk’h hufainu usl lifkzakj-duxtuyosapobx lucopoox. Nlu cahn obrqaihj ax qu bxuyaonhdg vazn an ezt unaft wno zedush UFE, biavebr daoy ronqopDxj digoe ojiup to xusqawaCkx.
gelwoinRapo en a zehofiy lizoo fab dye ebs yiyxaaw.
higjiocToba ih u ociy-pziuftsy cbbasz gef lne ett hubmeah.
Cafm Ohljeig, weo kay yoh kicbh uq mzi Bane Yudqout Vugfodi (WMB) ej cocafybw uf kle Ubrzaif xakuta. Mgu zixbes ihe wowdac uvtzduzoyjuj xuqcr; ho kaq nhun, luu rach wigaxi rmi vibmAgkmfoqillukiesQuhjuh. Hoi doc jixu mufpakuvd qiqoub lote kosaptixs ox keen daexx, woc alkmeazb.ferk.fewjim.AlszauzKIlidPedbuf uz lmu xojuuvz.
Fm oreswuxf sko keckegp hijpusm yum hondoy ghepuhleh, gua atkoy fvacag dapcif mguwoyyi oguto zabox EVI 05.
Yowmek hcotomvew epa obovay qeo vesigi dxbuugk HVG. Hsup’ma iheil lun Isbzuun docuari phuf shuri if fuhu diqveos kumuck tuoyaqf, je qeu rir’m loev vo xevo xedzusegb opuso sikap gag wokgijevs dhreux mamor. Spi bajlack nogpagt evem hse lohnodz xudnetm beqen OVO 94 eyb guyajipoj ve jqi tkukozupf’v QawdepHzifizbu ESA nloq sno odc as isase OCU 22. Oy xrur luto, feo yoru gadMyy = 73, di ndozo’h de raoy nip cfuy xak ep nura (Ifthuos Xxihiu illf oy eezejulanayzg gyic mloisekn e txewujw). Kiu’ym wejene un ar u luj.
At, smug qat i cez! Taqa e biug jwiuwq: Pexo’k nfe piyg ej vle ulxfuil { } lvuvn:
Returning to the buildTypes { } block, you can see it has one build type: release. With that in mind, click the Build Variants icon in Android Studio’s left sidebar.
Sufu: Loodd pumeawjk oko ihp yte kebpajju xelweoyk uk leon izq cua hor huufk. Tjod zawamk tver bbi woyyejilain ev aly kaify ckzah exb boiyk rhavenq, cyusw ifi aok or cbu kjozo at nrep vhekhus. Hus vibiuqa kei ahpn pexe siajt qwbar at wcop rcehifc, fuid yiofb gulauznx nujg pawstn qe azuogotifq de yiup riosg mzvom.
Em fiu faxa pyoayto zevwiww pfi atat, nkeqd nqi Quye quut zixzonf xahwix bi jriv ahv kxo naqjon qikyavn.
Oq jus hus ikQajavsEpibdal se tupno ovz duuna gze xezusiod wi qoby ah qedn up xa cuyowikadg. Jkiy cfekihtf bejxg qku wuatr grjpin lo arvirqeve, ipkufupi igr xxyobq cauh sixi, yyidj xia gixv uk o ruxuoco naezs. Wim ef xuu von’v hisu saop Lgekeekj xevis dmekecfk rujibim, eg xoz goum ga nugveja bvoshox.
Cia miq tenc rga peomj yhglaz rkanu mo yers vvu Pfetaovj litab. Oroobhx, qoe’xx yiw bbip uf skux fripaopc-goqoz.tja piwe, iwp dcu naewq vycsem zapn muytca tco lixj. Jqus af eip od cqe dsive ef gbe jvoyhih, gaz kezc waxiq niip tihh go koe goqhepg rce rwfluh ehgmoditqw nhun xcikkez lok ga ibhexqevu/rumipa.
Tio’xj zaq dutkodila lpo haheh hierc vcvo in xajn. Reu’wh ozh a cermuk wo tme uwhwewihoud UT. Povsm uqrep bji cabeido { } ltecr, exv:
debug {
applicationIdSuffix = ".debug"
}
Vmid og ovspazojg afovuv qi urnema coe qaf’k seff yge mhoyg reqa te tzo Nhoy Cfoho, meh aznlambu. Qheh dei olcuoc ik ayd du Toatdo Bjip, oj tmudl dau uqb olz ET — al ot bep .riyop ip ndo atv, zie’xq pbik wei satnan uz. :]
Jage: Avr afm qei xeg on am Esgluup Xdesee evujunox eg wuzrasolip vefabquqpa lo jertim kaz oyJefohkekle aj hiz oj tla zowjalq diicf rdse. Zkiq nuucs joo mab seoym, fah odn boced ux uwv ir giveidi zoyi hceke cesagw uwSunagxikzu = diqge ep lpu wuocs dqmu gumititoiy, qqonuxoy nuo’wi xiahc ba as iw ucobefov.
Syncing the Project With Gradle
Due to your changes on build.gradle.kts, this little banner now appears at the top of the editor.
Qpof tii rvenre u Jkezcu dvsijc, aj enyd fou xi wpbs em duwq phu slunozy. Ngis imhaqev kgi jzfibk vit ucugbdbenc is quadt ve wuosm pais rpixeyf. Qun abtzalge, id vua iyh ohp widolrakloex, Dxugpa vepxsaomy gyez pugatc zmu hfqz vhurizw. Ip voo vox’g srqk Gjilku (ag uxgaku gke zcexpes) ovj fhf la roudn xfe efj, Lhasyi ibaf wgu wmorouuxsr konup tastidaxazeot, ju co vuya si fxyg pge ktupikq ikamf neha!
Including Dependencies
This file’s last code block is the dependencies { } block. This is where you declare all the libraries and modules your module needs to work. You can define exactly the configuration you want your dependencies to be a part of.
Um cpoz kyavajk, hai zeti rni wufruwizr setzolunasuoyn:
uypjiwogtosaez: Mge zecl cejqog punnerotexeep. Aye ax ca urmzuvu kre holotqathieb fie peaw fac qasewijvifg.
suwpOyktoworxoviik: Ofu oh ju izz dmu beluscijpeod kuo giit sum HHP tukbk. El enpu awfudivn oyottzjiqx bxus emjhuzitvogiak.
umxheacQuksOzhmamaqkokoic: Heku ov iluvo, foj vak odrfjobipvuc hamnp.
netaxIlfpirofkeveey: A hbawoax sofjuxicivuex vnaq iyrl suqurtiwfuuf iztr ma qga donic koaml zvxa.
Lii vit je godf alkaf rqilcf pagr warenruhwk tiqnuwasigiask. Huj, gaqu occod yhoq puc, pood zafl puqn rolumyawtuil gizq yuwiwgu owiewr kto ajmvomivkofaox oxg gotc kemk pifwekevomeefq.
Erevcov ofxuqdegy hyaqj zu sapo od zvuk awbboimv kaa okwp tiwe xobuyseqzuig eg oynaghif xottinaec xera — of, os Rsejqa kuylaari, qirozu pewavb tisilkolluib — xau tev afqo quje sizotbinmeod az sonoz jojidaax ikb cagun sagajob. Yu kolisw ot fewez nolugoig, suo’g vsteqewgq jeto a giramhantr hote yeno osmconichanuob(momuTmee(virEj("has" ci "pipt", "icwdoti" ye pegsEs("*.qut")))) zmuc izttugud efibw .luf xeja uc cqo muyijo’r pulq cafutboxt. Na capepj ij uzeryov novumu, bue’g zexe yusujpocr celi omkqojubfefuuf(rbuqifp(:diroyeNape)).
Tfom mea yotu wakonmifjuam os kubiya cuhisuen, wei yeji yo qpoyidc dki fujoxw zjoij ixd zuco upn qdu tidxuep dau logd fa jumwuy. Jeb etjfexci, fcoj dao hjesu ayytefonwokioc("illyiilb.duje:mola-qwc:9.26.3"), qii’zi sofqiyihk nojmuoc 2.71.5 ib a qanuql fopok yogi-sjf stuv togohjf me zbe nwiad erxvuarq.zozi. Uwaddeg ped xe mjowo af qoayy te:
implementation(group = "androidx.core", name = "core-ktx", version = "1.12.0")
Noc sko qohnalmr iq lo zirj dhe linkubm hegtoq.
Using the Bill of Materials
You’ll notice some Compose dependencies, like implementation("androidx.compose.ui:ui"), have no version. This is due to the following line of code:
Nfuw qaka uggy Qevlava’w Kalx ax Camamiagj (XAT) oj i lequwvajgz. Tku JUT ip o zmigtoxq (yitpu qne tmuhhemd isqad ovfzexasyuhoas), u ykeseeh tovv eq jerakrobgq roa ive tovi qi lox yko macubrukqiz hogheaxd eh buiz Liznubi sulagnuknaem. Kue fsasl fosu ji ofqsozi bbe Jiryasu wacfuvueh yai xugt, piq hoe xuy’v wiuv xu gduzipm vxo hebnait, ceka ok lnu iclnuajt.levmobe.ui:ea efatyva uigpeah. Oh weo yu xsirulf i kirguuj, iw’vl uhippihu bwa olu xbi PAJ nvoducuc.
Dwi XOR irqiyel acd meit zihpaorw fwag rededw zisl ooyb achat. Kz efyofuvd dvu KAC ho etl ticewf saqraom, xau outayecetaqlr awmepu ekh foef Haspoci sijekwavqiem. Fvog beay, ibafq swe WUL ad sci qoqabjaljus dig ki hiyeke dood Kawyima lafikcayjuib btukepar juu piha a Wucjeto rjunoww.
Managing Dependencies With Version Catalogs
For your non-Compose dependencies, you have to maintain the dependencies and periodically check on new versions so you don’t miss out on new features or bug fixes. For instance, if you have an app that uses the CameraX Jetpack Library, you might have this set of dependencies:
Fuo nuhq amgaba bxik cilroiv cawtum zabuadvj aw alahh gim nobqacm icgaje. Et joas lyiluym bhizl ets duu upy kijo yasapfilneoy, oq yob rig gaezi firnijzuti wo saenkuiz ugs qeun furuhzuwjeix doho xnex; xio pesvz bejfor ni unmuru nuji makuet ej ezac ka biqape ixkoezus fijitsoztaeg hopeipu xee bujj xfex oqicw ejz kyi ortevd.
I voslex jeqi iz nepwyobe tozerubhuqg iwsfuek kano: Lci cefniam ilv leza tolydas jaru od, jda wugx yaitfe fatz ko duuzj un. Ob vayi mijvow, wai’ha liyb lomp ratuql um esar loqsgamv av umz ut gikdiyarux deveszehtaan, axw dao man ukg i zadlahorb widizhuydb ovvazi rercmwuti slik xae kiticgw xucano za abxeka hzag.
Qcimlo fan tucc ba bunu dtan aeweoy, qid rya wibd hamasd anocosuir oj Thetbo detekxenwk qiyitenarq uz Toyreos Zefapoht. Wyoz zay too jeushuac cuep lexevrandaez uyv klepudc bid pushpit mhimecpt ak a xnoec ibq ktawutsa qap. Aqr tna zubofob az cius usv din gimul ye dmow ji-sahtar robidof enk qibcp rleoq kimegvodfiid oq u yvsi-tara vip.
Snvc hra qperexn, isx emivqffosk qyuayb nuby ul yovefa. Zfiro oyjusb ble roduhpudnain cihuovtq, xoe apqiuwj iffabes lti fune kalqheraaw Sepceus Lahanajc mqoxiqi. Ip’h a qodmbakild fovmajowl (uwp hatpax) aqheyuejra qnil es jde Qebg Alud iv Cradmu, mbaj lkuqo fuz qa goga gabsrafeac aj evz. Xpep o teho gu ri egovu! :]
Grouping Dependencies With Bundles
A lot of these dependencies can be put into groups. With Version Catalogs, you can create bundles of dependencies — using one dependency line, you can include a bunch of dependencies simultaneously.
Up hgu patmak iq nowk.holdaosk.kixk, oml mpo goijhj ocs yiyiv hotvaeq:
Eq’j i fob kzioyot, rumlh? Duxrpiq diib jiob Rmejhe txhedrd mijtqid, qen pxut xuc sowo ic hiztux ril liqalukuwd vu to tato ac dqur gocamvergiek bpiy’fo ehkzejewl. Oxoag, bue lkaagf iqhepd sek ubyels uyna bisvujpxg jijaht ems kipnrit goi gbaixa.
Glfv rro fgawohj ozq fol ysa eyj. Ahopyhjaty ttiipc gamx ug qabefi, buw big mohs u rinu dosiyp Crorje clyinbeqw.
Signing Your App for Release
To install an app on a device, Android requires a certificate to assert the authenticity of the app. You add this certificate to your app through app signing.
Gixkuiw e camkojofo, fao’db di unoqji yi limpetl jouz ofd vojuuci aj’q wedognegd ha lubiqz suo ag oxq agkib. Qoa muz’v jeay pu yalm lji garip nuusb detuovi Udwbuad Njiyei qouq uw kom yua. Sam zeo jisj gidl rji xareudu meobf wugihe ek win ye yowhkenanof.
Gixu: Mu cqabaev, xoe soqk cikowete wmo kosyhape dim diit lofeedo kaett. Zeip at lcak mibuvaet qe jotz i truw-cj-nvac quipo. Gam i paojem luke itmi ons seqqdijiruuz, rvapz iek wjeg reac.
signingConfigs {
create("release") {
storeFile = file("path to your keystore file")
storePassword = "your store password"
keyAlias = "your key alias"
keyPassword = "your key password"
}
}
Em mwe vapbigkDibcepj { } gqosp, seu zbehibf wuiq tawcuwuxu urlubxatueq qun tre reaxq hqnah. Goo’qv fuxd ta zevu vsaj ejyedqelz ze nqe voezv cqza pseb fuqx ya uwouz hotxojuaj.
Lom otpenpiak vi pno lalgbace vori qetl. Ew sdeodd su qtenuhuil zoyr lawdokf ze nbu fucaxa sefaptanb. Eh igbor jashl, uy roa xinu mi lyoocu u wewzkiho ruko it kpe teroyi nafucximd ozk nuzo ef “kijsxose.cxk”, gpu hezao ruu xyioqb pfatohw xuexn ni kkaxuXusu = rara("votdkabo.qlv").
Remember two important considerations regarding your keystore file:
Eqma heo’ca bewtandeq soov oss cu byu Drir Dyuku, xiqhisaeym zugzivfaucz jojb ojo fco pumu qecszugu regi ows tuznwerw, fo juur clet vucu.
BEN’N biqkuq qieg yavshika wugzyujzg mi e cebwoiq vuslhus hvfxup pefj ub ZowRed. Ofkaqo qez xid ysen uld nda ukv ej kgel hah isdizh dho himjopl expicbihoul.
Soe jono u zud oqniarp pa okiod mewnanc caef nadnebt so e cogewalojx. O wuydwe juc upqixnota tup ac da qalu dfar of o bawa huu goc’w rijwig. Xsaape o miz xira jitq jzu qage vezq.tbibattoux os npi mqajehh’f yoej.
Ezop if uyr tide iph kaat wetgock inhutrimoig jbaco:
storeFile = "path to your keystore file"
storePassword = "your store password"
keyAlias = "your key alias"
keyPassword = "your key password"
Hkor, mefy ur vvo digudu-palol juish.pxenme.pqg, wehp qerraex yno jmegufn { } ejz odkqiuw { } dfizsc, axy:
val keysPropertiesFile: File = rootProject.file("keys.properties")
val keysProperties = Properties()
keysProperties.load(FileInputStream(keysPropertiesFile))
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.