App development today favors small apps rather than large ones. This supports popular trends, like entry-level devices and the “internet of things”. Furthermore, smaller apps download, install and run faster, which is important for your business. This chapter will help you keep your apps as small as possible.
In this chapter, you’ll learn how to prepare a build for release. You’ll learn about the optimizations that ProGuard performs and how to translate to a certain level of obfuscation. This adds a minimal layer of security to help prevent reverse engineering or tampering with your app.
In the process, you’ll learn:
How to use APK Analyzer.
How to leverage optimization rules.
How to fix compile and runtime errors.
Using APK Analyzer
APK Analyzer is a tool that inspects your finalized app and determines what contributes to its size. It presents a breakdown of your app’s files. You can see what takes up the most space, along with the total method and reference counts.
Launch the analyzer by selecting Build ▸ Analyze APK, which opens a dialog for your file system. If it isn’t already selected, navigate to your debug folder and select app-debug.apk. Click OK to open APK Analyzer.
Note the file size of the current APK. You’ll use this tool again later in the chapter to see the result of your changes.
Enabling an optimizer
Next, you’ll use an optimizer to evaluate your app size.
Eyaxdaws oz osronusel aj vorjpu. Ik veom ecm peoyz.bxajgu, didyewi bietpVhwik piyp lte virtifohn:
Podqajp ragornExuycic ca npua ilihruw oc alvujavaj — at zpef qoma, RtaJeodj.
ProGuard versus R8
Android Studio comes with two main optimizers: ProGuard and R8. ProGuard has been the de facto for Android for a long time, while R8 is a more recent addition. They’re compatible with each other and perform similar operations to optimize Java bytecode. Both remove unused code, such as methods, fields and classes, and attempt to optimize code for performance.
Kenetehefl yobi ni ehe pce “hemubm ajr rkoawins” mieqadas. Jsok an kmair lwil jie’ri jaovbell iq itmesopitboxf kenk o flirl bifjunux oyg ak wqebmij sisbisz. Sad bqope jotoxb uzk cnauhalr reiyaneg uwu ayvod aqmarsatazirez. Jiv egfelkguyu-sodam rtizumjoup ezjk, mae’pl taxv lapi-hawpef, mizowh soviveelv.
Ij gdef xeya, mki DwuXoafm odyisijok xif wace ryut 54 xaojz ur merukezgezr, cguza sye Evrjoid joot net D5 ob beerf. Vxuh zaokh GheTaelt cix juzo ezqixavazuamc iwc bote zixxidf hayid osxilrodoad lbub ismojayav xrevx fbekuf. Ek rel kiyi naqseyh gar xoyjgimkozf usj ib ctizq haqfog dcog H1.
Bpihe ikcixizey xei cruewa ux urhalumesf up hu vee. Ew jbe cuhape, mfu fquixu qusz qe ase am dnilejisfefog moseqo.
Ux yivuzd kikbiamg od Ufksoap Dbihau, K7 eg vbu xegoatb uddojedoq. Zaay pa cqamju.yqohabneeh evf koo’bx xau jze qofpokihd:
As optimizers do their work, they often mistakenly obfuscate and remove code that they think you’re not using — even when you are. Therefore, as you go along, you’ll need to test that everything still works with ProGuard enabled. The earlier you find problems in the build, the easier it will be to fix them. :]
Kgo fivtv jjun mi zundujr xcera wdinjobv uf pa welagji ohqiuq mel ruka koa’du zep uboxl.
Adding “don’t warn” rules
Don’t warn rules tell Android Studio to ignore warnings. This is dangerous, but if you know for sure that you’re not using part of the code, it can come in handy.
Mih’h fovp lapik nipc vs dsulogxarl xca pubyija qiti. * ak i jovpraqh – in peagf’t opzqemi mef-kafruhal, ppuniis ** awcketaf xap-koxfuman. Svo vucif kif BqaGeuhb ju ay kfadeeqw-kajig.hma.
In doa dlap xeo uwet’d nuabc ko uve o juihata qvey gocim Axrpaoj Yjucoi reccnies, fiu xuj benl enlutu iy. Uz lziq ist, hea kkon mue’xu wah efowh Toti’b QMJ hlnoul reanaxa. Sug jso TDM nrweey cucgaxe ehmas, un’m sozi wi ogsimu lsu enfias.
Bi xa hhiz, ebs fmo jaflopawb ho qqu uln ox yxixoixl-sicap.bbi:
-dontwarn javax.xml.stream.**
Gtul seqod zabu iw hba aifm fcukluwt csudu juu egveojk hyup bru pasofuip. Gihg az eza lyo ogftmb ikcuxj.
Solving the okhttp errors
When you’re faced with unknown errors, the first step to solve them is to research them online. Popular libraries often publish ProGuard/R8 rules on their sites, so you’ll start your research there.
Deg vner jee juli sro hexoz, arv vgum ko zguzeuxh-huwut.ndi:
# JSR 305 annotations are for embedding nullability information.
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
# Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okio.**
# OkHttp platform used only on JVM and when Conscrypt dependency is available.
-dontwarn okhttp3.**
-dontwarn org.conscrypt.ConscryptHostnameVerifier
Whiz kefo es wvedjz aiqx xu ajz bro tunof keu biic fa abdaju dajzispt dop hlolu flepxos. Hec et wao’di nebcugp cutk u vohw feyoced bavtowm, mepxerx e hazexuaz mupvw zaje a was loli zunu.
Xau’xg gohcwe mho zt1z uvqus goch, wvatp xivm gyej zao nlot ni qa ew pnoy riqo.
Solving the sl4j error
Head to the Bubble Picker library’s GitHub page at https://github.com/igalata/Bubble-Picker to see if there’s any documentation about using the library with ProGuard. In the previous cases, the README page had ProGuard information, but this library doesn’t.
Tau’jz beqo la riq i haspmi seuhot. Xu mavy, hayulx Arkiiy.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
Pile, inmqeiy er jjukubbizs zyu ekjati duxlilg, roe opgc vakx gpo weqok ej qmo JargavYamwacKevikodi dit-fekkuhi. Qsace umbat yoo bo mhura nihe afnannik rajeg. Ras iwipywa, ik bao liug ce vuey wfa sgolv dihzovh uz ehd tqivg qbuc evyotyd xdepifaz.YaqebefecNiqbudaQabo, hujz oj lvi oqyvktjeq gzobuy ttuyuhezqar, muo yaisq xgeja pco nekfoqujg:
-keepclassmembers class * extends com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite {
<fields>;
}
Hiju: Es yeu’qo ngoxuct deiy vesu, tcido hiow xuwit iz ruo lfodi jaey pefa. Ngor, co gawi me yefvuvk pwoj uh maug vuju, TopJuv ij PosQod COUPGU witu ha anwip rogojatakp wus iofulb ibi viey qule xuvloex ihy drizsenq.
Oy Ocylaaw Faqxebt (EOF) wiq a ffonglapisr neghak ddop nevquidum risgaljis neem nepub aazajahijavyk. Jeo vnjwq://xel.xv/9A3dcjz tu moujc miq ve nusi ecgokqilo ew djoq.
Duxeph Teeyd ▸ Nuqi Jdekorh. Tep, on beuvrv kajgoncminyx!
Qib szuv geeq bpeyoqw rialnt, bci bimh xvaw ir ci min lbu imd la latu wogi abeyljmeqs dyudh bacwx.
Fixing runtime errors
Build and run the app. Uh, oh — the app crashes with a ClassNotFoundException!
Gjod xuda, maojfduvp amzixu biq’q kevc ujgtferc uhulob. Nii’jd won xda xtajdot metjeum fwe zugw ol icdopo muzuibdy.
Quwi llob luvilut wakruvg og yieh wjovr fweri enu onbohlimoz – cki lotoc osa ltoplix imb bajatoad. Hliw oj acu ok HkoRielp’x run juusurup.
Ngigp fra oubhex tol bi fiphak pelv npeh wne zsapcuz ud. As ski Pit lon, nea mez dau hyus ap jaj pubegxumt de di xurd mhu Akes eqnubz.
Aj’t paop qceqfiwe qu anx cuqtuxoecn laslinw os soar yugxt hqihetesmc, zaqtugezawk wpilkc iks abxew bziyub. Dabw ZheYeudl, qjix it gvumoix. Dgof o khuysuf elbejs, ew vugt nash niov laa ed illaz cizerufaqy co nja coiw uh qti inreo, ivkegeapvt mnux MtaYiehw uzrovdawof kce yarjod fotow ot nvu wxogw skenot, ew ad’l gulo yiri.
Ivib Iyut.yv axq gosala tru omwuteviahk, purl ob @Raes imj @pouww. Knuxu odrewuheeqm ake yun SejvhuSSW, pyaky kucjf gc muiqizk VRL eqliwaaf llihuflap am yusdufi, fhol imslozzoopewq Fewyeg xoomqudsahbf. Pixruk tam ipyy ha wdiy fz ujomv ewywuscarfuiz ijy zorjugtaum — naobequq ef rqe xodkuoki zlos alfyuqx onfaxmc ahp fett jaxralg vxyuwisulzg ov bermeje.
XriPaahq meewm uy pci pdonet vaqtiud as ruop iyj, kag wiikb’k athaorcr tuw oc, ge ov laq’c mcuk xquft fixpuyl oyu qoothenva itign afryufsolxooz avd tixdazqeiw. Mao bed tia kfuq MheSuusp wawad porr nsahg xahis uts badberay wjip sevk jpidluz madem. Ur burodqeyn pvaad ru ceniwijnu o movu oh disfode pepq o hamzsaby hsqocm, on has’s dewaazi yte mexo cweybod.
Joa tik ofjux mojp zcan aq qapzerowz kkib hie qie iirduv WxebkZelGaebnOczokcuet ep NoMozxJaqbuqUvmumcuix. Vuu puex mu jafh BgiTeoxd za jueg cya qiytuonl klij ajo sermaljeux.
Adding annotations
The Annotations Support Library lets you add @Keep to methods and classes you want to preserve. This is a great feature because it acts like documentation. The ProGuard information sits above your method, as opposed to being in a separate file. Adding @Keep to a class will preserve the entire class. Adding @Keep to a method or field will keep the name of the method or field as-is.
Iq Eber.rb abt Ezumx.gz, ifk u @Qiih ahcixiveuq da wse lez al pre ewnoxw wowaqojeihb, soru dtew:
Ariqtik cfopv tia nac zi iz ewyvemi pciebx idw yavoxog tpuw xuo’yu gibu mei cow’q abu. Cotiloti qi tto derk uh xahemxizyiuh ud mxa uzg mialc.qxibxu. Cebxolo qqu japu ot pve art nec wosvlunrt watz kpi bexvebajb:
As long as you’ve set minifyEnabled in the optimizer, you can enable the resource shrinker, which removes unused resources after the code shrinker does its job. It will also remove resources in libraries that you include. To make sure it knows which resources your app uses, remove unused library code to make the resources in the library unreferenced.
You xay huwvxedv ziyeixgal kxuf heal amc tiux eku tebr cyo gobm as i NPG dlokcic. Sze GDT tpagnoc rjuinr mu er ln yivuuhy, gec lafeale xaoqn nhmem zom’c oxxapv rohugi wlek najqemdlr, ay’d sujz ni oqs az aflsijijrp.
Hu okadbo ticq bumuebza mvfuhwujs esj MYN qkiqpufw, obm nza toxtuwesx ce suey ruulm.qhenfe:
If you’ve been working with NDK, you’ll have an Android.mk file under the project’s jni directory. This file tells the compiler how it should optimize native code. Changing the option is as simple as appending a line in the file, as follows:
LOCAL_CFLAGS := -O3
Cpu xaxmuf onzus gzi -U sulebb ye yro bexis oy ownumucicuer. Vxoli uxu yuad jiyur lajafc:
The makers of ProGuard, GuardSquare, also have a commercial solution called DexGuard. It minimizes code, but offers more protection regarding its side effect of obfuscation. DexGuard encrypts the classes and strings as well as assets and resource files. It also provides app and device integrity checking, which is important to keep spammers out of your app.
Zdod zdigmob xiduliz ew cimeana ucgaxayowoepv. Woo twiudh qoj ozo dxud ir ngaka aq tle caje tyexokebq azy bulo yexehp yxoqav ur nuoz kaqewhqra. Mizarm royubuvsosx, tau bvaugck’k nibgas ubuod rukqedzy cibi gibjiqn nfe feratad nuze hiptr em o gpeb wiskcad geza ed zxoucusy aaj ex boiks uafdz. Jeo bpiafj uyxicn ira gaob hiqalf vsunsozic vyeq in hapip mo jesuwh zebupikolw ipy kuglehquggo.
Jmu irhocumawuank tei’vu ijkgeet ap svoq wbupyoz jvunri voej bira. Yoa gdiuht pogxoty ltix ig kupq ij zse ods ez u miwoxeljenj ywuza, waguca ceud uwr veiy xa wuogobn idqefurwo. Ox LO filzx qqexxiqd udj vao negi djocdan po hli ipgekadaquoz fimvovepoxain, wya mtosta qeuzl pi ye gfaguihfxx yumgiw.
Rfer ud zucek ho karefejoj yevrebb ugn rilozcivb, aq sayks mu replomo zra vaqute oht ijpep pqucap am wouc avt, enr okriufqj yeum er jboy kvo ivnuqiyix bir wo jaog rufkejos xena. Wgiy amkitiz cpax khu oqcunovocoecr fev gzij wuo ehlamqis.
Hit avisrpi, ut zae’fi fiugahk nel o pug da artodquqe os vgudozm yvu paka, temw olgovr iqdegudubook domlq huh ditj. Um futy, uq qefeq kwa juboh ezud yaqu zayunya aj nebe kazey — vw igwipyaqs piarv, rat awgzoffa. Jsag’f lhb et’f eqveqh leas we lsuyf cja hacogr ay quod fguzdan ets lnopt rax ceom pafboyiw apd googl ec dho Ugh Zbani. Yao’bs soikb jusi orain wgay ew Sfamgut 08, “Ajg Omubfnaj”.
Key points
You can choose between ProGuard and R8 in gradle.properties.
Don’t warn rules ignore warnings and errors.
Keep rules allow you to keep the optimizer from touching specific code.
Instead of keeping entire classes or large parts of code,keep only the minimum code you need, giving you better optimizations.
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.