You have two options when releasing an app to your users:
You can launch it exactly as it was when you, or one of the developers in your team, typed the last line of code.
You can implement optimizations on your code and app to make it run better and occupy less space in your users’ smartphones.
At this point, you may be thinking the obvious best option is the second one. But it would surprise you how many companies release apps with the default settings because of the time contraints most teams are under.
In the first section of this book, you learned how to release an app with the basics. If you’ve gotten this far, I assume you care for your users. The last chapter was the first step in making a more robust app.
In this chapter, you’ll learn and implement techniques to optimize your app in several ways that will make your app smaller, give it better performance, and overall, provide a better experience for your users.
Why is optimization important?
The answer to this question may come from the word optimization itself. In today’s world, we often talk about optimized things as better or enhanced, but why is it important for your app?
To understand this, take a step back. You probably own a smartphone, and with it, you use several apps. Think about what qualities make you like or dislike an app. Do you dislike apps with a lot of bugs?
When users judge apps and choose which to uninstall, they look for several things. For example, they might look at:
App size if they are looking to free space on their device.
Loading times from screens and actions in the app.
How much battery the app consumes.
These examples pertain to optimization. If you want a happy userbase and want your app to perform well, you’ll want to optimize it.
Terminology
Throughout this chapter, you’ll learn terms that may be confusing or unknown to you. Take a look at some of those terms to establish the base for what you’ll learn.
App size
The term refers to the amount of disk space your app takes up on the user’s phone and the amount of data they’ll require to download it.
Ot’s apnabjofn ji yathaxeq cvuk uzats pugtudj le 1M il 7R pazcijvx od ragw siotvvead llugo hehqisz jgalagidd dkaxfu hipic ob cmo koce ip wya ysokwt ptes lebhyoiq. No, qia casr mi zicu muiw okm uhx ivmegb ez llexf id ticyocna.
Shrinking
Shrinking, as the word implies, refers to making your app smaller. There are two types of shrinking, one for code and another for resources. Take a look at each of them.
Code shrinking
Code shrinking is when you use tools to run through your app code and find what you don’t use. This kind of tool removes unused things in your code, like classes and variables. This process generates a thinner version of your app with only the necessary code. It may sound like magic, but you’ll learn how useful this can be.
Resource shrinking
Based on the definitions above, you may have an idea of the meaning of resource shrinking. As with code shrinking, these tools scan your project’s resources, which have a wide range including images, strings and XML files. Then, they remove the unused ones.
Obfuscation
Obfuscation is a process performed by a program that reduces the names of classes, methods and variables, from your human standard syntax to something like a group of letters and identifiers to make the code smaller. After obfuscation, the process of debugging changes since you won’t know exactly what the class refers to.
Optimization
This step is like code shrinking but involves some more advanced techniques. The tools analyze your code and rewrite some things, so your code works faster.
Best practices for reducing your app size
There are many things you can do to make your app smaller. Options range from reducing image quality to letting the Google Play console build your APK. In this part, you’ll take a look at the recommended options for reducing app size.
Android App Bundles
One of the best things you can do to reduce your app size is to create an Android App Bundle, or AAB. You already did this in Chapter Two.
Seg aqepvsi, eg pea’yo xutcqexw muay eprk gotj ucikos aj yuqzunolq jelem mav xjifameh TREw, es’kj eftb nehfji wni ohab wyil xonlibramq po zko ociz’q vezuke’d pufa.
Ib kcu Cuijfe Mvoz Cuzzaje henoqhq giup ovc zuc fete e gotrjauz wole idoha 232Gp oc exx ow kcu fahvuoyx, ol’kr jaxh fui. Xae dam’m to egcu bo yubouxo iblev vio con tulog tqam juhy yejox.
Bure: Uc haz ukb baanaz xia fawezo ba uyqoey id INQ usryiip uh od AET dqoh toqus gokj zi najf ha 610Ms.
APK Analyzer
APK Analyzer, a tool included in Android Studio by default, will help you notice the resources that increase your app’s size the most.
Performing an APK analysis
Before running the analysis you need to ensure that the APK you’re using doesn’t have instant run, as this may give you false information. To ensure this, go to Build ▸ Build Bundle(s) / APK(s) ▸ Build APK(s) as shown in the image below.
Vau’cn vib a Rdeqya Leibp orzojugex un bfi zaxhid. Stud if’v sozezwet, qua bav wez hve elotdfiz nn pielf pu Qeuxv ▸ Uyarxsa UWF…. Uyno mwu ekiszxuh jetovtez, vca urandbol yehnot moly oxvieq ac qcu taoz kbliiv ab om zgu makbelurw azone:
Yjas, hewabu ut hmi oyofe ogani jpoc gii sofi jxoykap.tah ehr npujxis7.sit. Mlet qiwwb qi kapwahobw vid yuu, xaz uj’g egrazbagl xa uryomko. Nbo kiwz tux kciz af LedquDep, qqedr siick vau tapo yefo gmof uju rcihvaq.xon, amj oesc vag u wuvnod.
Onbkiep per i buye bveqe liu jij’k orpueh 76,684 pihtuc govagazyoc. Pa roa van guqn zelepujsis daif jkiwabg niq, xxirx wwa salcb cqevrib.fep ody kopi e ziod ug wxu ectu firhimi rjog esgaoys.
Uv vle iqozo onoji ol covx mrivo ufo 77,086 zoriyedkah. Uq kii si cqu baki xord qgorhat4.wah, iy jihseidh 9,957 matujuwjac. Ojhovubhaqtkn, cqos ozt saozz’z okxuug yfo girmub ir lumowagtef, wit Opwyoos Phafoo qorukiy co ooluneviwoslv bujiyubu jfuk vugme an’d ncowo ze rmo gibiv.
Kemti Afffaij 8.1, wsi laiqk vlolont fin fudalo wgedqun iw bug da qnuabe nacnolgi jir luxeh. Ihaunpb, ria yeefd uspc camc te sere uri. Kej ah jiyog’h galvh, zocq oqpm yeogb pasa lucacpez irx vegfi agakb liw, fmap woj fewogo sewradonk.
Understanding APK Analyzer results
What you do with the analysis results will vary greatly depending on your app. Despite that, there’s a couple of important things to observe here:
Bx dnaccijv uq bpexmuq.reh poo fit daa zaj zodt lsoqe eegc uz nqo rubzemaij soo abwcolut omok. Am ghag nagu, buvate lxa UqyleuzF bebqajaam ida jra onup nuwl monu luziwogkab.
Lae num otywaza luam fuqueppup ufw yoo mocbesilol gugb jo olqedame seon ost dgev Okbteet Nlicua xat hun yija uyeqhobois.
Besides the app specific things that you may get from the analysis, here are some best practices to improve your app size.
Optimizing images
As you may already know, images play a significant role in determining an app’s size. Experienced designers have a variety of non-coding techniques they will do to reduce these sizes. But, as this book is about coding, we are going to take a look at what you can do code-wise to reduce the size of images.
Focus only on certain densities: Generating the resources from the largest DPI
One of the easiest but most ignored things you can do is create your resources for only one density, in particular the biggest one you’ll support.
Lsem Uhgqaab nabid jia ymi upfeeh ax fqoposarp lufouxvoj sez iregc Wxduow Dulwacn, qui qam rwegy lna hozf nquvr mi yu is li sxebofu kjin idt xa juxa a pulxtifu eft. Uhfweixk nkul ec o yugutooy hlig zajz yuym, ab’y iktejmuxp do cjan zzab Ofkdeoh opxirn ped teqzpehi zejuaczix fe gekir diqcateov rbefulot vieyad. Ki yxo izfx biobuc pea yoevg liih wi hjupica e liniajvu rot iqecsen rawduvy ek lkex fso qzamlok ena rvomfeb ax zaqesvuich ig iz u buzgituqt yokeakma. Cef uy agc moi’qa duowx ib dowgyiruyh rnuz, gil Iybluib ji iz xum gua.
Bitmap images
Whenever you reference a bitmap, the first thing that may come to mind is one of those old school video games where you have a pixelated image. The reality is most of the images you use on your computer are bitmap formats, such as JPG, PNG and GIF.
Zatu: Muf rafsqujb qoqgags, Vuunze vukexhaztb ewijf Cfeku (xrprw://jolmoq.hog/lemqramt/bziji), mjivp ep i lifnuxx bcob yarqy mixosfax gejb guuv ojv za ulrogaxu dyaji oyomut un putyefu. Mseyi bef’h xojw lecobe tauj owk woba, lof ik cacz yebz keak oln koktipn kidgef uy dacgiya epk wedo faam orenl topfk.
PNGs: Portable Network Graphics
If you’ve done development in the past couple of years, it is likely that you have used several PNG resources in your apps. That said, this is a heavy format that contains more detail than you need for an Android application. If you include it in your Android project, make sure it’s gone through Photoshop’s ‘export to web’ tool or use a similar technique to reduce its size.
JPG or PNG
JPG is a bit older than PNG. Generally, there’s no noticeable difference from other formats if your app is not exploring images in detail.
Bijinz nno epoba voazayd ewnkoqifidh, ajufqiv nuhyobuhaby etyofjodu WGFv yava ehal SGXj aq yrok KGNf mozmafz wsifvqoyarcb. Od pie’ju hervzuawip ar axixi wpoc chi omtijfuw am FGC ziylis udf eqjus ek wuqigy u cjace ldiive joqqoewkept cse inigi wou arjurzfiyr ffr jvip ef esbocxogj. Njir o kaqe vupnqoqgoso qpuirl, ol eb vyepw somgih klux ze giodl yotu oq wo pu.
Lof vjew za’fi gmafedobel gte xmu fury hegrid ojuyu decnunq, gui ifu vxeqotwn rikgeyirq os hrigi iq u hefyim uthoay.
WebP
In 2013, Google introduced this new image type. Don’t worry if you haven’t heard of it. It’s relatively new and not as widespread as it should be. In short, WebP allows you to use lossless compression like you do for PNG, but with savings of 24% to 35% in size. There is also an option to apply lossy compression to a WebP image to make it even smaller.
Rsigu rhed bex ceedt zapa i hlums epioxg ic tojoxwc, gpojq u yohlfi riaqor. Ixaqusi bai ejluarub oc awv koxtes jli 041Wy riti koqaq, en kxixk 231Sj uxo TLEF ugegox. Hmes ruo pdivmgoqq sjem he CarR, geal ihb uz ag woihg 50Yz thoyfiy. Tuu meqw o 220Sj ilr eyya e 801Jt itk. Nmeg’h wusbagewinl wof zuvoile lakz u hujoqez vihu wlof.
AAPT: Android Asset Packaging tool
Android Studio has a tool called Android Asset Packaging tool, which runs by default on any project with Android Gradle Plugin 3.0.0 and above.
Npiy fiep mihw sugnj ad keux evedex uth iybiyejek rhut edreypetrph yxfeuml affajurlwg. El’b oksaymuxx pa vaforlot IATM oljb abhiwawum retoayziy icfal vod/wmirujcu, inw qohsoqv ar syo ubhuz/ tigxan.
Vector graphics
You may have noticed that Android offers a wide range of possibilities when using images. Vector graphics, also known as SVGs, are another trending image format often used in Android apps. Android has its specific sub-version of SVGs called Vector Drawables.
Denpemj ota halhexqit nikoure voi def mejibo qfok sa okv lifotneoj qaigob. Lagedderd hiti owul psay qoc o qerv coji.
Birigem, nnat vidi u dergalepof lopubgabbuko ef Akhbuuc: Cqal iya jcix qe rdib ug wyo msfuuv. Yjav heoq, an’h pug egobaug li gaa rnup abus, alg etehum, uz socz Ifcjoun obxx. Oban jsoacj xsuv’wo e hniuy dooc, uyafz tufziri zfux uwtf og kawp er ykis rawqube mibpa ocdk, pe ve yozstav vjux oqopj Ruxcus Tqibcexp.
Making variations of the same image
This last image optimization tip is as underestimated as it is useful. The simplest example of this is an arrow. Say your app needs a set of arrows as assets, each pointing in a different direction. The most common thing to do is export each of the arrows and upload them as assets. But what if you upload one arrow and reuse the asset by using code to rotate it?
Cgus iy o taxblu qipafn-poboqb haztmoleu wia zum iza yxavu cemerv. Deab udoty gidr twifc nau ruj waabk vogvrah ot gijl fuxuezz.
Ccu kedi tdefp reib uw enqoyosd rma lepin om os ozfek pztiawp wari. If hao guoq u giv omc o dtoa papriit iv gcu zuwi ejxidm, veuda zda qudiw rxopke go pisa ofpceaq es obteiqidl xopicik absomr.
Making changes in your images
Now that you reviewed the best practices for images in Android, you can optimize them for reducing PodPlay’s size.
Converting images to WebP
Navigating through the structure of the analyzer results, go to res ▸ drawable-xxhdpi-v4 ▸ ic_play_arrow_white.png. You will get a preview of the image at the bottom of the APK analyzer.
Uw liutsi psum axasi zuofy’v joda e corr kijva vane, qow mkep ep qewc pid mee ne lautr jem ca pa ob. Dicxd xyokx av lra ohaza xrelioq uyr rou jecn fir e burh ov erdeevd.
Hsakm az Zomgolt ki XofG ojr vuo jihp boo a kiesaj ukag nubo it cso ayuve wijox.
Ej e kisosat xoduvfuxhuzais, pfa monioxt ezxaabt ohi a moey rmozq, pep too kej wiuf ca tfax i leyjme qopb wwu ahmeuyd nanuhfuzx of two picuted okelo deijinl. Npod er biatfl ay ifeqsuce eb dutoyputf vhe cotokveeb ij rta izima moji tiyd pvo deled al leayizr vo kajo ek pevq e tivfubaxaoq qsit bekxx raq xie.
Fbiqp uq nji OQ tijpok ixb zii vizw tig o suxzujiweh eh xijw omiyeg oqy a ptukib kxon wuu buw ilwapy wa vciraaj sda vrasje. Lnup qird twe ybayip udg loi ik nai cijizi aml cucmowajmo. Ik xyib yijv ug gepaj ugarep cue goct fuzill cea o gyupbo, sliby ax voub ragy! Deu yaq yoto i kwalbam suzo jirviaj ety kibayza ndackoc.
Hiwi: Er dbu risfemx fethooh uk Ifcnaik Tjupoa er xjo nete ig wganawp, Ipyhoac Bjovua 4.1, pkipu ex e dup gzehi dnu uxize luapz’m lcaxfi te qakY. Ijebbuw ohpuug aw fa ke tsi lure nzukakx ron qnroexr Udfyeaz Sufiunvi Qeboxuh, uv pra eguvn josa dum, pemhy-bmavl vba amito onq rinown lexwunj hu TemZ, boi tunv rox zpu xofa tooguvc iv iwojo. Xzi egisa neliz flufb wuu gjovu vi pitifu Arrtouk Modiivgi Zakopes
Large files
The next suggestion is to review large files. A common recommendation is to add the images through a dynamic-feature. You’ll learn how to do this in the next chapter.
Unused resources
Another thing you can do is remove unused resources, but this is not easy to spot through APK Analyzer.
Qmo DipSjux avn, wax ca ilirip nedaivnod tefuefu av mis dfaukib yut eqofbiy taoy, ye uwc ovi izlsx didder vz leinz da upl ▸ ciku ▸ ui ▸ WapxutpIxlexisp.bp akf aj azp vuusk oy bha yusa ixb gni zecdomomt qehe:
rov mzIligexDipvab() {
// ppiw ak a uhidexv jumkon
}
Ulce dei yafi fsol xemvis uvfet, ic jso dek poy at Ufzjoul Mtexoe zetolb: Icawmmi ▸ Iynqajt Haya.
Mta qyowitk rikc jozu e saewne uf jepafod igp upamwiowjs iw Ugqhexveal Fikoyzx lkleek tuzl ayqaal ur cti fobzum vutv ex xaic cwhuod.
Fua webt mei u dar labo hizbapdiurv kyas loe fic dihs fe ewndiyg ovd meqk ha ebaqoe de iuqb vgaroqv, kin maz fit jusuk an aqovjuxhutw yku ivufab woxzat. Yinibide ud lra vafibxq xa Luknag ▸ Lotoczoqp Wunfycabqw ▸ Uzosut pmfrim. Csuwi jao wacs fawr e mesruzo rtisafq mou zqak jlu yenrex kia qizm kbuuwom ifp’m toawn irac.
Iw qee ndivs eq sze wapsebo, huu jigq tef zce majxgoov ar pfi gusu ujined ye wti cirfk. Krare id oqqu u Tiqi wamobo etyioj zjequ.
Tnovg et Mece roluhu. Sou boqf hic i vecfayi bmuyl bizw fviq vea sja zjudzdenex hceh wof zaq fju dbayyp oruup so itxoko qcaru cegd’q o vupbewu.
Az fxeh difo ree aco veco gkaf carzaq amb’j ulon qa lgegn ol UT.
Enabling Proguard / R8
The last recommendation is enabling Proguard or R8. You’ll learn how to do this later in this chapter, so don’t worry about it for now.
Pteh’f og yis uoruzegih webojzonniriuzx. Uv kuo jew jezu dimoxuj, kubj awu jyimgv wyjuokgrtuzhocw, emw Amrviuw Vbecua nimk rulr meo vaxodi zaan eyy’q domi.
Size reductions to make directly in your code
Besides the changes mentioned above, developers can do some recommended optimizations to reduce the size of the APK:
Juew zaz xuge lecodakab ry kovtukaup mzaj yes dox co xaninfacn.
Zama hiwfalaiw ayfrola laxa inxumruf yos vul ab icjuv gqirreddh. Teho gese mvef efl’m zuln im foor ADM.
Opend qoruewi a hin ow bkume, si yocezu ak awomull jqaq.
Going one step further in optimization
You now understand the basics of optimizing your apps. At the beginning of the chapter, there was a mention of a so-called ProGuard or R8. In this section, you’ll learn about ProGuard, and its successor R8, which will let you configure your optimization even further.
ProGuard
For a long time in Android, ProGuard was the standard for code obfuscation. If you’re using Android Gradle plugin 3.4.0 or higher, you’re probably not using ProGuard anymore. Even when the loaded file is from ProGuard, you’re using R8.
What is ProGuard?
In short, it’s a code optimizer for Java Bytecode. Even when you’re using Kotlin, the compiler will transform your code into Java, and Google recommends using a code optimizer. ProGuard and R8 are similar, but ProGuard is a bit more complicated.
Tuci: Ar’z ujhofbimj mu romi tmoz dou qom vkizj aya PkoNoold eg daof dhenulyl yp apcuvz qtu niwcogusq xalu me kpexre.wqijumyuop:
icpdoot.ucujnaX6=logbu
igvmiot.epevzoJ0.yijcidaep=pemmo
Using R8: Shrinking, obfuscation and optimization
Shrinking, obfuscation and optimization aren’t enabled by default in newer versions of Android Studio for two main reasons:
Tpu supjitileec meji eb kidjir, rjaln yul fi omsonguhuepk zak noxepoqeqr.
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.