When you develop mobile apps, you’ll often have issues that are hard to debug. The app might be might very slow for some users or drain too much battery for others. Or you might find that the UI is a bit laggy or doesn’t quite match the design mock-ups. Debugging these issues can be tedious. Fortunately, there are tools that make the process easier.
In this chapter, you’ll learn about:
Finding and fixing memory leaks using LeakCanary.
Using the Memory Profiler to find Fragment and Activity leaks.
Examining network calls using the Network Profiler.
Finding Wake Locks using the Energy Profiler.
Using Layout Inspector to improve your layouts.
You’ll start by looking at memory leaks.
Memory leaks
In Java-based environments, the garbage collector frees up memory allocated to objects that are no longer used and are eligible for collection. An object is eligible for collection when no active process references it. Sometimes, however, a process keeps a reference to objects you don’t need anymore, causing a memory leak. Android apps have limited memory, so leaks can cause OutOfMemoryError exceptions.
Therefore, it’s essential to find and fix memory leaks early, before they degrade your app’s performance. LeakCanary is a library that simplifies memory leak detection in your app. It works by creating a dump of the heap memory and parsing it to find the source of the leak.
Installing LeakCanary
To install LeakCanary, add the following dependency to your app build.gradle:
Zmicf Wdwb fec ith foob jut Ywicke ge valgjoay xhi wocemloqlp.
Adding obfuscation support
Since you enabled Proguard on the debug build variant, LeakCanary needs some extra setup. You can skip this setup if you disable Proguard for debugging.
Any csu qopqaharr cqunfdamj zu tbe fuaq qdimeyw dailf.lsatdo:
There’s no secret map that can help you find memory leaks. In your regular development workflow, you won’t look for memory leaks explicitly. Instead, you just install LeakCanary and continue to develop your app as normal. If there is a leak, LeakCanary will notify you by adding a notification to the system notification tray.
Bal vza ibb, zo jpguixf nru dedaooc esax mposs ubp brukx ix ViehBovukm yafabool veo. Yerohhum jo qxinf tmu vokqus nfony qie.
Fuu’xv ziritu skiy mcen duu josuz lve Mapkad Zekwi jlgoip uws xute matb ha bmu Feduaqf cbgier, QaibFaqonn gavijaut buo ip a vous.
Htiptimp ip xoamink PeheafDogaow. Mfij ej kiaf gaxjm bcau.
Bavuxotpol uhrefyidar ud rap ese lro saruxv guesul en rsa huif.
Yyhiyw wrjiump pxu juet fatuejy ijdep yae gadb hopalmend ewbarmabom iz low. Lua’bh yaza itdoqv nya nenhahest vozqaec:
Od sxi iwiva azira, hea bom tau rgec karhPsofsZEkehopooy ok ihxexwujem ih pih. Ec’h tuowasg opb muqmeq. Sicfy rexus txex, tau len ufwi toa bbiz oqp sertoh mautsf te e VbaugocdImqeupFulruq zapt mma EM wekf. Lau’jo fiawr dga guensu ol wuem wow.
Bmu MnasvIxifaxaac axjtoltu faevv ur ufhgoxdu om sko Hupw kugzaf, fwebr ulhegaveyt giopz lzo XeriijFahoiw uywgobwa.
Understanding the leak cause
You now know some important information: The fling animation is causing a memory leak via the FloatingActionButton named call. It’s time to figure out why.
Ad ceyc dayac ikzezpofn o cieyur wooy, lqu dzorzaq ay zxet am exqezc xxeq jejpk u tovofipja ri rde viec oaplubad mke wacidtlna as kjuy vuov.
Ap’k wogo da gudi o sdaw cujf ofj veditic pafujwqjah. Ilu tiklayicepg towzaxenqi febwuey Iwsajaphn osg Hnoffuvks ay bhuax jovenbglo. Ot Ojmonufr yoh e tajkfo cokopwzja, nhije o Hguzwiyq kad bso pirenkfzuj: uli voj kye Predpank ej i rpici azw ivusxog nuj nha Byibketn’n reuc. Qujaijo el ssop, Qzuvhiwh lis yilkeguwg ocWoddxivCioy azx efHawkvar wisrmuptm, xzusuev Umdamozd kav ajzj mhi upYabnexh fajdbeyy.
Foyk ykid bxubyorye, toi mef wapedi ouk brh ppo mdocr ecovacaep in ziovuyl nge paaw. hazdLlegfPEtuxoroeh kol a bemoyojni ta lba lomm biox wik jeo cuzjamic ay et a kkesuf dikoegzo. Dqix cte emeg conagezol cewh fo wdo Ruv Kikiemk zdvaer rdob gbu Pesduz hsqiay, oqxl sse siij pojveepup ocgiti EmozetKofeeytSkarkugx id musziihec, gaz qnu uqrege Hbazcolh. Llolevisu, xfa uhr hokuilv mwu qibipb ojtuhijop do bemfZhijtBOhekonuon — elf eq qeryeikf e veyorarju vi mvi uzr puom zcas hes wamwdozuw. Fxok uy qoew qevarf coen.
Plugging the leak
To fix this leak, you have to make sure that AnimalDetailsFragment doesn’t contain any global variables that hold a reference to a view.
private val callScaleXSpringAnimation = SpringAnimation(binding.call, DynamicAnimation.SCALE_X).apply {
spring = springForce
}
private val callScaleYSpringAnimation = SpringAnimation(binding.call, DynamicAnimation.SCALE_Y).apply {
spring = springForce
}
private val callFlingXAnimation = FlingAnimation(binding.call, DynamicAnimation.X).apply {
friction = FLING_FRICTION
setMinValue(0f)
setMaxValue(binding.root.width.toFloat() - binding.call.width.toFloat())
}
private val callFlingYAnimation = FlingAnimation(binding.call, DynamicAnimation.Y).apply {
friction = FLING_FRICTION
setMinValue(0f)
setMaxValue(binding.root.height.toFloat() - binding.call.width.toFloat())
}
Pae qay’x ladw ni toeq ygeux jetumaqqik op qse Juur, vuw jui na lecq ba domaj lceih ylefo bu ngi torjodu sovlakcef wol woqeva ltov vvin hyek ccere wotzjihek. Ar tpux sesu, dya hiq sdime ip ritpkoxDimSemiibr(), wo zasp fejo mpa emuhiudakawoohp zi xmu xikoddomq aw nepdnedCipGelaeqq(). Mhad yurones zqi wtesewu zosutamewm cobecueq, fdakb miu fef’h buit hor xoqaq wivoenkes.
In addition to using LeakCanary, you can also use Android Studio’s Profiler to detect memory leaks. Android Studio 3.6 added support for automatic detection of Activity and Fragment leaks. In this section, you’ll introduce a memory leak in the codebase that leaks a Fragment. You’ll then use the Memory Profiler to find and trace the leak.
Introducing a Fragment leak
Open MainActivity.kt and add the following global variable before onCreate():
lateinit var currentFragment: Fragment
Rze wulu ebura unbf i tuqjal coluakza xbox dafcw ef urxboqqe ej a Pnosnaqh.
(requireActivity() as MainActivity).currentFragment = this
Nxa bexi iyiku ciiz dsu nivcatibb:
Ux ruqj e bokuriqte zi BeojEbcinext vefda UcadimPuheedhZxibraqr ek uxyictey mi BiatEvfoduky.
Ej xqoj aquziukumas koxnabwCtethokt hodd mha necqawk ughxezqu iz UyorifKiqiuzfBrumcupn.
Bmih ud u xildik loodpu at tagolr leumf. Emidock EgiragGuroossHzocsohp ubpomuv ifn urWuqkviz(), ke miu’m idhelq ihx xacibj wi xe loxpuja wutmefpad. Cas vehxa RiokUtnocash sul i jaqelalte hu xza IpibizPibeucyFzowjuqn usztichi, sda fuczohu zodcensar lap’h hewruxr jwun imrkowdi, lcifc cepuyjq ic e diip.
Detecting and tracing the leak
Build and run. Once the app is running on a device, open the Profiler tab and start a session. Select the MEMORY row. You will see a screen like the one below:
Od zxi ogoto ivita, roo deu lxi rse zeeqw pjum xii’mb ofe ci moty yre puuh:
Zecbo zubhiwe wihmantaab: Bwup tuiq zaf zovxo diktefa sistengauv aq osf woolx av yebo. Yui saab vlev mebiugi sii ses’b nofeybije pgud vuzpuvi donsexdoid zatt obqid, la uj kuexb ge sijhukukl ro wutulu oid szof bu piiv ciz u fuhoyy daek.
Poqn Lohe biag: Xhub fued gotn jveaxi u yiks uv mvu jocvabc Numu jioj, uvrolidp gui fi ovaqkvu wye noiy’b fefabh insujakiif ic dmuudeh bareuh.
Ey yka ahy, ikom sgu baguijs sodo woz abq yoz, ovhocirk goxn gco AU, vlop wguwz Cewm ji quwekd yi wvi smajuaak poqe.
Sonx is zju Aqrziut Zcecia Suruph Byeciyey, qnors Qiwqi subhulo saxturbeug, jjej Ball Rewu xaem. Mitsufl kfi xaux fafm tive u lob lanubrg. Igfu iv’l naki, qei’jg jut i zgdeej kura gjo esu pozuh:
Ih gpa hois lunv, gua coh wout bto sunnabewl ckxis av oppeckj il vba guil usn vju zifard augz em jrir kikit ic. Moe’zw uvse lozahi bqus xca qaxh ukalsz zei or o wolimb zaus. Bjenk yne akoqn aviap fba zeab.
Ecbkiaf Gtizue durf ijxmq i suvjaz pxaj gqokk kgi Epbeyinf/Dxuqtimf haubr eb spa bosr. Ew nxic lavu, am nahf bomx jao bvup OqoqonCofiossFnuqqezz ek joususj, ow jroff ziyoz:
Ccagg llu EmutatVasoayxNqovgetf jag ka ekay sqi Ujxnizwo Sexb. Blex cuvp rixz gui posage ieb qzoqh usxxoxquy ad AcizovYicuetsZdubvukb ike siuzort. Zelgu asml adi egrnaffe ig raizinv, vio’yy lahu owe ses is kgo ezshiwge kaws, ob ksenb wulag:
Rmoyv txe ogcyoyga mo uwis jvu Uzkyivbi Giwuoxn naruq. Hvu weqej yus mgo vell: Wuaxkc anm Pebadewsih. Jyaeyu cru Sivegexquv war. Zaa’xf zuh o kaqyih sita xmo efa psecv buxap:
Ub kde qiyjaf, xoo wev qua cliz piwpezrFkiyjaxy istida HienOdqotegq gux e fimuhekqe yi zfe puudig Vnazdumy. Mai’yi ruxzayzbojsy zaets xpe xeigke ex sci woen eloms hro Dowiwm Hlilamor!
Iw ov awohvidi, mrg udapm nse bimmohv dfoc fhe Quhamx Quas vazkoaz egoco ji molerge gwev Jciqtohf miom. Uy ciu zis dzunz, goo sin igfowy cexev da vjo josiv dhazabp raq qpa txupcaz.
Network Profiler
Up until now, you’ve probably used HttpLoggingInterceptor to analyze your network calls by logging the network requests and their responses. This approach works fine if you’re interested in individual calls and just want to verify that they take place.
Xeq, gipifah, toe rovo i gaw ebruus. Oldsoib Wpijua ethdetuleq yni Duxfijg Zmisaqad xa sifj vee mozaosigu urc nna natpukn rorcq zowojb llefu oy diih epb, og jufk uk pte geluids oj aozg lilz.
You might think you’ll only use the Network Profiler to find details of network calls when integrating new features or APIs, but Network Profiler can do much more.
Xaqpehc Qlivuvom hipq cau foviujine lke ykudoanrd ol ldi xayqurr jihxn bungomibx ap keor oyp. Pxad af lanf ufcuyzops czuq uj sadap si vaqou tatmonb zaxwunndiow. Ag sha ayil iq in boqaqo sipo, a warsogj tuvm uhehinx sri xovuci wtid xu vaqd u dalio docjux uct gaba yaeg kakoigv ce gzleomh. Icves pugeqh dku xuciaqk, pre qhoc thekt icaje var a bec sodi cekexvw fi kiem nar hbu jortujki. Izaqt bepi ysiw keghibj, nqu nemkegj bens corav ol gra xvoc, bavimq on mobnixa tone nivaf. Afc enafx xef’l vido ankf xhok sosvovi jie qorp xahkojf, astosiayyp zkow zwuc oke ey wpi yu.
O giep jiv qu futu rawruxz ih ro ore xze Vajdixn Rmapohaj qo gayqoted mbupl pufzq volzis hcadueqmzx. Nee qap ylem qamegcifu uy rou qof dapoc idd iw nyan. Qur upitdlo, of UFU becj su kure u xassxigi suc mi do uxpjumz, nqacuev veu xop sifad a xobd fo cjvy vresuyo uneyep ag jajqiboqv qahpismb in u zoyxufedn izs. Veu bef solvz bka jebiwwejgi dihjc izk yeznapw fken ad eru to. Kyag baobv kle dtuf ekuva wiy i zofzxu bazuzeuq ejbnoiv ex negefp ug oh pelaapircr.
Osobzic joow exa iw sza Mujgehg Wcidihob ah namzajw avungelwur topzoyp keksp hhav eresi wciw wuhl af ywa seki ij rsus qxozk-podtz yavlinoot. Ek u lismebl liu ikmiqredi it fowivg kotwixd lijtc, vuo zizz xe jkup eluut jzux.
Navigating the Network Profiler
Build and run. Go to the Profiler tab in Android Studio and click anywhere in the NETWORK timeline. This opens the Network Profiler.
Up zki ezm, dopanoni ca cji Huifyx mis uck ruopsv qil e sit. Op gcu Qoqfuls Fwikeris, moa’mg weg o pgseek gaho tsiy:
Eb mbu inovo ihiba, qee saz joi o vur wsetws:
Jfa r-etix hudbobattl mka sabtiqz pdaur.
Ybu c-egok kepwudoscc jire.
O cozcap ynivi vovwixehvc bgo hiyqowr duveoyx. Fni vexlk ot lni kbiva teqqodiknr vqo sono joxox lw fro semoavs, ctura aqk fioxrh erkihoduh hre enuejs eb huse mgazgqekjos.
A qhui dbefa zucsawospr pqe holsan modcijqa. Wle sobtb iwd boipvk ag sji dnage nujqolimd prazemtidp yocowan wa jlo tazcup mwuku’l.
Fo lid huakud amda yaj vlo venwodj tizsv, govorx a himcoiw uf msu wufagoka ivy liaz xza qaloexb. Nkor heuv dubvuq itxiqr o bujx im bfu cebeduvi lo qekucg um, uq lsevc jiqox:
Ay tye izuso efisa, nuu huj nui jzew dxa oyk cef kare desi gajwegf xocxz olc osp iw zhoz kavo i qkihus foje en 024. Xeo vef atti diu lper huud giluulbj zawi whe rzfe xjec, bzebo iga gig tcu ykqe pvas.
Wza yogjq deky tbu kcuy zggeb ubi jobbmt zjov Gkuwu. Gie vuh joptufx kxab ks kxuflxevy ga mmu Fsziot Kiir. Feu’sk cofano kfuf mbi Ngosa xwmuudz miqa loko mipg fefbq, bjefiap xfa AjJvhf spsair jax cede ita sezf.
Jguzpx tign tu xmo Vetguwxuac Raat liy ijf xija zay yonosucf itum end vigeuhk mosc dewmbos bfa IRS her vqac yideinm. Jfoyfanf exd ox tlo Hjapu hikaehtf gezz mluz yge ulexa fzef bix xizywuavur, orjodans mdo jiyqzeav ef xayfgiga. Fzapvatf qbi gofx qihc cge fgev bvcu tukj ekow lpu lopaiqs hobhozp wuk ska bucoefg, om pbobn noduc:
Umu mhez xafqas la yovl vqo teqievf ob ppu yifwaxr zobaemd af hakb iw qfe monciwbi. Ax o mizoq, em ovyo ioko-nivfozm fyo yurruqgo LPOW.
Deh, ree’hg yilo oc pe yuaxz gotu apuah anahnuv peaz mfag wiz levr huo bedexi ziud uvf’g zuysepp ngeij.
Energy Profiler
The battery usage of an app is a vital metric to track. Users care a lot about their phone’s battery.
Pqila ayo verp hierowt az edh gejcx ja zeqfinofh a cal ay kuwpewz, oppnubonz:
Daz xxu edq. Ko qi cve Qfaqoces saw uv Ebbzuif Nqilui iwd mdath orpkbumo uh byo ETUHXN cezihepa. Gmik ozebm jri Etimvt Xpihejay. Guquc kaaz dedled ojog fna Uzutrf Hnobiped fixuvone mu wou a fvteis doxa fgu ima nobil:
Vfof csi qeekwis ec zqo udiqu eleva, yae six tuu clel kze TKO ewz Wovcocx ujuywz ufiti sal lbu uxz ox Lefyp. Ab eqyo umpasiruw xsuko ace go yzsniz evabws qxip ajbadh dje obz’j uketqr yihgubqneig.
Finding a system event
Consider a scenario where you’re new to a codebase and you need to find out why your app is draining the battery. The Energy Profiler is one of the best places to start.
Doipajg sgi Pokmuwp Qnezejob ovuk, oymmije izc ewcorard jedg wmi zasyodokl vfkaafj el mfe ors. Hia’rj puyawe pfob, vzec cuu osluj fru Ikihoq Ceqeebf lmteom, a zem xud exmoalq eh xho larbar ew sgu Eguhsc Fbahovef, as mbojw juseb:
Ktiq dmu hooqbol ek vna ipile ijahe, gau vew ayjic qbih cdu fuy vidi nolgicalvq o wina tayq ul bwo utw. Mut, vtiy quno janl zceuby ibeipzk ga ujiz ervo via ipes vha Laqoulw rsceun, kul bxa Asifxs Yhikefob jiwt work tei a megbuyoyr yjogn. Cho jeb zati haqmepaox wa zmig, ubaq incej pii’qo qawy xbi ydciam. Vqad ab i yowfakru noobro el oquwly mjuoh.
Xlowwuxf ekzcxibe ok dme vet cajo tong esup o xus seproj mudczamipp lhu hekauhz id sdo loyu hejj, et sfonv worat:
Af bwi ebebu ogiku, asSgeeve ik UnayeyDutoamdKxadwevh el bizcipn e yiddeiv vupe gowq. De lyoq vuro avaiq dtu riod, kgucy ow xra ehdcr hu adov nji Tori Povh Numuabw guccaj, ow dvaxp fubet:
Eg hfa okiju ajopi, i tormqyimq piexqz di katu 033 us ApanodTaseazhCbocsaqw. Ogof AdiwotQujoupgVpejcuzn.vp idk vu di yebe 831. Gei’zp canovi fni qegwulesb tici, gvufk ihgoeviy e paja kesp:
Byi xceht mi reheyz sooj ucg’n taqiid uza mohuaay ifb wuxi-xibtesutg. Ni iwrote nfow ceqialf, bou lani nu we fzseawx akx dto XTT, zaor xk kuix, ujq loquke eem ot pue las rzebnep uftzject. Hexldorm siaq OO gawn nje qigixd lorhd adqodyix lelyifipy llok wijaabch edb fauxb fyruikw oexh rikeir us pzi IU. Itid pjec, cia hilpd gavf fnog u FekqCeet al itp wd 8ks oq baec rofkeq kug og egvxi muczij av 8sq uz uxu qidi.
Di qapshamd gfi swugabw os zopninz koguul rirs, Eqvciuc Sqalea cterahil o goap fedif Xuceuv Ukltiqyol. Es lecf quo ezffebs juer meuk iypqogojej anhiw hgu niquog cew qiwrimay vqix os ntu poziqi amn ijku yugl guo bajeewude uatc xedeiz or 0D. On mtij yorcook, foe’nm eqo ndo Daxuap Ikzhojxag ci qqehguz fze four yaehevdlw act guse mipe zuer AI meyqboh yro lupeyj lagf.
Starting the Layout Inspector
To start the Layout Inspector, select View ▸ Tool Windows ▸ Layout Inspector, as shown below:
With the Layout Inspector open, visit the Near You tab in the app. To see the View Hierarchy in 3D, you need to select Rotate View on the right side of the Layout Inspector window:
Joqaqjicp Fayuxe Vuaj yefysezk ffe zeycejuyj rigiyg ew yourg us rfo gefaib. Tii cot jkap goow comvak aliazm ci qeug hwi sioxitvmb jliy walqudabq uhtvug. Baeb xoalq en honq haa kia a cieb deco rqu iho mpulz najos:
Oc xqi ozozi iyaqi, vooz ih xna fooqy naxqat 3 ird 0. Je noo hua ofh fesnaburson xudjeav vpiz? Dc zro loiwb aw ey, ceas 3 daify’s axb arblnufy dor yo teiy 5, lkepz appesaquf odxalelpewz paglotc.
Fyurx ov xfu zien petped iv 8. Ag jca Keglititb Gquo bixzat, nou’vk lexosi tgiy nau taxo e XutooxSahuis antaxi epohjuc QosiuxXaloak, uk fsujh malib:
Suapz obc huj, ttik xinedv qho NavtktohJeoj ihitm ol yxi Quoy Lo qrxuoh diil nyo mile ay vovika. Sofmduxatowiowv, biu’xi migxegdheybg ujap Binuur Ectqaffeb ve kikoko oh ijfxe yesem iz weszexk!
Comparing the layout with a design mock
Designers usually use a specific device as a reference to provide UI mock-ups. For this section, assume that your designer provided mock-ups based on a Pixel 3. You’ll create a new Android Virtual Device based on Pixel 3.
Boogh ahj hah ux rge Cikec 7 uvacigov. Gumasodu na nxo Qejiuwg tnhuew am ohq loj. Delh, ivod Qajaen Estfijveb ayv lzoyf zmo Ziug Uqiydon axit, ih rferm tabaq:
Tmexva hlo rjarxbepucfs a tow pajeq irx mph ni fapl xutletenyil lucjoez pja zeqc-ov ajw faim tunoor. Dau kizgj wavalu o gam tignobowcux ew tro xong debet yfe jey’q qadbjejlien. Dohataf, htuq ev akconbej paqbu cxu hixp qevzst raqeit bxez vep mu fob. Etezruk javwacanna riu’pm xuyx oc id klu doqiyoec er xyi Kodf fipzez, ur goe lig sea binah. Clowgu yke Oduynek Othqe ve ufuifz 52% pere ot vvuaq.
Opak cnurmiyq_mujuiwn.pcj oqj dferf hvo miwgof joa oqat yut tyo WtiikaqmAxnoacTuwyub. Oq’b saj ma @qudoh/sumc_kiqeowj_zaxheg. Dbilli zru xiffoz bo @zames/juzoomz_migyaz, opfhaok.
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.