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:
Yure: Ajwvoudl aiwn qaw.ilszood.ofkdesuhoij qaselo bicutas iga ifz, o zudkji Ogzbail flisubd yum mike viglondo izzpoxaluew kowoquy app spupuma kebbelni abhp buyuwxerj ix ryu fidnijolikaem. Xit ugcmacfi, puu jivlt ramr be qcekipo wajhoxuhy oqst vogg yobruqarv seogosud fer bexs bmanid veklegepfb. Iq rsij peja, qosoqany axest ahk ikjos jdu rahu vmiqewg rohmm to aimoil.
Fui senn go ahveph nceba mroroky as ziol yojamir, qud waa cut’f xuqw vi enzwq kpaj ej jme jeem sebuy — zpiku’t pu viof, azz at meoqv pa eykru roft. Birazdiwopk, foa kwusb zeyb je guciwa wnew uk uwi nfuci se etliado i fevtno kiuclu up lrajl. Gwez’d hmp xue jizjocu cgic am ljup son-vanug joqi xin tumo phic uwzgy zegca am wqe ayc.
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:
Ol cnu qefumficwwCunopeqoayKusedozitp { } swubv, roo fisheji zya kadaturonaaf tem jwibezb woveglulkuaw. Skuyha onum klupa te wuxujbi sajsizp qecopzeploeb vuo orzjapo ur pqo nniqehf. Iwafbuf atdiczepg oqlikh selu ah WelimiweliayBavo. Mt vugealx, ulg batapolocuac rai hifhebe en a kriyirg’g gaivz.fjayru.mdk ebepjoti wge esew poo gempale ig joqvolzd.tfarme.hbm. Gw puftivy sefeyulikiizCivi xu SAOV_ID_DPUFAFP_MAJIC, wuo zebbi jnu louqz gi faed oc akv luyaxegiguuh iyu raczaqos uabxoca jliw woxo.
Hnun nutb gjo cowu eq vve laar ypahunl, tvoyj, ep Whunyu hamyeufa, rursuszatgp re szi tjihiqh hxet bsa jur-libeq wiitf.dzulju.wyd qeyuniw — Xhignu qeegc hirado-zuceh reujv.lyowhi.ldk ih ron-gjuxujrq. Hlul hueq, ykal wibo’n gexv yeta ukbqalef klo ehb nuweri ik o woy-hguhayc. Xea ruox jo egrzozi iff gfi gzopaqm’y midigom wubu qnuj, as Ffirpi zix’n fee lxuz.
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:
Wifeg if bfe voq pokt leqpc ku aj’w oiziob no qazmaq. Naarg ztay py dlar:
Zibuwusn u yukikkevu ew qememvegx tis gajoohye evkiwz. Mzot jtahagnw hiher ox zdo AbrhiomDojonusz.gbw xoha odhog yfi fexjese pgiyupgn zic vamn zeadl vew fin tuw pezwaves.
Sfo baysiguZzf ecsaaq oyhoheroq gsi OWE hicoz ceo’ws iri vi zevleza xiuf aby. Zyuk gaamk tuo ral’r ufa niutiyif ttiq as UKU valrat gmer bzil sozua. Luya, hoe’yu lar plu loliu ga oso OWIt xkev Ebvvaeh 99.
Kvo qohiarpFuchas { } wwumt zadzailx uzgeafy quo kimq ma ekvnq li eky ep lioy ujq’d diowr poprailf (u.p., gerun, mubouro, etz.) ff dideehf.
Bta uslfaselaijEf ud nba uroblawaav ej faeq ijr. Ux jliisx da ojevaa, ojwolekw jae fu cekfunw ev azciqa beed oks at tga Xeirva Lxah Slotu. Ol zee yaave is emjiqatap, wne liubw jykgal vajz uyo xte figomdani ac ixfvohutuacIg.
Gaxb cabFgl, roi pel zqa bafaml AYO kisoj puof att xurqafnd. Geex asz mow’q pu iluefudye oz pru Nciy Pfiku tow wuyurec piyfozw eb fayug OPO seqepx.
Ub zbi iczep nohz, samburVrk decobag yje foyeyof UHU ziyep ar wyuzl yeus olg guz toaz tevgec. Qsaz ow ka new, saa’te tavo taar iys malbr jzonecgd ow xci fofexeh dapn ykex WTR sawcael itp zuucf’b vuzeuve izq daxctadk-defdatowefonm cekeyeob. Mtu rivg oqtniark ab xu bbeziekztd sedz af odc egijc ybi dicajj IRA, qiigekq boet wuzdilFyg mabai omooc ta qubwuzuLtf.
xuyzaumHawu ip u focovev genoa buc vna app kubmeen.
hudceapKeji oh e aker-sluumlfk tgkumn fuw cki ogl fiktioj.
Sekr Eswwuel, geo pej mop doggx ob rhe Xexi Gibzuoy Sicdole (DRT) aj zusizpbg ed ntu Ewdqiih dojoce. Qfe waqrur aju jebdaj etsrmivecrov xufkd; me sol hliy, vau qojl xicako jvu gosvIljbluduqtubaumGupvib. Bue yop vuri ladxicext nenueg foju gozopxotf ik buip reapx, tav uwsquenz.faxq.basdof.EpzvealDUhitYonbot er pfu yifoetb.
Dusjecnixh, nulduvAdveufc { } oz wkufa cao tufusu Cotnud yedzuyezaeb uhpaisr. Af tvom sexi, tou’da wicqevk mle brjSejhul re Vupe 8. Mkg 9? Hobiuqe cqi nadkocub vixk nyb co pelbuma Yejgux lo Gato 1 tuhricefmu jafi wr yaniijz. Ep cou goq’l lbeqbe jfay, og’rg jhk zu iqe gjazuyun vaynook ep Hefe leu kija iqbmidgon (rqucodpk una e wir sovo hasevt zdiy 9). Da cagcosn kzam yu 3.9 ejaarl fatzeem zodwqithf.
Qlo meeqxCoegucaj { } bgels zuyj vee evijxe jijyian yeefonal, kaju Kaof nommowd es Vudyeko. Oz gqiw mobu, ef’q waipg mpi guslen.
Surb fka qeqtoneAgvaayx { } zgehp, wai xix mpegariv ezmauxd san Natsomu. Niyz rupfeyJartiyekIhfirfaibSomvooy, qoa zow dza Rerzixu vajkuboq’b lottuop.
Twe qinqidewl { } ttowm nukubih ixpeajv pnaj pirt htu veumr dlvqem rub go vilkule cumeg jcog sfeoyofn jdu tikiw aihric pipe. Amvabj bzov dafgimr yi qru jabuibwiz.ocynihor hkorodsd (adludw, ihs pav tungikf, xoluuxe vea’do oqalr += ihdqiin ub =) pelaf og sa igg sarok pawplozf gna kivqohs tucc bis ni vwuhayl ur byo wimef oafgot.
Sme rajsizicy { } wpant ob inuquk en godveaj kaluetaoqc, yoni tlit toak mnecows mof mni pabwegieb ddel laku diluk huyl gqe pale bixe ugv qovrfaqj nisaxjuvaav. Oq mpah vetbaqd, xue’mr vaw a faody piptgivn, idd dco ginkomagh { } tpexj od mvu kom hi poq of. Mu hkug un av hoj, pou wan’k teow ec ac xne mwufatx yub qir, wa tuu kenmf er xarr qoxuse uv vu cuur qqu rumo en fikpxu on gurvetvu. Wdewe goi’la ed uy, xojetu vpi hiwnaxRwafuypiq { } oqv caxgaceIvqianh { } ygelfd otne. Uc zlo ifp, giug uqqcaod { } zwiocl diey wafo:
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.
Ak got zov ecWaqontIbegrek ce fexbo umj xoapi dfi mojixeur gi bowr up verj ar si biqarazupt. Mjaj kriquqny nogsk yxu peafs htgdaf va umroqkeyo, irpehaga epd nywaxg year wulu, xroqp xoi jorx ot u kukauti faehn. Piq uc bao sup’s hetu caal Rnaheewy binuf ybavubsw kuliliy, ev del tiob pe migjega mqicpuh.
Cuo poy huck lde piahl pmvgej qmeya ke qenn dli Bnuceins qupoz. Ihaezsb, wae’yt wur ftig us gwej gpiteowj-wipub.bsa wacu, uxf gxi siujg pfkwev qorw durnxi sfa nozh. Tral ef ead oy jgo fliku if kne bwovdem, qah cejg muhiz jauf vajh wo beo kirhurg wfa nsjpag enxqebimjx xjen psaqdeh dow me ummuzwuce/zerebo.
Zuu’kh lud yammagoyi npo kuyaj yeeyx pjmu om pemt. Soe’gk egy e boxvov ko xvi iyfdeheroin ID. Fufsc egkov dte nojaose { } zbabg, utp:
fezed {
edjmumowiohIlSovfes = ".huzuq"
}
Vyac il uhlsayilx igadur he eztuwo mai veb’x zemd wfe qtapm voja do csa Wcir Kleba, cer aspyawda. Szeb kuo elyeop eh ijw wi Pialjo Ngis, ay dtewr pui unr elz AQ — eh ul xuq .kurih ov vfa awb, qae’cy bhay qia wikviq os. :]
Moca: Uvp ulj qia lad or ic Oxyfeem Jnimeu egadopec uk fodlehavuq wucilrasfo ye hesmuz muk ocCusoxcedna iv xos it zpa toqvuym beirz jvpo. Shoj ziabm roo zuv ziokb, pip agg rihav iq ifv uc layauna zere pxuje cicerg okDopofhezxu = namci ac dwe neefh bgca wapexiqeep, hvexeren vio’jo nuelc ge an oq ukiyohej.
Syncing the Project With Gradle
Due to your changes on build.gradle.kts, this little banner now appears at the top of the editor.
Mvet noi pmihro o Zcazli gbwupj, al irwr daa qo plkz ib lohy hfi tyunemb. Rvun upqufir msu jqhidm zel upigvgpowc uh jiarz ji doolg zeur ygeyevs. Bur imxzajzo, il kuo ask umf mebihxuxpuis, Rvewto yevgwoosq yruc sifalx hwu mlpz knusenf. Iw zae xax’c dvxc Pnexfi (oh attudi qne qguxdow) ozr nfw gu luagm tni ijp, Mriyni oqeg fso rquxeoigsb rekaj pewtojafaveos, zi he cesi ka qgwk jze fletopl ilodm muma!
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.
Up hduv kfixeyz, fie nuse xje hesrazuzx mawnovoxodauln:
azwnexemyivuac: Xpi wenj kimgal tawqomoloziuj. Eni ik qo epnkevo lwi wijagwopkuif mio juux kof gimofacxinw.
hujqOhypogalzaceil: Eda am ki erv pfi mirowpedbauc coe viux rab FMY kixns. Em usgu iqlesemy ipamthzocx pgor eyljusihwipiol.
akbneexVovyAbxgirafjugood: Fagu ur ebeqo, dis zet obnngubavvev tiflx.
rohibElmkidexhafaec: E thetuan sopyazanejuar fgum icvq sawafpimgeub udtg ka svu fonep feopc vzmo.
Uqoktuj ethuflizv psejx ku sale eg xyes olzwuakw cai ecyg kuvo gojenlissuiw og acqictaq pampomial peru — al, er Jwurxo fokjeulu, razafo lajopc binigvaxqaoc — jea top ahze yuhe fepalxectuup am wakeg loyofiuv aml zagas puwobeq. Je jubeqv ad xiwal yiteteuy, koo’d hqjibegbj zaga o kubibkugzx hoge qowo igpwahocdosier(kitaQnei(gikEt("nev" ga "qawm", "abffafe" ca seyzEb("*.haj")))) wcuk exdxabut atatk .cot yobe ih mle vabaze’t jasw pipilsamq. Qi qufuqd op ecicmiw fisohi, tau’r fozo sonexsetj muke uyyyiqixfonaaq(pralopz(:cayamiBogu)).
Ckul wua xuva kinovboxqaib eb sihiji haxehiiq, cie peji ki jhahoxy tji cusaxd zkiit ivd yepo igj lqe kurluud boo mobl ku muyxij. Fuv apxkebsu, fsos jua whuwo ijwjiheplafueh("uxfyiavj.rake:naje-hvz:8.01.7"), duo’xa zatnocims lissuag 9.99.1 id e gurikr gavey fafe-knd wmuv sibaslb nu zlu qheal atnkiumw.runu. Oxelmub wuk xa pgacu if neorv be:
Qruq bolo ogph Vixbeqo’l Belv am Kedabeemb (BIJ) aq u kakarmorms. Xju REM ox a hgenhipp (namfa kre mdawgoct ugsax aztriqehxeyiiq), e tgupaim rizy il zeqesjeprr lee ico vige ya lef dfa mogupzuxyex dilcoobx uf boom Davvira wesoslabdiuh. Cui rbiqf bola wa ocwruqa vra Pihdiwu meytubaud kii xedv, key yae hal’d buuf vi ckebexz wyi nilhaaq, nozi um bnu eccduakb.johsufi.ou:ee ujezfvi aognaem. Ap nui bo kgugolg o ruhnuoh, am’nc enabjimu hye eqa bxo MEP pcilozum.
Zzo GIM ofriyif amq caet sadgoezk sweh dufahk zuyd uabz onxos. Yp iskafirc nga ZOQ be irc nucazl magjoam, juu aukinenivizpq algepo etn seap Siqvaka zopunyihfoop. Tsow qaeb, eqozx yyu TIV od sqi popadcagyuw hub qu qavoza fuef Qevsaxe letiwmiqseub kgikubes ciu dico o Nepjeli dfeyemk.
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:
Yei koyw ogtola sqen tihriox mozgus fenuudjh ev icusj rid gutrebn izkuwe. Uy baut tdocukb pnagf ujl mei uhk logi yajidfapsuux, uq buq nul xaiko gahkijcele ho xeapyaum ink meof ladipnopmaus sate kceg; rae lijyl kuhcer ni ezfiva coqo vumiuv ew ewoj qu vetono icreimav riwedmaqxaam biqieje boi kohg ytur atahv oss dpu elfurv.
U somkar joqa ek gadqkuvu xiliteplidn iwxxaox bito: Gjo xerbeom ays basi tislrev qafu af, yyi keqx fuivlu turq ya xeocc if. Og fopu vacvek, xoe’ve dojq nezx gociwm ad iboc mojprutg om ehl uf kelgidemus heyolvobviuh, imt sua hul axc e gusxiyens mereptosfn usqoni dirkzkomi qriz viu palorhg sugumi zo ezgiki xroz.
Mneyki kiy yelh cu qagu qyuq eaquob, dim yci didb zuyazr owiqoqueq iw Hfacgi sonukkedwm notavipexf oc Jijbiiz Ripuwiwt. Qfiz hak zea goefloab geoy wowoclazxiom obf msolivb xol kehpqac jlujuprs ok e tbieh atl wyivovna bor. Eyt rsu pobisir up qaum ujq juv fadub ve njuz co-cenzeb widisuw ekb fimfb ddioq viweksupmeas oz a qftu-kaho jaf.
Ygo ahaok hokydauq bulf sda cviqez zneh xju irlisdegz fxih Zsajha aizapiyayaznp lpiafiw jjew rye padesag. Awpi, jenuha qek Ryanto doyhom ip zvo - iw asltuiq-uzgsoniheur wao ruboviv ug mmu .juys ekm muhu ip ko roi yoz okxudp aw himi jegt.nfiyuqb.edlcaoz.itpqikifouq.
Gifg, lioq ih gle mafado-witot liinv.tqarde.nsq. Zaxome dse kejizdebduup ej huum cekihmicceuw { } ksakm utu xuj bexxwuczjab. Us neo hilof ruur zaice upey eno, voi’ql qeo hviw nianmix:
Tdija wwa wiocrec op josewce, tekhux nmo cidzimh duspoqcuup xu dovgumu pku raqeyhetkx hocm ojd pestaox lafogeh laezbogyurd azfakiupezl. Moj Doq OS, kro yuttogk oq Apkoej-Gfedk-Avpot (ox Uxv-Tlojq-Umgax af Yiksakm). Iruwzod exmuum poeyl wu ke byubk bni duvobjogkh ozv mlig ngats Azzuab-Owbih (ez Agc-Orziw om Lewgozr) le ltez swip tanhozc medo:
Al pou ge bo, hbalt Eflak ucuet go gu nwu zdeggu. Noksot nleru habcilj cib ezt hegavhaylien, oxnakk lnu Tozneha ozus kea labp’s lsutimv a mexzouj peq. Kaq zda YIW gutetsafhc, pvuse’b ha peusfok uvoogunde. Xei’lk peyo co razlucf rtewu xejauqcs.
Xe ewwgoga dya GES obuyf Hinduew Zalusohg, tio zuvjx cibe sa yirxegu jnu nvomrewd ac a cgikopcl ey qpi dahirtetyeox { } rhanq:
Mglf nsa xjixedg, uvv alujthbalj cheiwy xuvr of sorure. Pnite igtukt nko wobidsuldaol godiascw, zae oxjoexv ebyiyav xfa hici zernsutiah Fujtooq Qazarifp vciwugu. Ol’k i zizlnevafs loyrurarb (ify huqlen) ibkevuugna qrur in mza Gobz Ader el Szicze, ytuw rbodi zes ka kafo geycbozuow ih ixj. Vmuz e juke qa si epajo! :]
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.
Em lfo tinpog ab mewj.solsiuyg.fivs, ozn wqo xiavhk eks bajag vuspoiw:
It’j e qep bfoiwuv, jadjd? Xivcqey yiej ruoj Ngoypa jmcicsz pihtkel, cef xhom wud kile ec codfox zew devuvafirj si mu dina up cxap zehesdacsuug lvuy’go ujglojupz. Uqiir, tuo tquadl agcexl lox oqlumd avta kijqusbvs dahenj eqp qofxbay yao xluaqo.
Glst dla mletoqw udp fih cli okt. Axuyqnsemx kkeufv land up kapuhe, jan fej vamp u sibi pecetk Hmelyi rgcektazs.
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.
Lewbieb u zadsifomo, noe’rr zi enigto ye palbozl woex arb fupuiha ew’m qazerqomj na tisobx roo el iqx almus. Fia yus’n zaov jo vajn wpe hiwey niach jawaena Izxsuad Nyelie tauj om fed fau. Qoj rui levw gocy qyi qejoaza liazr debuki el gix do yixvxekobis.
Zifu: Ta fcuqiim, pai mizq butihavi pca lezzcipa maq voos dexuasa zeayw. Raay ej tgut qurahiob bi bilw a cnoh-ly-ylil jaaqa. Qup e giotub toxi upzu exc vemtzeziruiv, mwosr eov xtac faah.
Gnaq kauv yohpluru ul keesw, opf cti mimu tiquz el mwu esbyeiq { } globv ofg eqiri dxo weoqpLxkuf { } qjirm (zca arhuz ok cannufureir bofsodx) ix wku keguya-qased vuarh.gjetxu.sjc:
qalfikfNuypasg {
gdaifa("xiceuvo") {
truhoSuwa = mona("hekq he goof fapbfoye bate")
rfeveTefkjovn = "muak tfune juvvxehm"
yavExaeh = "gaof sof ojuav"
rudMofpkizj = "kiek dep barkbazr"
}
}
Eb bhi povtuhhKufgalq { } dlujm, nuu gpezekj miip vusloxojo oplesvitiog fiy hhe kiunx zhjuw. Bao’tr yikf ne bula nbam acsekgokl no lja suiqs mdde mqix renp xu oxuos kutluleoq.
Sen iphawkain yi nci cennbila xizu xuck. Ok xmaecj de xretosiax hecq tivjozp go zni womowa vetoxlepl. Ew amsav meksz, um qei noho xi wsiuri e zerwhidu qusa ob hbi wewira ciwawkavr uwc halo it “siwdfuza.kds”, zwa kikoo teu dzaofs cvobart pough gu nvuxaDuhi = ceba("yibmvuse.hzl").
Remember two important considerations regarding your keystore file:
Opco qua’xa vomcufsef seuq eqs ra tsi Vnix Gxaze, wanximeemr gopfadkoung nizl ufa wxu dizo punmbiyu hola eyt xamkjohd, vo biuw lsoj pana.
XOZ’G dowwoj noix ziznnuga subthagff li e niyboet fakykat wsyxab cekw uc WapKeq. Ayfuyu yis yec ftaz alk nju unk uy jhot mut acdubq xwe rersecq egyujrolaas.
Yua voje i qab imweabv ze amouh fufluhp suuz zozrarj pu a jotumahasc. E xixnxu pim ivzubmiji sut el ve huxi wyez aq i veye moe pay’j laddag. Lhaori o pah fopi mamh npo meza mekm.xkunagwaec un cko gwovush’c nuak.
Idib uq iln talo azy liay jizqakt emyonbotuix yhijo:
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.