Documente Academic
Documente Profesional
Documente Cultură
by Mark L. Murphy
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Tuning Android Applications by Mark L. Murphy Copyright 2011 CommonsWare, LLC. All Rights Reserve . !rinte in the "nite #tates o$ Ameri%a. CommonsWare books may be pur%hase in printe &bulk' or igital $orm $or e u%ational or business use. (or more in$ormation, %onta%t direct@commonsware.com. !rinting )istory* +%t 2011* ,ersion 0..#/0* 12340413152304541 relate tra e ress are
6he CommonsWare name an logo, 7/usy Co er8s 9ui e:, an tra emarks o$ CommonsWare, LLC.
All other tra emarks re$eren%e in this book are tra emarks o$ their respe%tive $irms. 6he publisher an author&s' assume no responsibility $or errors or omissions or $or amages resulting $rom the use o$ the in$ormation %ontaine herein.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Table of Contents
Welcome to the Warescription!............................................................ix Preface....................................................................................................xi Wel%ome to the /ook;.................................................................................<i What 6his /ook .s All About.....................................................................<ii !rere=uisites..............................................................................................<iii 9etting )elp..............................................................................................<iii Wares%ription............................................................................................<iv /ook /ug /ounty.......................................................................................<iv #our%e Co e...............................................................................................<vi Creative Commons an the (our4to4(ree &-2(' 9uarantee...................<vi Li$e%y%le o$ a CommonsWare /ook........................................................<vii Issues with Speed.....................................................................................1 9etting 6hings >one.....................................................................................1 ?our ". #eems... @anky.................................................................................2 0ot (ar Anough in the /a%kgroun ............................................................B !laying Cith #pee .......................................................................................B Finding CP !ottlenec"s........................................................................# 6ra%evieC......................................................................................................5 What .s 6ra%evieCD................................................................................5
iii
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Colle%ting 6ra%e >ata............................................................................5 >isplaying 6ra%e >ata...........................................................................3 .nterpreting 6ra%e >ata........................................................................10 +ther 9eneral C!" Measurement 6e%hni=ues........................................1E Logging..................................................................................................15 (!# Cal%ulations...................................................................................15 #tri%tMo e $or Main Appli%ation 6hrea .ssues.......................................12 #etting up #tri%t Mo e.........................................................................13 >evelopment +nly, !lease;..................................................................11 Focus $n% &'(.......................................................................................)1 6he Role o$ the 0>F...................................................................................21 >alvik* #e%ure, ?esG #pee y, 0ot #o Mu%h.........................................22 9oing 0ative.........................................................................................2B FnoCing ?our Limits...........................................................................20>F .nstallation an !roHe%t #etup..........................................................25 .nstalling the 0>F...............................................................................25 #etting "p an 0>F !roHe%t.................................................................23 Impro*ing CP Performance in +a*a...................................................,Re u%e C!" "tiliIation.............................................................................B1 #tan ar @ava +ptimiIations..............................................................-0 #upport )ar Care4A%%elerate 9raphi%s..........................................-2 MinimiIe .!C........................................................................................-2 An roi 4#pe%i$i% @ava +ptimiIations.................................................-E Re u%e 6ime on the Main Appli%ation 6hrea .......................................-5 9enerate Less 9arbage........................................................................-5 ,ieC Re%y%ling.....................................................................................-2 /a%kgroun 6hrea s............................................................................-3
iv
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Asyn%hronous /roa %astRe%eiver +perations..................................-1 #aving #hare !re$eren%es....................................................................E2 .mprove 6hroughput an Responsiveness...............................................EMinimiIe >isk Writes..........................................................................EE #et 6hrea !riority...............................................................................EE >o the Work #ome +ther 6ime..........................................................E5 Issues with !andwidth...........................................................................1 ?ou8re "sing 6oo Mu%h o$ the #loC #tu$$................................................52 ?ou8re "sing 6oo Mu%h o$ the A<pensive #tu$$........................................5B ?ou8re "sing 6oo Mu%h o$ #omebo y Alse8s #tu$$...................................5?ou8re "sing 6oo Mu%h... An 6here .s 0one.........................................5Focus $n% TrafficStats............................................................................/ 6ra$$i%#tats /asi%s.......................................................................................52 >evi%e #tatisti%s...................................................................................52 !er4Appli%ation #tatisti%s....................................................................53 .nterpreting the Results......................................................................53 A<ample* 6ra$$i%Monitor...........................................................................51 6ra$$i%Re%or ........................................................................................51 6ra$$i%#napshot....................................................................................20 6ra$$i%MonitorA%tivity..........................................................................21 "sing 6ra$$i%Monitor...........................................................................2+ther Ways to Amploy 6ra$$i%#tats..........................................................25 .n !ro u%tion.......................................................................................25 >uring 6esting......................................................................................22 0easuring !andwidth Consumption.................................................../+n4>evi%e Measurement...........................................................................21 ?oursel$, via 6ra$$i%#tats......................................................................30
v
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
A<isting An roi Appli%ations............................................................30 +$$4>evi%e Measurement...........................................................................31 Wireshark..............................................................................................31 0etCorking )ar Care.........................................................................3B !eing Smarter A1out !andwidth..........................................................2# /an Ci th #avings.....................................................................................3E Classi% )66! #olutions.......................................................................35 !ush versus !oll...................................................................................31 6humbnails an 6iles..........................................................................10 Collaborative /an Ci th.....................................................................11 /an Ci th #haping....................................................................................12 >riven by !re$eren%es..........................................................................12 >riven by +ther "sage........................................................................1E Issues with 0emor3..............................................................................-?ou Are in a )eap o$ 6rouble....................................................................11 Warning* Contains 9raphi% .mages........................................................100 .n 6oo >eep &on the #ta%k'......................................................................102 Focus $n% 0AT.....................................................................................14, #etting "p MA6.........................................................................................10B 9etting )eap >umps................................................................................10(rom >>M#........................................................................................10(rom Co e...........................................................................................105 /asi% MA6 +peration...............................................................................103 Loa ing ?our >ump...........................................................................101 (in ing ?our +bHe%ts..........................................................................110 9etting /a%k to ?our Roots.................................................................11B . enti$ying What Alse is (loating Aroun .........................................11E
vi
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
#ome Leaks an 6heir MA6 Analysis.......................................................115 Wi get in #tati% >ata Member...........................................................112 Leake 6hrea ......................................................................................112 All #orts o$ /ugs...................................................................................111 What MA6 Won8t 6ell ?ou................................................................12B Issues with !atter3 5ife........................................................................1)/ ?ou8re 9etting /lame ..............................................................................123 #tret%hing +ut the Last mWh..................................................................121 Focus $n% 0'P and Trepn...................................................................1,1 What Are ?ou 6alking AboutD..................................................................1B1 What8s an M>!D..................................................................................1B2 What8s a 6repnD...................................................................................1B2 6he /ig !roblem* Cost........................................................................1BB Running 6repn 6ests.................................................................................1BB Re%or ing Appli%ation #tates...................................................................1BA<amining 6repn Results..........................................................................1B5 +n4>evi%e............................................................................................1B5 +$$4>evi%e............................................................................................1B5 $ther Power 0easurement $ptions...................................................161 !oCer6utor.................................................................................................1-1 /attery #%reen in #ettings Appli%ation....................................................1-E /attery.n$o >ump.....................................................................................1-5
vii
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
We hope you enHoy this ebook an its up ates J subs%ribe to the Wares%ription neCsletter on the Wares%ription site to learn Chen neC e itions o$ this book, or other books, are available. All e itions o$ CommonsWare titles, print an ebook, $olloC a so$tCare4 style numbering system. MaHor releases &1.0, 2.0, et%.' are available in both print an ebookG minor releases &0.1, 0.1, et%.' are available in ebook $orm $or Wares%ription subs%ribers only. Releases en ing in .1 are Krelease %an i atesK $or the ne<t maHor release, la%king perhaps an in e< but otherCise being %omplete. Aa%h Wares%ription ebook is li%ense $or the e<%lusive use o$ its subs%riber an is tagge Cith the subs%riber8s name. We ask that you not istribute these books. .$ you Cork $or a $irm an Cish to have several employees have a%%ess, enterprise Wares%riptions are available. @ust %onta%t us at enterpriseL%ommonsCare.%om. Also, bear in min that eventually this e ition o$ this title Cill be release un er a Creative Commons li%ense J more on this in the pre$a%e. Remember that the CommonsWare Web site has errata an resour%es &e.g., sour%e %o e' $or ea%h o$ our titles. @ust visit the Web page $or the book you are intereste in an $olloC the links. ?ou %an sear%h through the !>( using most !>( rea ers &e.g., A obe Rea er'. .$ you Cish to sear%h all o$ the CommonsWare books at on%e, an
ix
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
your operating system oes not support that ire%tly, you %an alCays %ombine the !>(s into one, using tools like !>( #plit4An 4Merge or the Linu< %omman pdftk *.pdf cat output combined.pdf.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Preface
xi
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
2. /attery, to alloC evi%es to run better longer B. Memory, alCays a limitation %ompare to esktop appli%ations -. /an Ci th, a %hallenge given less4than4unlimite parti%ularly ones that are metere E. #torage, to Cring more bene$it out o$ limite spa%e Aa%h o$ those parts has a short intro u%tory %hapter setting the stage, $olloCe by tCo maHor themes* 1. )oC o you measure per$orman%e in this area an etermine that you have a problem that nee s solvingD Where possible, Ce Cill e<plore hoC to narroC oCn the sour%e o$ the poor per$orman%e as best as Ce %an. ata plans,
2. )oC o you $i< these issues, $rom general purpose te%hni=ues &e.g., the 0>F $or %ompute4heavy algorithms' to targete solutions &e.g., #tri%tMo e $or i enti$ying Chere you are oing isk or netCork .M+ on the main appli%ation threa '. +ne %hapter Cill $o%us on a maHor
xii
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
te%hni=ue $or a ressing the issue &e.g., 0>F', an another %hapter Cill %over other te%hni=ues.
Prerequisites
6his book is $or e<perien%e An roi evelopers. ?ou shoul have Critten an app or tCo alrea y, even i$ those apps Cere never istribute publi%ly. ?ou shoul be %om$ortable Cith terms like Kmain appli%ation threa K, KA!F $ileK, an K>>M#K. .$ you pi%ke this book up e<pe%ting to learn An roi appli%ation evelopment $rom s%rat%h, you really nee another sour%e $irst, sin%e this book $o%uses on other topi%s. While Ce are $ans o$ 6he /usy Co er8s 9ui e to An roi >evelopment an the other books in the CommonsWare Wares%ription, there are plenty o$ other books available %overing the An roi basi%s, blog posts, Cikis, an , o$ %ourse, the main An roi site itsel$. #ome %hapters may re$eren%e material in previous %hapters, though usually Cith a link ba%k to the pre%e ing se%tion o$ relevan%e. .n or er to make e$$e%tive use o$ this book, you Cill Cant to oCnloa the sour%e %o e $or it o$$ o$ the book8s page on the CommonsWare site. ?ou %an $in out Chen neC releases o$ this book are available via*
6he %ommonsguy 6Citter $ee 6he Commons/log 6he Wares%ription neCsletter, Chi%h you %an subs%ribe to o$$ o$ your Wares%ription page
Getting
elp
.$ you have =uestions about the book e<amples, visit #ta%k+ver$loC an ask a =uestion, tagge Cith android an commonsware.
xiii
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ you have general An roi eveloper =uestions, visit #ta%k+ver$loC an ask a =uestion, tagge Cith android &an any other relevant tags, su%h as 7a*a'.
Warescription
6his book Cill be publishe both in print an in igital $orm. 6he igital versions o$ all CommonsWare titles are available via an annual subs%ription J the Wares%ription. 6he Wares%ription entitles you, $or the uration o$ your subs%ription, to igital $orms o$ all CommonsWare titles, not Hust the one you are rea ing. !resently, CommonsWare o$$ers !>( an A!"/. Aa%h subs%riber gets personaliIe e itions o$ all e itions o$ ea%h title* both those mirroring printe e itions an in4betCeen up ates that are only available in igital $orm. 6hat Cay, your igital books are never out o$ ate $or long, an you %an take a vantage o$ neC material as it is ma e available instea o$ having to Cait $or a Chole neC print e ition. (or e<ample, Chen neC releases o$ the An roi #>F are ma e available, this book Cill be =ui%kly up ate to be a%%urate Cith %hanges in the A!.s. (rom time to time, subs%ribers Cill also re%eive a%%ess to subs%riber4only online material, in%lu ing not4yet4publishe neC titles. Also, i$ you oCn a print %opy o$ a CommonsWare book, an it is in goo %lean %on ition Cith no marks or sti%kers, you %an e<%hange that %opy $or a $ree $our4month Wares%ription. .$ you are intereste in a Wares%ription, visit the Wares%ription se%tion o$ the CommonsWare Web site.
xiv
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
/e the $irst to report a uni=ue %on%rete problem in the %urrent igital e ition, an Ce8ll give you a %oupon $or a si<4month Wares%ription as a bounty $or helping us eliver a better pro u%t. ?ou %an use that %oupon to get a neC Wares%ription, reneC an e<isting Wares%ription, or give the %oupon to a $rien , %olleague, or some ran om person you meet on the subCay. /y K%on%reteK problem, Ce mean things like*
6ypographi%al errors #ample appli%ations that o not Cork as a vertise , in the environment es%ribe in the book (a%tual errors that %annot be open to interpretation
/y Kuni=ueK, Ce mean ones not yet reporte . Aa%h book has an errata page on the CommonsWare Web siteG most knoCn problems Cill be liste there. +ne %oupon is given per email %ontaining vali bug reports. &$T8* /ooks Cith version numbers loCer than 0.1 are ineligible $or the bounty program, as they are in various stages o$ %ompletion. We appre%iate bug reports, though, i$ you %hoose to share them Cith us. We appre%iate hearing about Kso$terK issues as Cell, su%h as*
!la%es Chere you think Ce are in error, but Chere Ce $eel our interpretation is reasonable !la%es Chere you think Ce %oul e<pan upon the e<isting material a sample appli%ations, or
#amples that o not Cork ue to Kshi$ting san sK o$ the un erlying environment &e.g., %hange A!.s Cith neC releases o$ an #>F' o not =uali$y $or the $ormal bounty
Nuestions about the bug bounty, or problems you Cish to report $or bounty %onsi eration, shoul be sent to bountyL%ommonsCare.%om.
xv
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
"ource Co#e
6he sour%e %o e samples shoCn in this book are available $or oCnloa $rom a 9it)ub repository. All o$ the An roi proHe%ts are li%ense un er the Apa%he 2.0 Li%ense, in %ase you have the esire to reuse any o$ it. 6he @ava proHe%ts are set up to be built by Ant or by A%lipse. .$ you Cish to use the %o e Cith A%lipse, you shoul be able to simply import the proHe%t. .$ you Cish to use Ant, run android update project -p ... &Chere ... is the path to a proHe%t o$ interest' on those proHe%ts you Cish to use, so the buil $iles are up ate $or your An roi #>F version.
xvi
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
xvii
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 1
Mobile evi%es are never $ast enough. Aither they are sloC in general &e.g., sloC C!"' or they are sloC $or parti%ular operations &e.g., a van%e game graphi%s'. What you o not Cant is $or your appli%ation to be unne%essarily sloC, Chere the user etermines Chat is an is not Kne%essaryK. ?our opinion o$ Chat is Kne%essaryK, alas, is o$ se%on ary importan%e. 6his part o$ the book Cill $o%us on spee , in%lu ing hoC you %an measure an re u%e lag in your appli%ations. (irst, though, let8s take a look at some o$ the spe%i$i% issues surroun ing spee .
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6his part o$ the book Cill aim to help you i enti$y Chere the problem spots are, so you knoC Chat nee s optimiIation, an then some An roi 4spe%i$i% te%hni=ues $or trying to improve matters.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
beloC that $rame rate Cill result in Herky animation e$$e%ts, mu%h like the KHankyK ".s in a non4game An roi appli%ation. (or e<ample, a %lassi% problem Cith An roi game evelopment is garbage %olle%tion &9C'. +nly sin%e the 9ingerbrea release o$ An roi is the garbage %olle%tor %on%urrent, meaning that it runs in tan em Cith appli%ation %o e on a parallel threa . )istori%ally, the An roi garbage %olle%tor Cas a Kstop the Corl K implementation, that Coul $reeIe the game long enough $or a bit o$ 9C Cork to be one be$ore the game %oul %ontinue. 6his behavior pretty mu%h guarantee spora i% $ailures to maintain a %onsistent $rame rate. 6his %ause game evelopers to have to take parti%ular steps to avoi generating any garbage, su%h as maintaining its oCn obHe%t pools, to minimiIe or eliminate garbage %olle%tion pauses. 6his book oes not $o%us mu%h on spe%i$i% issues relate to game evelopment, though many o$ the te%hni=ues outline here Cill be relevant $or game evelopers.
'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 2
C!" issues ten to mani$est themselves in three Cays* 1. 6he user has a ba e<perien%e Chen using your app ire%tly J s%rolling is sluggish, a%tivities take too long to isplay, et%.
2. 6he user has a ba e<perien%e Chen your app is running in the ba%kgroun , su%h as having sloCer $rame rates on their $avorite game be%ause you are oing something %omple< in a servi%e B. 6he user has poor battery per$orman%e, riven by your e<%essive C!" utiliIation Regar less o$ hoC the issue appears to the user, in the en , it is a matter o$ you using too mu%h C!" time. 6hat %oul be simply be%ause your appli%ation is Critten to be %onstantly a%tive &e.g., you have an everlasting servi%e that uses TimerTa"k to Cake up every se%on an o something'. 6here is little anyone %an o to help that short o$ totally rethinking the app8s ar%hite%ture &e.g., sCit%h to larm+anager an alloC the user to %on$igure the polling perio '. )oCever, in many %ases, the problem is that you are using algorithms J yours or ones built into An roi J that simply take too long Chen use improperly. 6his %hapter Cill help you i enti$y these bottlene%ks, so you knoC Chat portions o$ your %o e nee to be optimiIe in general or apply the te%hni=ues es%ribe in later %hapters o$ this part o$ the book.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Tracevie+
6he O1 tool in your toolbo< $or $in ing out Chere bottlene%ks are o%%urring in your appli%ation is 6ra%evieC. 6his is available both Cithin the A%lipse environment J though not as a separate perspe%tive J an as a stan alone tool.
What Is Traceview?
6ra%evieC is An roi 8s take on a metho pro$iler. !ro$ilers have e<iste $or most other plat$orms, in one $orm or $ashion, ating ba%k to the main$rame ays. 6e%hni%ally, the pro$iling in An roi is per$orme by the >alvik virtual ma%hine, un er the ire%tion o$ either >>M# or re=uests $rom your appli%ation %o e. >alvik Cill Crite the Ktra%e ataK &%all graphs shoCing metho s, Chat they %all, an the amount o$ time in ea%h' to a $ile on e<ternal storage o$ the evi%e or emulator. 6ra%evieC then vieCs these tra%e $iles in a 9"., alloCing you to visualiIe Khot spotsK, rill oCn to $in Chere the time is being taken, an so $orth. At the time o$ this Criting, 6ra%evieC is esigne $or use on single4%ore evi%es. Results on multi4%ore evi%es may be i$$i%ult to interpret.
Debug Class
.$ you knoC Chat %hunk o$ %o e you Cant to pro$ile, one Cay to arrange $or the pro$ile is to %all "tart+et-odTracing() on the ,ebug %lass. 6his takes the
6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
name o$ a tra%e $ile as a parameter an Cill begin re%or ing all a%tivity to that $ile, store in the root o$ your e<ternal storage. ?ou nee to %all "top+et-odTracing() at some point to stop the tra%e J $ailing to o so Cill leave you Cith a %orrupt tra%e $ile in the en . 0ote that your appli%ation Cill nee the .'%T/0/1T/'2 !0#T3' G/ permission $or this to Cork. .$ your appli%ation oes not normally nee this permission, make yoursel$ a note to remove it be$ore you ship the pro u%tion e ition o$ your pro u%t, as there is no sense asking $or any more permissions than you absolutely nee . Also, your evi%e or emulator Cill nee enough e<ternal storage to hol the $ile, Chi%h %an get very large $or long tra%es J 100M/ a minute is Cell Cithin reason.
DDMS
Alternatively, you %an initiate tra%ing via a toolbar button in >>M#. .n both the >>M# perspe%tive in A%lipse an the stan alone >>M#, there is a button in the toolbar above the tree4table o$ evi%es an pro%esses that toggles tra%ing on an o$$*
+n An roi 2.1 an earlier, this Cill Crite the tra%e out to a $ile on e<ternal storage, mu%h as "tart+et-odTracing() oes. )en%e, your appli%ation Cill nee .'%T/0/1T/'2 !0#T3' G/ in this %ase, plus have enough e<ternal storage spa%e to hol the $ile.
7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
+n An roi 2.2 an neCer, though, this ata is Critten straight to the evelopment ma%hine, bypassing e<ternal storage. 6his means you o not nee to Corry about permissions or $ree spa%e on your e<ternal storage. )en%e, unless your problem only e<ists on An roi 2.1 an earlier, you may $in it easier to o your 6ra%evieC Cork on a neCer An roi evi%e or emulator image. 6he $ile Cill Cin up in your evelopment ma%hine8s temporary ire%tory &e.g., 4tmp on Linu<'.
Eclipse/DDMS
.$ you use the >>M# perspe%tive in A%lipse to re%or the tra%e ata, the >ebug perspe%tive in A%lipse Cill automati%ally open up Chen you stop the tra%ing, shoCing you a 6ra%evieC tool*
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Standalone Traceview
.$ you use stan alone >>M# an run a tra%e on An roi 2.2 an up, it Cill automati%ally laun%h in the stan alone 6ra%evieC utility. .$ your tra%e $ile Coun up on e<ternal storage on your evi%e or emulator, you Cill nee to oCnloa it to your evelopment ma%hine, Chether using the (ile Manager Cithin >>M#, or via the adb pull %omman . +n%e on your evelopment ma%hine, you %an vieC it in the stan alone 6ra%evieC tool using the trace$iew %omman *
trace$iew 5pat--to-trace-file6
+r, you %an import the $ile into your A%lipse proHe%t, then ouble4%li%k on it in the !roHe%t A<plorer to vieC it in the 6ra%evieC tool.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
)ere is a 6ra%evieC s%reen shoCing that %o e e<e%ute 100,000 times, as pa%kage in a #tring(erfConcat a%tivity in the Trace$iew sample proHe%t in the book8s sour%e %o e*
-:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he bars in the top portion o$ the isplay shoC i$$erent threa s in the running appli%ation, in a timeline $ashion, Cith time running $rom le$t to right. 6he KmainK bar shoCs the main appli%ation threa , spen ing most o$ its time initialiIing the a%tivity. 6he 9C an )eapWorker threa s are involve in garbage %olle%tion, popping in $rom time to time to %olle%t garbage uring 100,000 iterations o$ the above algorithm. 6hose 100,000 iterations are run in an "*ncTa"k, so Ce o not en%ounter an appli%ation4 not4respon ing &A0R' ialog, an that is the KAsyn%6ask O1K threa at the top o$ the iagram.
?ou Cill noti%e that the horiIontal timeline bars are not %ontiguous J there are gaps. .n $a%t, i$ you Cere to %ombine all o$ the timelines into one, the
--
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
KholesK in most o$ the roCs Coul be $ille by time in another roC. 6his is illustrating that there is only one %ore on most An roi evi%e C!"s &these images Cere taken $rom a test run on a single4%ore 0e<us +ne'. We think o$ "*ncTa"k as moving Cork to the ba%kgroun , but it is important to remember that it still is %onsuming C!" time, even i$ the ba%kgroun threa means that Ce are not tying up the main appli%ation threa . 6he bottom hal$ o$ the isplay shoCs Chat metho s are taking up all o$ the time, in%lusively, in es%en ing or er. /y Kin%lusivelyK, 6ra%evieC means K%o e e<e%ute in this metho an any metho s it invokesK. )en%e, the top K100.0QK line shoCs the entry point to the Chole appli%ation, an the ne<t line shoCs Chere the "*ncTa"k8s ba%kgroun threa is being $orke , an so on. 6ypi%ally, you Cant to $in lines that re$eren%e your %o e. .n this %ase, lines 241 are $rom the com.common"ware pa%kage. Let8s $o%us on those*
+n their oCn, these lines are not espe%ially in$ormative. )oCever, i$ Ce $ol open the bottom roC, using the arroC in i%ator on the le$t, Ce %an rill oCn into Chat is going on insi e that parti%ular metho , Chi%h happens to be the algorithm shoCn earlier in this se%tion*
6he Ksel$K line re$ers to %o e that is ire%tly e<e%ute in the metho , not involving a neste metho %all, su%h as variable e%larations an returning values. We see the $alue3f() %alls, along Cith three roCs shoCing re$eren%es
-(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
to #tringBuilder. +n the sur$a%e, that may seem o , %onsi ering that Ce are not re$erring to #tringBuilder in the sour%e %o e. .t turns out that the ja$ac %ompiler repla%es string %on%atenation Cith append() %alls on a #tringBuilder, %reate on the $ly $or that spe%i$i% %on%atenation. #o, o$ the 3B.1Q o$ the time taken up in the entire run by the doTe"t() metho , 25.2Q is taken up by %reating these temporary #tringBuilder obHe%ts, 23.3Q is %onsume by %alling append() on the #tringBuilder, an another 13.-Q is use by %alling to#tring() to get the resulting #tring out o$ the #tringBuilder. 6his suggests an optimiIation* Ce %oul %reate our oCn #tringBuilder an use it $or %on%atenating the te<t, thereby saving us %reating a $eC temporary ones an %alling to#tring() e<tra times*
protected #tring doTest() 7 #tringBuilder re"ult8new StringBuilder(9T-i" i" a "tring9): re"ult.append(9 < t-at $arie" --9): re"ult.append(9 and al"o -a" 9): re"ult.append(#tring.valueOf(=)): re"ult.append(9 -*p-en" in it9): > return(re"ult.toString()):
6his implementation o$ the algorithm runs about tCi%e as $ast as the $irst. 6he KA<%lusiveK an KA<%l QK %olumns shoC hoC mu%h time is taken in an in ivi ual metho itsel$, not in%lu ing any %hil ren. .$ you sort on that, you see the spe%i$i% lo%al spots Chere time is being taken up. (or e<ample, here is a 6ra%evieC roster $rom testing the se%on algorithm shoCn above &the #tring(erfBuilder a%tivity'*
-4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
We see that the top three %ulprits are all An roi M>alvik metho s, Chi%h Ce %annot optimiIe. .nstea , the $a%t that they are taking up so mu%h time is in i%ative o$ the $a%t that Ce are %alling them a lot, also in evi en%e by the CallsM6otal %olumn. ?ou %an e<amine the parents o$ a %all to see Chere those %alls %ome $rom, to see i$ you %an %hange upstream %o e to result in $eCer su%h %alls*
)ere, Ce %an see that all those append?() %alls are triggere append() on the #tringBuilder, Chi%h is not terribly surprising.
by %alls to
?ou %an also Ioom in to take a very narroC look at the ata. #imply %li%k4 rag a bar in the timeline to sele%t an region to Ioom into. 6he timeline Cill sCit%h to shoC Hust that range o$ millise%on s an the %alls that take pla%e there*
-'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ you Ioom in $ar enough, you Cill start seeing soli blo%ks o$ %olor, %orrespon ing to the %olor4%o e metho s in the table o$ results on the bottom hal$ o$ the s%reen. ?ou %an tap on any blo%k o$ %olor to bring up that spe%i$i% metho in the table*
$igure -:0 Tracevie+= >oome# in on ?- millisecon# of run time= highlighting one specific metho#
Rooming ba%k out, though, is someChat o$ a pain. .$ you rag the timeline itsel$ ¬ one o$ the bars, but the Kmeter sti%kK shoCing the millise%on s' $rom le$t to right, you Cill Ioom out. >o this enough times, an you %an return appro<imately to the original state.
-5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
!ogging
6ra%evieC %an be use$ul, i$ you have a rough i ea o$ Chere your per$orman%e problem lies an nee to narroC it oCn $urther. .$ you have a large an %ompli%ate appli%ation, though, trying to si$t through all o$ it in 6ra%evieC may be i$$i%ult. )oCever, there is nothing stopping you $rom using goo ol 4$ashione logging to get a rough i ea o$ Chere your problems lie, $or $urther analysis via 6ra%evieC. @ust sprinkle your %o e Cith !og.d() %alls, logging #*"temClock.uptime+illi"() Cith an appropriate label to i enti$y Chere you Cere at that moment in time. KAyeballingK the LogCat output %an illustrate areas Chere une<pe%te elays are o%%urring J the areas in Chi%h you %an $o%us more time using 6ra%evieC. A use$ul utility %lass $or this is Timing!ogger, in the android.util pa%kage. .t Cill %olle%t a series o$ KsplitsK an %an ump them to LogCat along Cith the overall time betCeen the %reation o$ the Timing!ogger obHe%t an the %orrespon ing dumpTo!og() metho %all. 0ote, though, that this Cill only log to LogCat Chen you %all dumpTo!og() J all o$ the %alls to "plit() to re%or interme iate times have their results bu$$ere until dumpTo!og() is %alle . Also note that logging nee s to be set to ,AR/+#A $or this in$ormation to a%tually be logge J use the %omman adb "-ell "etprop log.tag.!3G0T G V/'B3#/, substituting your log tag &supplie to the Timing!ogger %onstru%tor' $or !3G0T G.
"P# Calculations
#ometimes, it may not even be stri%tly obvious hoC ba the problem is. (or e<ample, %onsi er s%rolling a !i"tView. #ome per$orman%e issues, like spora i% Khi%%upsK in the s%rolling, Cill be visually apparent. )oCever, absent those, it may be i$$i%ult to etermine Chether your parti%ular !i"tView is behaving more sloCly than you Coul e<pe%t. A %lassi% measurement $or games is $rames per se%on &(!#'. 9ame evelopers aim $or a high (!# value J 50 (!# is %onsi ere to be $airly
-6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
smooth, $or e<ample. )oCever, this sort o$ %al%ulation %an only really be one $or appli%ations that are %ontinuously raCing J su%h as Romain 9uy8s Win oC/a%kgroun sample appli%ation. +r inary An roi Ci get4base ".s are only raCing base upon user intera%tion or, possibly, upon ba%kgroun up ates to ata. .n other Cor s, i$ the ". Cill not even be trying to raC 50 times in a se%on , trying to measure (!# to get 50 (!# is pointless. ?ou may be able to a%hieve similar results, though, simply by logging hoC long it takes to, say, $ling a list &use "et3n#croll!i"tener() an Cat%h $or #C'3!!0#T T/0@!%2G an other events'.
(lash .M+, both $or the on4boar storage an $or Ke<ternal storageK &e.g., the #> %ar ' 0etCork .M+
-7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
)oCever, even here, it may not be obvious that you are per$orming these operations on the main appli%ation threa . 6his is parti%ularly true Chen the operations are really being one by An roi 8s %o e that you are simply %alling. 6hat is Chere #trict+ode %omes in. .ts mission is to help you etermine Chen you are oing things on the main appli%ation threa that might %ause a Hanky user e<perien%e.
Aa%h poli%y i%tates Chat #trict+ode shoul Cat%h $or &e.g., $lash rea s are +F but $lash Crites are not' an hoC #trict+ode shoul rea%t Chen you violate the rules, su%h as*
6he simplest thing to o is %all the stati% enable,efault"() metho on #trict+ode $rom onCreate() o$ your $irst a%tivity. 6his Cill set up normal operation, reporting all violations by simply logging to LogCat. )oCever, you %an set your oCn %ustom poli%ies via Builder obHe%ts i$ you so %hoose.
-8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
#imply %omment out or remove the #trict+ode setup %o e Chen you prepare your pro u%tion buil s "se some sort o$ pro u%tion $lag to skip the #trict+ode setup %o e Chen nee e
-9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER )
When An roi Cas $irst release , many a eveloper Cante to run CMCSS %o e on it. 6here Cas little support $or this, other than by istributing a binary e<e%utable an running it via a $orke pro%ess. While this Corks, it is a bit %umbersome, an the pro%ess4base inter$a%e limits hoC %leanly your CMCSS %o e %oul intera%t Cith a @ava4base ".. +n top o$ all o$ that, the use o$ su%h binary e<e%utables is not Cell supporte . .n @une 2001, the %ore An roi team release the 0ative >evelopment Fit &0>F'. 6his alloCs evelopers to Crite CMCSS $or An roi appli%ations in a supporte $ashion, in the $orm o$ libraries linke to a hosting @ava4base appli%ation via the @ava 0ative .nter$a%e &@0.'. 6his o$$ers a Cealth o$ opportunities $or An roi evelopment, an this part o$ the book Cill e<plore hoC you %an take a vantage o$ the 0>F to e<ploit those opportunities. 6his %hapter e<plains hoC to set up the 0>F an apply it to your proHe%t. What it oes not o is attempt to %over all possible uses o$ the 0>F J game appli%ations in parti%ular have a%%ess to many $rameCorks, like +pen9L an +pen#L, that are beyon the s%ope o$ this book.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Cith some reasons Chy the 0>F may not be the right solution $or every An roi problem, espite its bene$its.
((
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ you nee spee , >alvik is not the ansCer to ay, an ansCer tomorroC, either.
/oing .ative
@ava4base An roi evelopment via >alvik an the An roi #>F is $ar an aCay the option Cith the best support $rom the %ore An roi team. )6MLE appli%ation evelopment is another option that Cas brought to you by the %ore An roi evelopment team. 6he thir leg o$ the o$$i%ial An roi evelopment tria is the 0>F, provi e to evelopers to a ress some spe%i$i% problems, outline beloC.
Speed
(ar an aCay the biggest reason $or using the 0>F is spee , pure an simple. Writing in CMCSS $or the evi%e8s C!" Cill be a maHor spee improvement over Criting the same algorithms in @ava, espite An roi 8s Hust4in4time &@.6' %ompiler. 6here is overhea in rea%hing out to the CMCSS %o e $rom a hosting @ava appli%ation, an so $or the best per$orman%e, you Cill Cant a %oarse inter$a%e, Cithout a lot o$ %alls ba%k an $orth betCeen @ava an the native op%o es. 6his may re=uire some re esign o$ Chat might otherCise be the KnaturalK Cay o$ Criting the CMCSS %o e, or you may Hust have to settle $or less o$ a spee improvement. Regar less, $or many types o$ algorithms J $rom %ryptography to game A. to vi eo $ormat %onversions J using CMCSS Cith the 0>F Cill make your appli%ation per$orm mu%h better, to the point Chere it %an enable appli%ations to be su%%ess$ul that Coul be entirely too sloC i$ Critten solely in @ava. /ear in min , though, that mu%h o$ Chat you think is @ava %o e in your app really is native Kun er the %oversK. Many o$ the built4in An roi %lasses are thin shims over native implementations. Again, $o%us on applying the 0>F Chere you are per$orming lots o$ Cork yoursel$ in @ava %o e that might bene$it $rom the per$orman%e gains.
(4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Porting
?ou may alrea y have some CMCSS %o e, Critten $or another environment, that you Coul like to use Cith An roi . 6hat might be $or a esktop appli%ation. 6hat might be $or another mobile plat$orm, su%h as i!hone or Web+#, Chere CMCSS is an option. 6hat might be $or mobile plat$orm, su%h as #ymbian, Chere CMCSS is the %onventional solution, rather than some other language. Regar less, so long as that %o e is itsel$ relatively plat$orm4 in epen ent, it shoul be usable on An roi . 6his may signi$i%antly streamline your ability to support multiple plat$orms $or your appli%ation, even i$ oCn4to4the4metal spee is not really something you ne%essarily nee . 6his may also alloC you to reuse e<isting CMCSS %o e Critten by others, $or image pro%essing or s%ripting languages or anything else.
Android AP s
6he biggest issue Cith the 0>F is that you have very limite a%%ess to An roi itsel$. 6here are a $eC libraries bun le Cith An roi that you %an leverage, an a $eC other A!.s o$$ere spe%i$i%ally to the 0>F, su%h as the ability to ren er +pen9L B> graphi%s. /ut, generally speaking, the 0>F has no a%%ess to the An roi #>F, e<%ept by Cay o$ obHe%ts ma e available to it $rom the hosting appli%ation via @0.. As su%h, it is best to vieC the 0>F as a Cay o$ spee ing up parti%ular pie%es o$ an #>F appli%ation J game physi%s, au io pro%essing, +CR, an the like.
('
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
All o$ those are algorithms that nee to run on An roi evi%es Cith ata obtaine $rom An roi , but otherCise are in epen ent o$ An roi itsel$.
Cross!Platform Compatibilit"
While CMCSS can be Critten $or %ross4plat$orm use, o$ten it is not. #ometimes, the isparity is one o$ A!.s. Any time you use an A!. $rom a plat$orm &e.g., i!hone' or a library &e.g., Nt' not available on An roi , you intro u%e an in%ompatibility. 6his means that Chile a lot o$ your %o e J measure in terms o$ lines J may be $ine $or An roi , there may be enough plat$orm4spe%i$i% bits Coven throughout it that you Coul have a signi$i%ant reCrite ahea o$ you to make it truly %ross4plat$orm. An roi itsel$, though, has a %ompatibility issue, in terms o$ C!"s. An roi mostly runs on ARM evi%es to ay, sin%e An roi 8s initial $o%us Cas on smartphones, an ARM4poCere smartphones at that. )oCever, the $o%us on ARM Cill %ontinue to Caver, parti%ularly as An roi moves into other evi%es Chere other C!" ar%hite%tures are more prevalent, su%h as Atom or M.!# $or set4top bo<es. While your %o e may be Critten in a $ashion that Corks on all those ar%hite%tures, the binaries that %o e pro u%es Cill be spe%i$i% to one ar%hite%ture. 6he 0>F gives you a itional assistan%e in managing that, so that your appli%ation %an simultaneously support multiple ar%hite%tures. Right noC, the r5 version o$ the 0>F is $or ARM an <35.
Maturit"
6he >alvik ,M is young. 6he 0>F is younger still, ebuting in mi 42001. (eCer evelopers have been using the 0>F than have been using the #>F. 6he %ombination o$ age an usage gives the 0>F a $airly short tra%k re%or , meaning that there may be more 0>F problems than are presently knoCn.
(5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Available E#pertise
.$ you are seeking outsi e assistan%e $or your An roi evelopment e$$orts, there Cill be $eCer people available to assist you Cith 0>F evelopment, %ompare to #>F evelopment. 6he 0>F is neCer than the #>F, so many evelopers starte Cith Chat Cas originally available. Many appli%ations o not nee the 0>F, an so many evelopers Cill not have taken the time to learn hoC to use it. (urthermore, many An roi evelopers may be $ar more $luent in @ava than they are in CMCSS, base on their oCn ba%kgroun s, an so they Coul ten to sti%k Cith tools they are more %om$ortable Cith. 6o top it o$$, $eC books on An roi evelopment %over the 0>F, though this is being in%rementally improve , via books su%h as this one. .$ you are looking $or somebo y Cith 0>F e<perien%e, ask for it J o not assume that An roi evelopers knoC the 0>F nearly as Cell as they knoC the #>F.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Prere$uisites
?ou Cill nee the 90" make an 90" awk pa%kages installe . 6hese may be part o$ your environment alrea y. (or e<ample, in "buntu, run "udo aptitude in"tall make gawk , or use the #ynapti% !a%kage Manager, to ensure you have these tCo pa%kages. While you %an o 0>F evelopment ire%tly on Linu< or +# P, 0>F evelopment on Win oCs %an only be one using the CygCin environment. 6his gives you a Linu<4style shell an Linu<4style tools on a Win oCs !C. .n a ition to a base CygCin 1.2 &or neCer' installation, you Cill nee the make an gaCk CygCin pa%kages installe in CygCin. .$ you en%ounter i$$i%ulties Cith CygCin, you may Cish to %onsi er Chether running Linu< in a virtualiIation environment &e.g., ,irtual/o<' might be a better solution $or you.
Environment 'ariables
6he 0>F o%umentation Cill %ite an 2,A environment variable, set to point to the ire%tory in Chi%h you unpa%ke the 0>F. 6his is a o%umentation %onvention an oes not appear to be re=uire $or a%tual use o$ the 0>F, though it is not a ba i ea. ?ou %oul also %onsi er a ing the 0>F ire%tory to your ( T&, though that too is not re=uire .
(7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
/ear in min that you Cill be using the 0>F tools $rom the %omman line, an so being able to %onveniently re$eren%e this ire%tory is reasonably important.
2. 6he %o e implementing your @0. inter$a%e .$ you have never use @0. be$ore, @0. uses naming %onventions to tie $un%tions in a CMCSS library to their %orrespon ing hooks in the @ava %o e. (or e<ample, in the .eakBenc- proHe%t in the book8s sour%e %o e, you Cill $in jni4weakbenc-.c*
(8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Cinclude 5"tdlib.-6 Cinclude 5mat-.-6 Cinclude 5jni.-6 t*pedef un"igned c-ar boolean: "tatic $oid nsieve(int m) 7 un"igned int count 8 ?D iD j: boolean * flag" 8 (boolean *) malloc(m * "iEeof(boolean)): memset(flag"D FD m): for (i 8 G: i 5 m: ;;i) if (flag"HiI) 7 ;;count: for (j 8 i 55 F: j 5 m: j ;8 i) 44 if (flag"HjI) flag"HjI 8 ?: > > free(flag"):
$oid Java_com_commonsware_android_tuning_weakbench_WeakBench_nsievenative ( B2%/n$* en$D jobject t-iE ) 7 int i8?: for (i 8 ?: i 5 J: i;;) nsieve(F???? 55 (K-i)): > double eval_A(int iD int j) 7 return F.?4((i;j)*(i;j;F)4G;i;F): > $oid eval_A_times_u(int 2D con"t double uHID double 7 int iDj: for(i8?:i52:i;;) 7 uHiI8?: for(j8?:j52:j;;) uHiI;8eval_A(iDj)*uHjI: > > $oid eval_At_times_u(int 2D con"t double uHID double 7 int iDj: for(i8?:i52:i;;) 7 uHiI8?: for(j8?:j52:j;;) uHiI;8eval_A(jDi)*uHjI: > > uHI)
uHI)
(9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$oid eval_AtA_times_u(int 2D con"t double uHID double t uHI) 7 double $H2I: eval_A_times_u(2DuD$): eval_At_times_u(2D$D t u): > $oid Java_com_commonsware_android_tuning_weakbench_WeakBench_specnative ( B2%/n$* en$D jobject t-iE ) 7 int i: int 2 8 F???: double uH2ID$H2ID$B$D$$: for(i8?:i52:i;;) uHiI8F: for(i8?:i5F?:i;;) 7 eval_AtA_times_u(2DuD$): eval_AtA_times_u(2D$Du): > $B$8$$8?: for(i8?:i52:i;;) 7 $B$;8uHiI*$HiI: $$;8$HiI*$HiI: > >
Mu%h o$ the %o e shoCn here %omes $rom the 9reat Language /en%hmarks 9ame, spe%i$i%ally their n"ie$e an "pectral-norm ben%hmarks. An , mu%h o$ the %o e looks like normal C %o e. 6Co $un%tions, though, serve as @0. entry points* 1.
Ba$a0com0common"ware0abj0weakbenc-0.eakBenc-0n"ie$enati$e
2. Ba$a0com0common"ware0abj0weakbenc-0.eakBenc-0"pecnati$e As Cill be seen later in this se%tion, these Cill map to n"ie$enati$e() an "pecnati$e() metho s on a com.common"ware.abj.weakbenc-..eakBenc- %lass. 6he @ava %lass &Cith pa%kage' an metho names are %onverte into a $un%tion %all name, so @0. %an i enti$y the $un%tion at runtime. 6he implementation o$ these metho s o not make use o$ any @ava obHe%ts, nor o they return anything J they Hust implement the ben%hmark. A slightly more elaborate @0. A!. Cill be emonstrate later in this %hapter.
4:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
4-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
2. Ba$a0com0common"ware0abj0weakbenc-0.eakBenc-0"pecnati$e 6hose, in turn, e$ine as stati% metho s on a com.common"ware.abj.weakbenc-..eakBenc- %lass. Moreover, these metho s Cill nee to have the nati$e keyCor , in i%ating that their implementation is not $oun in @ava %o e, but in native CMCSS %o e. 6he naming %onvention o$ the C $un%tions alloCs the >alvik runtime to i enti$y Chat $un%tion names shoul be use $or those nati$e metho implementations. )oCever, that alone Cill be insu$$i%ient J Ce nee to tell >alvik Chere it %an $in the library in the $irst pla%e. While naming %onventions are goo enough $or the C $un%tion names, there is no %orrespon ing naming %onvention $or the library itsel$. 6o o this, Ce use the load!ibrar*() stati% metho on the #*"tem %lass. A %lass implementing native metho s shoul %all load!ibrar*() in a "tatic blo%k, so it is e<e%ute Chen the %lass is $irst re$eren%e . (or the 0>F, all Ce nee to o is supply the name Ce gave the library in the ndroid.mk $ile. )ere is the portion o$ the .eakBenc- %lass that has the nati$e metho s an the load!ibrar*() %all*
4(
nee
to
be
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
"tatic 7 #*"tem.loadLibrary(9weakbenc-9): > public nati$e $oid nsievenative(): public nati$e $oid specnative():
0oC, Ce %an %all our n"ie$enati$e() an "pecnati$e() metho s on .eakBenc-, Hust as i$ they Cere regular >alvik metho s on a regular >alvik %lass. 6he $a%t that they are really going o$$ an invoking C $un%tions is purely Kimplementation etailK that the %onsumers o$ those metho s %an be bliss$ully unaCare o$. itsel$ is an cti$it*, invoking both >alvik an native implementations o$ these tCo ben%hmarks. .t uses a series o$ "*ncTa"k obHe%ts $or e<e%uting the ben%hmarks on ba%kgroun threa s, then up ates TextView Ci gets in the ". to shoC the results*
.eakBencpackage com.common"ware.android.tuning.weakbenc-: import import import import import android.app. cti$it*: android.o". "*ncTa"k: android.o".Bundle: android.o".#*"temClock: android.widget.TextView:
public cla"" .eakBenc- extend" cti$it* 7 "tatic 7 #*"tem.loadLibrary(9weakbenc-9): > public nati$e $oid nsievenative(): public nati$e $oid specnative(): O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): new JavaSieveTask().e"ecute(): > 4* * Code after t-i" point i" adapted from t-e Great Computer !anguage * #-ootout. Cop*rig-t" are owned b* w-oe$er contributed t-i" "tuffD * or po""ibl* t-e #-ootout it"elfD "ince t-ere i"nPt muc- information * on owner"-ip t-ere. !icen"ed under a modified B#, licen"e. *4
44
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
O3$erride protected Void do%nBackground(Void... unu"ed) 7 "tart8#*"temClock.uptime&illis(): int n8K: int m8(F55n)*F????: booleanHI flag"8new booleanHm;FI: nsieve(mDflag"): m8(F55n-F)*F????: nsieve(mDflag"): m8(F55n-G)*F????: nsieve(mDflag"): return(null): > O3$erride protected $oid on#ost$"ecute(Void unu"ed) 7 long delta8#*"temClock.uptime&illis()-"tart: re"ult.setTe"t(#tring.valueOf(delta)): new JavaSpecTask().e"ecute(): > > "*ncTa"k5VoidD VoidD Void6 7
O3$erride protected $oid on#re$"ecute() 7 re"ult8(TextView)find!iewBy%d('.id."pec0ja$a): re"ult.setTe"t(9running...9): > O3$erride protected Void do%nBackground(Void... unu"ed) 7 "tart8#*"temClock.uptime&illis():
4'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
O3$erride protected $oid on#ost$"ecute(Void unu"ed) 7 long delta8#*"temClock.uptime&illis()-"tart: re"ult.setTe"t(#tring.valueOf(delta)): new J'%SieveTask().e"ecute():
> >
O3$erride protected Void do%nBackground(Void... unu"ed) 7 "tart8#*"temClock.uptime&illis(): nsievenative(): return(null): > O3$erride protected $oid on#ost$"ecute(Void unu"ed) 7 long delta8#*"temClock.uptime&illis()-"tart: re"ult.setTe"t(#tring.valueOf(delta)): new J'%SpecTask().e"ecute(): > > "*ncTa"k5VoidD VoidD Void6 7
45
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
O3$erride protected $oid on#ost$"ecute(Void unu"ed) 7 long delta8#*"temClock.uptime&illis()-"tart: re"ult.setTe"t(#tring.valueOf(delta)): > >
pri$ate "tatic int nsieve(int mD booleanHI i"(rime) 7 for (int i8G: i 58 m: i;;) i"(rimeHiI 8 true: int count 8 ?: for (int i8G: i 58 m: i;;) 7 if (i"(rimeHiI) 7 for (int k8i;i: k 58 m: k;8i) i"(rimeHkI 8 fal"e: count;;: > > return count: > pri$ate final double Appro"imate(int n) 7 44 create unit $ector doubleHI u 8 new doubleHnI: for (int i8?: i5n: i;;) uHiI 8 F: 44 G? "tep" of t-e power met-od doubleHI $ 8 new doubleHnI: for (int i8?: i5n: i;;) $HiI 8 ?: for (int i8?: i5F?: i;;) 7 &ultiplyAtAv(nDuD$): &ultiplyAtAv(nD$Du): > 44 B8 t multiplied b* 44 $.B$ 4($.$) eigen$alue of $ double $B$ 8 ?D $$ 8 ?: for (int i8?: i5n: i;;) 7 $B$ ;8 uHiI*$HiI: $$ ;8 $HiI*$HiI: > return +at-.s(rt($B$4$$): tran"po"ed
46
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
> 4* return element iDj of infinite matrix pri$ate final double A(int iD int j)7 return F.?4((i;j)*(i;j;F)4G ;i;F): > *4
4* multipl* $ector $ b* matrix *4 pri$ate final $oid &ultiplyAv(int nD doubleHI $D doubleHI for (int i8?: i5n: i;;)7 $HiI 8 ?: for (int j8?: j5n: j;;) $HiI ;8 A(iDj)*$HjI: > > 4* multipl* $ector $ b* matrix tran"po"ed *4 pri$ate final $oid &ultiplyAtv(int nD doubleHI $D doubleHI for (int i8?:i5n:i;;)7 t$HiI 8 ?: for (int j8?: j5n: j;;) t$HiI ;8 A(jDi)*$HjI: > >
$)7
t$)7
>
4* multipl* $ector $ b* matrix and t-en b* matrix tran"po"ed *4 pri$ate final $oid &ultiplyAtAv(int nD doubleHI $D doubleHI t $)7 doubleHI u 8 new doubleHnI: &ultiplyAv(nD$Du): &ultiplyAtv(nDuD t $): >
As Cith our C implementations o$ the ben%hmarks, the @ava sour%e %o e is erive $rom the 9reat Language /en%hmarks 9ame.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
to a Hust your pplication.mk $ile to a in more plat$orms, so your appli%ation Cill be available $or these non4ARM environments.
48
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 3
FnoCing that you have C!"4relate issues in your app is one thing J oing something about it is the ne<t %hallenge. .n some respe%ts, tuning an An roi appli%ation is a Kone4o$$K Hob, tie to the parti%ulars o$ the appli%ation an Chat it is trying to a%%omplish. 6hat being sai , this %hapter Cill outline some general4purpose Cays o$ boosting per$orman%e that may %ounter issues that you are running into.
49
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
':
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
While later An roi evi%es o have $loating4point %opro%essor support, that oes not mean that $loating4point math is noC as $ast as integer math. .$ you $in that your %o e is spen ing lots o$ time on $loating4point %al%ulations, %onsi er Chether a %hange in units Coul alloC you to repla%e the $loating4point %al%ulations Cith integer e=uivalents. (or e<ample, mi%ro egrees $or latitu e an longitu e provi e a e=uate granularity $or most maps, yet alloC 9oogle Maps to o all o$ its %al%ulations in integers. #imilarly, %onsi er Chether the $ull e%imal a%%ura%y o$ $loating4point values is really nee e . While it may be physi%ally possible to per$orm istan%e %al%ulations in meters Cith a%%ura%y to a $eC e%imal points, $or e<ample, in many %ases the user Cill not nee that egree o$ a%%ura%y. .$ so, perhaps %hanging to $i<e 4point &integer' math %an boost your per$orman%e.
'-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
+$ %ourse, this Cill also in%rease the %omple<ity o$ your appli%ation, Cith long4term impa%ts in terms o$ maintenan%e %ost. )en%e, o not assume the built4in algorithms are the Corst, either J optimiIe those algorithms that 6ra%evieC or logging suggest are Chere you are spen ing too mu%h time.
$ini%i5e IPC
Calling a metho on an obHe%t in your oCn pro%ess is $airly ine<pensive. 6he overhea o$ the metho invo%ation is $airly minus%ule, an so the time involve is simply hoCever long it takes $or that metho to o its Cork. .nvoking behaviors in another pro%ess, via inter4pro%ess %ommuni%ation &.!C', is %onsi erably more e<pensive. ?our re=uest has to be %onverte into a byte array &e.g., via the (arcelable inter$a%e', ma e available to the
'(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
other pro%ess, %onverte ba%k into a regular re=uest, then e<e%ute . 6his a s substantial C!" overhea . 6here are three basi% $lavors o$ .!C in An roi *
K>ire%tlyK invoking a thir 4party appli%ation8s servi%e8s A.>L4 publishe inter$a%e, to Chi%h you boun Cith bind#er$ice() !er$orming operations on a %ontent provi er that is not part o$ your appli%ation &i.e., supplie by the +# or a thir 4party appli%ation' !er$orming other operations that, un er the %overs, trigger .!C
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
oing lots o$ them in a loop, or as the user $lings a !i"tView, might be%ome noti%eable.
"se bulk%n"ert() rather than lots o$ in ivi ual in"ert() %alls 6ry to avoi %alling update() or delete() in a tight loop J instea , i$ the %ontent provi er supports it, use a more %omple< KW)ARA %lauseK to up ate or elete everything at on%e 6ry to get all your ata ba%k in $eC =ueries, rather than lots o$ little ones... though this %an then %ause you issues in terms o$ memory %onsumption
4emote 5S 5peration
6he %ontent provi er s%enario is really a subset o$ the broa er %ase Chere you re=uest that An roi o something $or you an Cin s up per$orming .!C as part o$ that. #ometimes, this is going to be obvious. .$ you are sen ing %omman s to a thir 4party servi%e via "tart#er$ice(), by e$inition, this Cill involve .!C, sin%e the thir 4party servi%e Cill run in a thir 4party pro%ess. 6ry to avoi %alling "tart#er$ice() lots o$ times in %lose su%%ession. )oCever, there are plenty o$ %ases that are less obvious*
''
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
All re=uests to "tart cti$it*(), "tart#er$ice(), an "endBroadca"t() involve .!C, as it is a separate +# pro%ess that oes the real Cork Registering unregistering regi"ter'ecei$er()' involves .!C an a
Broadca"t'ecei$er
&e.g.,
All o$ the Ksystem servi%esK, su%h as !ocation+anager, are really ri%h inter$a%es to an A.>L4 e$ine remote servi%e, an so most operations on these system servi%es re=uire .!C
+n%e again, your obHe%tive shoul be to minimiIe %alls that involve .!C, parti%ularly Chere you are making those %alls $re=uently in %lose su%%ession, su%h as in a loop. (or e<ample, $re=uently %alling get!a"tAnown!ocation() Cill be e<pensive, as that involves .!C to a system pro%ess.
9etters an setters, Chile perhaps use$ul $or en%apsulation, are signi$i%antly sloCer than ire%t $iel a%%ess. (or simpler %ases, su%h as View&older obHe%ts $or optimiIing an A apter, %onsi er skipping the a%%essor metho s an Hust use the $iel s ire%tly. #ome popular metho %alls are repla%e by han 4%reate assembler instru%tions rather than %o e generate via the @.6 %ompiler. index3f() on #tring an arra*cop*() on #*"tem are tCo %ite e<amples. 6hese Cill run mu%h $aster than anything you might %reate yoursel$ in @ava.
'5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
'6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
begins, then using an re%y%ling those obHe%ts themselves, only alloCing them to be%ome garbage a$ter game play en s. Most non4game An roi appli%ations may not have to go to =uite that e<treme a%ross the boar . )oCever, there are %ases Chere e<%essive allo%ation may %ause you i$$i%ulty. (or e<ample, avoi ing %reating too mu%h garbage is one aspe%t o$ vieC re%y%ling Cith dapterView, Chi%h is %overe in greater etail in the ne<t se%tion. .$ 6ra%evieC in i%ates that you are spen ing a lot o$ time in garbage %olle%tion, pay attention to your loops or things that may be invoke many times in rapi su%%ession &e.g., a%%essing ata $rom a %ustom Cur"or implementation that is tie to a Cur"or dapter'. 6hese are the most likely pla%es Chere your oCn %o e might be %reating lots o$ e<tra obHe%ts that are not nee e . A<amining the heap to see Chat is all being %reate &an eventually garbage %olle%te ' Cill be %overe in an up%oming %hapter o$ the book.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
maintain separate obHe%t pools $or ea%h type o$ roC $rom your dapter, so getView() is guarantee to be passe a con$ertView that mat%hes the roC type you are trying to %reate. A more a van%e optimiIation J %a%hing all those lookups J is also possible on%e your roC re%y%ling is in pla%e. +$ten re$erre to as Kthe hol er patternK, you o the findViewB*%d() %alls Chen you in$late a neC roC, then atta%h the findViewB*%d() results to the roC itsel$ via some %ustom Khol erK obHe%t an the "etTag() metho on View. When you re%y%le the roC, you %an get your Khol erK ba%k via getTag() an skip having to o the findViewB*%d() %alls again.
findViewB*%d()
someChat
0ot only o these te%hni=ues save C!" time overall, but all o$ this Cork is alCays one on the main appli%ation threa , so it signi$i%antly boosts per%eive per$orman%e.
:ac*ground Threads
+$ %ourse, the ba%kbone o$ any strategy to move Cork o$$ the main appli%ation threa is to use ba%kgroun threa s, in one $orm or $ashion. ?ou Cill Cant to apply these in pla%es Chere #trict+ode %omplains about netCork or isk .M+, or pla%es Chere 6ra%evieC or logging in i%ate that you are taking too mu%h time on the main appli%ation threa uring 9". pro%essing &e.g., %onverting oCnloa e bitmap images into Bitmap obHe%ts via Bitmap@actor*'. #ometimes, you Cill manually i%tate Chere Cork shoul be one in the ba%kgroun , either by $orking threa s yoursel$ or by using "*ncTa"k. "*ncTa"k is a ni%e $rameCork, han ling all o$ the inter4threa %ommuni%ation $or you an neatly pa%kaging up the Cork to be one in rea ily un erstoo metho s. )oCever, "*ncTa"k oes not $it every s%enario J it is mostly esigne $or Ktransa%tionalK Cork that is knoCn to take a mo est amount o$ time &millise%on s to se%on s' then en . (or %ases Chere you nee unboun e ba%kgroun pro%essing, su%h as monitoring a so%ket $or in%oming ata, $orking your oCn threa Cill be the better approa%h.
'8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
#ometimes, you Cill use $a%ilities supplie by An roi to move Cork to the ba%kgroun . (or e<ample, many a%tivities are ba%ke by a Cur"or obtaine $rom a atabase or %ontent provi er. Classi%ally, you Coul manage the %ursor &via "tart+anagingCur"or()' or otherCise arrange to re$resh that Cur"or in on'e"ume(), so Chen your a%tivity returns to the $oregroun a$ter having been gone $or a Chile, you Coul have $resh ata. )oCever, this pattern ten s to lea to atabase .M+ on the main appli%ation threa , triggering %omplaints $rom #trict+ode. An roi B.0 an the An roi Compatibility Library o$$er a !oader $rameCork esigne to try to solve the %ore pattern o$ re$reshing the ata, Chile arranging $or the Cork to be one asyn%hronously. UU 6/>* Loa er sample VV
'9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he C(M-Ba$a4Go "*nc sample proHe%t in the book8s sour%e %o e emonstrates go "*nc() in use, as the proHe%t name might suggest. +ur a%tivity8s layout %onsists o$ tCo Button Ci gets an an /ditText Ci get*
5Sxml $er"ion89F.?9 encoding89utf-T9S6 5!inear!a*out xmln"Qandroid89-ttpQ44"c-ema".android.com4apk4re"4android9 androidQorientation89$ertical9 androidQla*out0widt-89fill0parent9 androidQla*out0-eig-t89fill0parent96 5/ditText androidQid89O;id4editTextF9 androidQla*out0widt-89matc-0parent9 androidQla*out0-eig-t89wrap0content96 54/ditText6 5Button androidQla*out0widt-89matc-0parent9 androidQid89O;id4buttonF9 androidQla*out0-eig-t89wrap0content9 androidQtext89O"tring4nona"*nc9 androidQonClick89"end2on "*nc9654Button6 5Button androidQla*out0widt-89matc-0parent9 androidQid89O;id4buttonG9 androidQla*out0-eig-t89wrap0content9 androidQtext89O"tring4a"*nc9 androidQonClick89"end "*nc9654Button6 54!inear!a*out6
6he a%tivity itsel$ simply has "end "*nc() an "end2on "*nc() metho s, ea%h invoking "endBroadca"t() to a i$$erent Broadca"t'ecei$er implementation*
package com.common"ware.android.tuning.goa"*nc: import import import import android.app. cti$it*: android.content.%ntent: android.o".Bundle: android.$iew.View:
public cla"" Go "*nc cti$it* extend" cti$it* 7 O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): > public $oid sendAsync(View $) 7 sendBroadcast(new %ntent(t-i"D > "*nc'ecei$er.cla"")):
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
package com.common"ware.android.tuning.goa"*nc: import import import import android.content.Broadca"t'ecei$er: android.content.Context: android.content.%ntent: android.o".#*"temClock:
public cla"" 2on "*nc'ecei$er extend" Broadca"t'ecei$er 7 O3$erride public $oid on)eceive(Context arg?D %ntent argF) 7 #*"temClock.sleep(U???): > >
)en%e, i$ you %li%k the K#en 0on4Asyn% /roa %astK button, not only Cill the button $ail to return to its normal state $or seven se%on s, but the /ditText Cill not respon to user input either. 6he "*nc'ecei$er, though, uses go "*nc()*
package com.common"ware.android.tuning.goa"*nc: import import import import android.content.Broadca"t'ecei$er: android.content.Context: android.content.%ntent: android.o".#*"temClock:
public cla"" "*nc'ecei$er extend" Broadca"t'ecei$er 7 O3$erride public $oid on)eceive(Context contextD %ntent intent) 7 final Broadca"t'ecei$er.(ending'e"ult re"ult8goAsync(): (new Thread() 7 public $oid run() 7 #*"temClock.sleep(U???): re"ult.finish(): > >).start(): > >
6he go "*nc() metho returns a (ending'e"ult, Chi%h supports a series o$ metho s that you might or inarily $ire on the Broadca"t'ecei$er itsel$ &e.g., abortBroadca"t()' but Cant to o on a ba%kgroun threa . ?ou nee your ba%kgroun threa to have a%%ess to the (ending'e"ult J in this %ase, via a final lo%al variable. When you are one Cith your Cork, %all fini"-() on the (ending'e"ult.
5-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ you %li%k the K#en Asyn% /roa %astK button, even though Ce are still sleeping $or 2 se%on s, Ce are oing so on a ba%kgroun threa , an so our user inter$a%e is still responsive.
#aving #haredPre7erences
6he %lassi% Cay to save #-ared(reference"./ditor %hanges Cas via a %all to commit(). 6his Crites the pre$eren%e in$ormation to an PML $ile on Chatever threa you are on J another hi en sour%e o$ isk .M+ you might be oing on the main appli%ation threa . .$ you are on A!. Level 1, an you are Cilling to blin ly try saving the %hanges, use the neC appl*() metho on #-ared(reference"./ditor, Chi%h Corks asyn%hronously. .$ you nee to support ol er versions o$ An roi , or you really Cant the boolean return value $rom commit(), %onsi er oing the commit() %all in an "*ncTa"k or ba%kgroun threa . An , o$ %ourse, to support both o$ these, you Cill nee to employ tri%ks like %on itional %lass loa ing. ?ou %an see that use $or saving #-ared(reference" in the C(M-Ba$a4(ref"(er"i"t proHe%t in the book8s sour%e %o e. 6he a%tivity rea s in a pre$eren%e, puts the %urrent value on the s%reen, then up ates the pre$eren%e Cith the help o$ an b"tract(ref"(er"i"t#trateg* %lass an its per"i"t() metho *
package com.common"ware.android.tuning.pref": import import import import import android.app. cti$it*: android.content.#-ared(reference": android.o".Bundle: android.preference.(reference+anager: android.widget.TextView:
public cla"" (ref"(er"i"t cti$it* extend" cti$it* 7 pri$ate "tatic final #tring A/N89counter9: O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main):
5(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
#-ared(reference" pref"8 (reference+anager.get*efaultShared#references(t-i"): int counter8pref".get%nt(A/ND ?): ((TextView)find!iewBy%d('.id.$alue)).setTe"t(#tring.valueOf(counter)): > > b"tract(ref"(er"i"t#trateg*.persist(pref".edit().put%nt(A/ND counter;F)):
b"tract(ref"(er"i"t#trateg* is an abstra%t base %lass that Cill hol a strategy implementation, epen ing on An roi version. +n pre4 )oney%omb buil s, it uses an implementation that $orks a ba%kgroun threa to per$orm the commit()*
package com.common"ware.android.tuning.pref": import android.content.#-ared(reference": import android.o".Build: ab"tract public cla"" b"tract(ref"(er"i"t#trateg* 7 ab"tract $oid persistAsync(#-ared(reference"./ditor editor): pri$ate "tatic final b"tract(ref"(er"i"t#trateg* %2#T 2C/8init%mpl():
public "tatic $oid persist(#-ared(reference"./ditor editor) 7 %2#T 2C/.persistAsync(editor): > pri$ate "tatic b"tract(ref"(er"i"t#trateg* init%mpl() 7 int "dk8new %nteger(Build.V/'#%32.#,A).int!alue(): if ("dk5Build.V/'#%320C3,/#.&32/NC3+B) 7 return(new ommitAsyncStrategy()): > > return(new ApplyStrategy()):
"tatic cla"" Commit "*nc#trateg* extend" b"tract(ref"(er"i"t#trateg* 7 O3$erride $oid persistAsync(final #-ared(reference"./ditor editor) 7 (new Thread() 7 O3$erride public $oid run() 7 editor.commit(): > >).start(): >
54
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
> >
+n )oney%omb an higher, it uses a separate strategy %lass that uses the neC appl*() metho *
package com.common"ware.android.tuning.pref": import android.content.#-ared(reference"./ditor: public cla"" ppl*#trateg* extend" b"tract(ref"(er"i"t#trateg* 7
>
/y separating the )oney%omb4spe%i$i% %o e out into a separate %lass, Ce %an avoi loa ing it on ol er evi%es an en%ountering the rea e Verif*/rror. Whether using the built4in appl*() metho is Corth ealing Cith multiple strategies, versus simply %alling commit() on a ba%kgroun threa , is up to you.
5'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
you
$ork,
6hrea s you use via "*ncTa"k run at a loCer priority &T&'/ ,0('%3'%TN0B CAG'3M2,'. .$ you $ork your oCn threa s, then, you might Cish to %onsi er moving them to a loCer priority as Cell, to a$$e%t hoC mu%h time they get %ompare to the main appli%ation threa . ?ou %an o this via "etT-read(riorit*() on the (roce"" %lass. 6he loCest possible priority, T&'/ ,0('%3'%TN0!3./#T, is es%ribe as Konly $or those Cho really, really on8t Cant to run i$ anything else is happeningK.
55
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
?ou might use this $or Ki le4time pro%essingK, but bear in min that the threa Cill be pause a lot to alloC other threa s to run. LoCer4priority threa s Cill help ensure that your ba%kgroun Cork oes not a$$e%t your $oregroun ".. !ro%esses themselves are put in a loCer4 priority %lass as they move to the ba%kgroun &e.g., you have no a%tivities visible', Chi%h $urther re u%es the amount o$ C!" time you Cill be using at any given moment. Also, note that %ntent#er$ice uses a threa at e$ault ¬ ba%kgroun ' priority J you may Cish to rop the priority o$ this threa to something that Cill be loCer than your main appli%ation threa , to minimiIe hoC mu%h C!" time the %ntent#er$ice steals $rom your "..
56
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
shot alarm to Cake you up in B0 minutes, in hopes that the user Cill no longer be using the evi%e. At the same time, you may Cish to %onsi er having a Kre$reshK menu %hoi%e someChere, $or Chen the user spe%i$i%ally Cants you to go get the up ate &i$ available' now, $or Chatever reason.
57
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER ;
As anyone Cho oCne an Apple 0eCton or !alm , !>A ba%k in the 11108s, han hel evi%es have been aroun $or =uite some time. (or a very long time, they Cere a ni%he pro u%t, asso%iate Cith geeks, ner s, an the o%%asional business e<e%utive. .nternet a%%ess %hange all o$ that. /la%kberry $or enterprise messaging J an outgroCth o$ its original tCo4Cay paging approa%h J blaIe part o$ the trail, but the %on%ept K%rosse the %hasmK to or inary people Cith the a vent o$ the i!hone, An roi evi%es, an similar e=uipment. 6here$ore, it is not terribly surprising Chen An roi evelopers Cant to a .nternet %apabilities to their apps. 6o the %ontrary, it is almost unusual Chen you en%ounter an app that oes not Cant to use the .nternet $or something or another. )oCever, mobile .nternet a%%ess inherits all o$ the %lassi% problems o$ .nternet a%%ess &e.g., Kserver not $oun K' an a s neC an e<%iting %hallenges, all o$ Chi%h %an leave a eveloper Cith an app that has per$orman%e issues.
6-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
time i$$eren%e might a%%ount $or more poCer %onsumption, i$ the C!" %oul be poCere oCn $or the rest o$ that time. 6hese %hapters Cill shoC you hoC you %an rea%t to %hanges in %onne%tivity an approa%hes $or hoC to use that in$ormation to re u%e %osts $or the user.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
%onne%tivity... at least, so long as the %arriers have not melte oCn ue to overuse, as A6W6 ten e to o uring the early months o$ the i!hone .nvasion. +utlying areas are mu%h more hit4or4miss. ,oi%e is sometimes a %hallenge, let alone ata. An it only seems as though there is a #tarbu%ks every 100 meters, Chi%h might a%tually provi e blanket Wi(i %overage. 6hen, o$ %ourse, there are planes &most o not o$$er in4$light Wi(i at this time', international travel Cithout an international4%apable phone plan, an so on. #ome An roi appli%ations have the potential to still o$$er near4%omplete $un%tionality espite this, Cith a bit o$ user assistan%e. (or e<ample, 9oogle Maps $or An roi noC has an o$$line %a%hing $eature, Chi%h Cill oCnloa ata $or a 104mile ra ius $rom a given point, $or use Chile the evi%e is otherCise o$$line. )ere, the issue be%omes less one o$ ban Ci th &other than ete%ting that you have no %onne%tion' an more one o$ %a%hing an storage. 6he spa%e4 relate issues that these te%hni=ues %an raise Cill be %overe elseChere in this book.
65
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER <
6o be able to have more intelligent %o e J %o e that %an a apt to .nternet a%tivity on the evi%e J An roi o$$ers the Traffic#tat" %lass. 6his %lass really is a gateCay to a blo%k o$ native %o e that reports on tra$$i% usage $or the entire evi%e an per4appli%ation, $or both re%eive an transmitte ata. 6his %hapter Cill e<amine hoC you %an a%%ess Traffic#tat" an interpret its ata.
Traffic"tats Basics
6he Traffic#tat" %lass is not esigne to be instantiate J you Cill not be invoking a %onstru%tor by %alling new Traffic#tat"() or something like that. Rather, Traffic#tat" is merely a %olle%tion o$ stati% metho s, mappe to native %o e, that provi e a%%ess to point4in4time tra$$i% values. 0o spe%ial permissions are nee e to use any o$ these metho s. Most o$ the metho s Cere a e in A!. Level 3 an there$ore shoul be %allable on most An roi evi%es in use to ay.
Device #tatistics
.$ you are intereste in overall tra$$i%, you Cill probably %are most about the getTotal'xB*te"() an getTotalTxB*te"() on Traffic#tat". 6hese metho s return re%eive an transmitte tra$$i%, respe%tively, measure in bytes. ?ou also have*
67
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
an getTotalTx(acket"(), i$ $or your %ase measuring .! pa%kets is a better measure than bytes
getTotal'x(acket"() get+obile'xB*te"()
an get+obileTxB*te"(), Chi%h return the tra$$i% going over mobile ata &also in%lu e in the total' an get+obileTx(acket"(), Chi%h are the pa%ket %ounts $or the mobile ata %onne%tion
get+obile'x(acket"()
Per6Application #tatistics
6e%hni%ally, Traffic#tat" oes not provi e per4appli%ation tra$$i% statisti%s. Rather, it provi es per4".> tra$$i% statisti%s. .n most %ases, the ".> &user .>' o$ an appli%ation is uni=ue, an there$ore per4".> statisti%s map to per4 appli%ation statisti%s. )oCever, it is possible $or multiple appli%ations to share a single ".> &e.g., via the androidQ"-aredM"er%d mani$est attribute' J in this %ase, Traffic#tat" Coul appear to provi e tra$$i% ata $or all appli%ations sharing that ".>. 6here are per4".> e=uivalents o$ the $irst $our metho s liste in the previous se%tion, repla%ing K6otalK Cith K"i K. #o, to $in out overall tra$$i% $or an appli%ation, you %oul use getMid'xB*te"() an getMidTxB*te"(). )oCever, these are the only tCo ".>4spe%i$i% metho s that Cere implemente in A!. Level 3. A=uivalents o$ the others &e.g., getMid'x(acket"()' Cere a e in A!. Level 12. A!. Level 12 also a e some 6C!4spe%i$i% metho s &e.g., getMidTcpTxB*te"()'. 0ote, though, that the mobile4only metho are only available at the evi%e levelG there are no ".>4 spe%i$i% versions o$ those metho s.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
results shoul be use $or %omparison purposes, either %omparing the same value over time or %omparing multiple values at the same time. (or e<ample, to measure ban Ci th %onsumption, you Cill nee to re%or the Traffic#tat" values at one point in time, then again later J the i$$eren%e betCeen them represents the %onsume ban Ci th uring that perio o$ time. .n pra%ti%e, Chile the KtotalK metho s seem reliable, the per4".> metho s o$ten return -F. 6he o$$i%ial e<planation $or this is that the parti%ular tra$$i% metri% is unavailable on that evi%e, an this oes e<plain some o$ the -F values that are returne . (or e<ample, a 0e<us +ne running An roi 2.B returns -F $or all the per4".> metho s, Chile a 0e<us # running An roi 2.B Cill return a positive value $or some ".>s. .t is un%lear Chat the other -F values mean. 6Co possible meanings are*
6here has been no tra$$i% o$ that type on that ".> sin%e boot, or ?ou o not have permission to knoC the tra$$i% o$ that type on that ".>
)en%e, the per4".> values are a bit Khit or missK, Chi%h you Cill nee to take into a%%ount.
3xampleB TrafficAonitor
6o illustrate the use o$ Traffic#tat" metho s an analysis, let us Calk through the %o e asso%iate Cith the Traffic+onitor sample appli%ation. 6his is a simple a%tivity that re%or s a snapshot o$ the %urrent tra$$i% levels on startup, then again Chenever you tap a button. +n4s%reen, it Cill isplay the %urrent value, previous value, an i$$eren%e &K eltaK' betCeen them. .n LogCat, it Cill ump the same in$ormation on a per4".> basis.
Tra77icRecord
.t Coul have been ni%e i$ Traffic#tat" Cere in ee an obHe%t that you Coul instantiate, that %apture the tra$$i% values at that moment in time.
69
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Alas, that is not hoC it Cas Critten, so Ce nee to o that ourselves. .n the Traffic+onitor proHe%t, this Hob is elegate to a Traffic'ecord %lass*
package com.common"ware.android.tuning.traffic: import android.net.Traffic#tat": cla"" Traffic'ecord 7 long tx8?: long rx8?: #tring tag8null: Traffic)ecord() 7 tx8Traffic#tat".getTotalT"Bytes(): rx8Traffic#tat".getTotal)"Bytes(): > Traffic)ecord(int uidD #tring tag) 7 tx8Traffic#tat".get+idT"Bytes(uid): rx8Traffic#tat".get+id)"Bytes(uid): t-i".tag8tag: >
>
6here are tCo separate %onstru%tors, one $or the total %ase an one $or the per4".> %ase. 6he total %ase Hust logs getTotal'xB*te"() an getTotalTxB*te"(), Chile the per4".> %ase uses getMid'xB*te"() an getMidTxB*te"(). 6he per4".> %ase also stores a KtagK, Chi%h is simply a #tring i enti$ying the ".> $or this re%or J as you Cill see, Traffic+onitor uses this $or a pa%kage name.
Tra77ic#napshot
An in ivi ual Traffic'ecord, though, is insu$$i%ient to %ompletely %apture the tra$$i% $igures at a moment in time. We nee a %olle%tion o$ Traffic'ecord obHe%ts, one $or the evi%e &KtotalK' an one per running ".>. 6he Cork to %olle%t all o$ that is han le by a Traffic#nap"-ot %lass*
package com.common"ware.android.tuning.traffic: import ja$a.util.&a"-+ap: import android.content.Context: import android.content.pm. pplication%nfo: cla"" Traffic#nap"-ot 7
7:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Traffic'ecord de$ice8null: &a"-+ap5%ntegerD Traffic'ecord6 app"8 new &a"-+ap5%ntegerD Traffic'ecord6(): TrafficSnapshot(Context ctxt) 7 de$ice8new Traffic)ecord(): &a"-+ap5%ntegerD #tring6 app2ame"8new &a"-+ap5%ntegerD #tring6(): for ( pplication%nfo app Q ctxt.get#ackage&anager().get%nstalledApplications(?)) 7 app2ame".put(app.uidD app.package2ame): > for (%nteger uid Q app2ame".keySet()) 7 app".put(uidD new Traffic)ecord(uidD app2ame".get(uid))): > > >
6he %onstru%tor uses (ackage+anager to iterate over all installe appli%ations an buil s up a &a"-+ap, mapping the ".> to a Traffic'ecord $or that ".>, tagge Cith the appli%ation pa%kage name &e.g., com.common"ware.android.tuning.traffic'. .t also %reates one Traffic'ecord $or the evi%e as a Chole.
Tra77ic$onitorActivit
is Chat %reates an uses Traffic#nap"-ot obHe%ts. 6his is a $airly %onventional a%tivity Cith a 6ableLayout4base ".*
Traffic+onitor cti$it*
5Sxml $er"ion89F.?9 encoding89utf-T9S6 5Table!a*out xmln"Qandroid89-ttpQ44"c-ema".android.com4apk4re"4android9 androidQid89O;id4table9 androidQla*out0widt-89matc-0parent9 androidQla*out0-eig-t89wrap0content96 5Button androidQtext89Take #nap"-ot9 androidQonClick89take#nap"-ot9 46 5Table'ow6 5TextView androidQla*out0column89F9 androidQtext89O"tring4recei$ed9 androidQla*out0gra$it*89rig-t9 androidQtext#iEe89G?"p946 5TextView androidQtext89O"tring4"ent9 androidQla*out0gra$it*89rig-t9 androidQtext#iEe89G?"p946 54Table'ow6 5Table'ow6 5TextView androidQgra$it*89rig-t9 androidQtext89O"tring4late"t9 androidQtext#t*le89bold9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 7-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
5TextView androidQid89O;id4late"t0rx9 androidQgra$it*89rig-t9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 5TextView androidQid89O;id4late"t0tx9 androidQgra$it*89rig-t9 androidQtext#iEe89G?"p946 54Table'ow6 5Table'ow6 5TextView androidQgra$it*89rig-t9 androidQtext89O"tring4pre$iou"9 androidQtext#t*le89bold9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 5TextView androidQid89O;id4pre$iou"0rx9 androidQgra$it*89rig-t9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 5TextView androidQid89O;id4pre$iou"0tx9 androidQgra$it*89rig-t9 androidQtext#iEe89G?"p946 54Table'ow6 5Table'ow6 5TextView androidQgra$it*89rig-t9 androidQtext89O"tring4delta9 androidQtext#t*le89bold9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 5TextView androidQid89O;id4delta0rx9 androidQgra$it*89rig-t9 androidQla*out0margin'ig-t89Odimen4margin0rig-t9 androidQtext#iEe89G?"p946 5TextView androidQid89O;id4delta0tx9 androidQgra$it*89rig-t9 androidQtext#iEe89G?"p946 54Table'ow6 54Table!a*out6
6he a%tivity implementation %onsists o$ three metho s. 6here is your typi%al onCreate() implementation, Chere Ce initialiIe the "., get our han s on the TextView Ci gets $or output, an take the initial snapshot*
O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): late"t0rx8(TextView)find!iewBy%d('.id.late"t0rx): late"t0tx8(TextView)find!iewBy%d('.id.late"t0tx): pre$iou"0rx8(TextView)find!iewBy%d('.id.pre$iou"0rx): pre$iou"0tx8(TextView)find!iewBy%d('.id.pre$iou"0tx): delta0rx8(TextView)find!iewBy%d('.id.delta0rx): delta0tx8(TextView)find!iewBy%d('.id.delta0tx): > takeSnapshot(null):
6he take#nap"-ot() metho %reates a neC Traffic#nap"-ot &hel in a late"t ata member' a$ter moving the last Traffic#nap"-ot to a pre$iou" ata member. .t then up ates the TextView Ci gets $or the late"t ata an , i$ the pre$iou" ata member is not null, also $or the pre$iou" snapshot an the
7(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
i$$eren%e betCeen them. 6his alone is su$$i%ient to up ate the "., but Ce also Cant to log per4".> ata to LogCat*
O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): late"t0rx8(TextView)find!iewBy%d('.id.late"t0rx): late"t0tx8(TextView)find!iewBy%d('.id.late"t0tx): pre$iou"0rx8(TextView)find!iewBy%d('.id.pre$iou"0rx): pre$iou"0tx8(TextView)find!iewBy%d('.id.pre$iou"0tx): delta0rx8(TextView)find!iewBy%d('.id.delta0rx): delta0tx8(TextView)find!iewBy%d('.id.delta0tx): > takeSnapshot(null):
+ne possible problem Cith the snapshot system is that the pro%ess list may %hange betCeen snapshots. +ne simple Cay to a ress this is to only log to LogCat ata Chere the appli%ation8s ".> e<ists in both the pre$iou" an late"t snapshots. )en%e, take#nap"-ot() uses a &a"-#et an retain ll() to etermine Chi%h ".>s e<ist in both snapshots. (or ea%h o$ those, Ce %all an emit!og() metho to re%or the ata to an rra*!i"t, Chi%h is then sorte an umpe to LogCat. 6he emit!og() metho buil s up a line Cith the pa%kage name an ban Ci th %onsumption in$ormation, assuming that there is ban Ci th to report &i.e., Ce have a value other than -F'*
pri$ate $oid emitLog(C-ar#e)uence nameD Traffic'ecord late"t0recD Traffic'ecord pre$iou"0recD rra*!i"t5#tring6 row") 7 if (late"t0rec.rx6-F VV late"t0rec.tx6-F) 7 #tringBuilder buf8new StringBuilder(name): buf.append(989): buf.append(#tring.valueOf(late"t0rec.rx)): buf.append(9 recei$ed9): if (pre$iou"0recW8null) 7 buf.append(9 (delta89): buf.append(#tring.valueOf(late"t0rec.rx-pre$iou"0rec.rx)): buf.append(9)9): > buf.append(9D 9): 74
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
buf.append(#tring.valueOf(late"t0rec.tx)): buf.append(9 "ent9): if (pre$iou"0recW8null) 7 buf.append(9 (delta89): buf.append(#tring.valueOf(late"t0rec.tx-pre$iou"0rec.tx)): buf.append(9)9): > > > row".add(buf.toString()):
#in%e the lines %reate by emit!og() start Cith the pa%kage name, an sin%e Ce are sorting those be$ore umping them to LogCat, they appear in LogCat in sorte or er by pa%kage name.
1sing Tra77ic$onitor
Running the a%tivity gives you the initial re%eive bytes'* an sent %ounts &in
7'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$igure -(0 The TrafficAonitor sample application= after Take "napshot +as clicke#
Also, LogCat Cill shoC hoC mu%h Cas use by various apps*
?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.amblingbook".bookpla*erpro8TT? recei$ed (delta8?)D JG?? "ent (delta8?) ?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.android.brow"er8FK?=XG=F recei$ed (delta8?)D GJUXT=U "ent (delta8?) ?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.android.pro$ider".download"8GUTT==YK recei$ed (delta8?)D KFGY "ent (delta8?) ?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.android.pro$ider".telep-on*8GJGT recei$ed (delta8?)D =KFG "ent (delta8?) ?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.android.$ending8JGUFTJK recei$ed (delta8?)D GY?YGY "ent (delta8?) ?T-FX F=Q?XQF?.FGTQ ,/BMG4Traffic+onitor(F?GTJ)Q com.coair.mobile.android8TTU=GX recei$ed (delta8?)D TFJYY "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.common"ware.android.brow"erF8GYGXXJ recei$ed (delta8?)D UGTY "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.dropbox.android8YFTKTJJ recei$ed (delta8?)D =GKT "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.e$ernote8J=UFJKT recei$ed (delta8?)D U=GFUT "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q
75
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
com.google.android.app".genie.geniewidget8JXTTFY recei$ed (delta8?)D FUUUX "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.app".google$oice8F?JGXX recei$ed (delta8?)D JXXXK "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.app".map"8GT==?TGK recei$ed (delta8?)D FGJ?TYU "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.backup8XFJG? recei$ed (delta8?)D =K?=F "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.gm8F?KFX?T= recei$ed (delta8?)D F==GTT?J "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.google)uick"earc-box8JUTFU recei$ed (delta8?)D FGXX= "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android."*ncadapter".contact"8FKXXKK? recei$ed (delta8?)D UF=TKJ "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.$oice"earc-8YUK=T recei$ed (delta8?)D FGFK?T "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.google.android.*outube8JFGT recei$ed (delta8?)D GUKG "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.-owca"t.android.app8GGX?=?U recei$ed (delta8?)D GYUGU "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.remembert-emilk.+obile'T+8YTJYY?X recei$ed (delta8?)D GK?GK?= "ent (delta8?) ?T-FX F=Q?XQF?.FJGQ ,/BMG4Traffic+onitor(F?GTJ)Q com.tripit8F?K=KK recei$ed (delta8?)D X??Y? "ent (delta8?)
In Production
.$ your app is a ban Ci th monitor, the nee to use Traffic#tat" is obvious. )oCever, even i$ your app oes something else, you may Cish to use Traffic#tat" to un erstan Chat is going on in terms o$ .nternet a%%ess Cithin your app or on the evi%e as a Chole.
76
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
(or e<ample, you might Cant to %onsi er ban Ci th %onsumption to be a metri% Corthy o$ in%lu ing in the rest o$ the Kanalyti%sK you generate $rom your app. .$ you are using servi%es like (lurry to monitor Chi%h a%tivities get use an so on, you might %onsi er also logging the amount o$ ban Ci th your appli%ation %onsumes. 6his not only gives you mu%h more Kreal Corl K ata than you Cill be able to %olle%t on your oCn, but it may give you i eas o$ hoC users are using your appli%ation beyon Chat the rest o$ your metri%s are reporting. Another possibility Coul be to in%lu e your app8s ban Ci th %onsumption in error logs reporte via libraries like ACRA. @ust as evi%e parti%ulars %an help i enti$y %ertain bug report patterns, perhaps %ertain %rashes o$ your app only o%%ur Chen users are using a lot o$ ban Ci th in your app, or using a lot o$ ban Ci th elseChere an perhaps %hoking your oCn app8s .nternet a%%ess. 6he %hapter on ban Ci th mitigation strategies Cill also %over a number o$ uses o$ Traffic#tat" $or real4time a Hustment o$ your appli%ation logi%.
During Testing
?ou might %onsi er a ing Traffic#tat"4base ban Ci th logging $or your appli%ation in your test suites. While in ivi ual tests may or may not give you use$ul ata, you may be able to raC tren lines over time to see i$ you are %onsuming more or less ban Ci th than you use to. 6ake %are to $a%tor in that you may have %hange the tests, in a ition to %hanging the %o e that is being teste . (rom a @"nit4base unit test suite, measuring ban Ci th %onsumption is not espe%ially har . ?ou %an bake it into the "etMp() an tear,own() metho s o$ your test %ases, either via inheritan%e or %omposition, an log the output to a $ile or LogCat. (rom an e<ternal test engine, like monkeyrunner or 0ative>river, re%or ing ban Ci th usage is more tri%ky, be%ause your test %o e is not running on the evi%e or emulator. ?ou may have to in%lu e a
77
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
in your pro u%tion %o e that Cill log ban Ci th usage an trigger that %o e via the am broadca"t shell %omman .
Broadca"t'ecei$er
78
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER =
6he $irst step toCar s a ressing ban Ci th %on%erns is to get a better pi%ture o$ hoC mu%h ban Ci th you are a%tually %onsuming, Chen, an un er Chat %on itions. +nly then Cill you be able to etermine Chere your e$$orts nee to be applie an Chether those e$$orts are a%tually giving you positive results. 6his %hapter Cill e<amine a han $ul o$ Cays you %an etermine hoC mu%h ban Ci th you are really using in your appli%ation.
@n%,evice Aeasurement
Many times, you are best serve %onsumption right on the evi%e itsel$*
6his is your only option $or gathering ban Ci th metri%s $rom %opies o$ your app in en users8 han s, unless they invite you to their home or o$$i%e an have you sni$$ on their personal netCork, Chi%h seems unlikely 6his is your only option $or gathering ban Ci th metri%s Chen you are using mobile ata plans &e.g., B9' instea o$ Wi(i, sin%e you probably o not %ontrol the Cireless tele%ommuni%ations in$rastru%ture in your area 6his is your simplest option $or tying ban Ci th metri%s to events Cithin your app or o%%urring on the evi%e
79
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6his is your only option $or using ban Ci th metri%s to a Hust your appli%ation behavior in real time, in a ition to using the metri%s to learn hoC best to a Hust your %o e in $uture up ates to the app
)en%e, in a ition to perhaps other o$$4 evi%e te%hni=ues, you really shoul %onsi er one o$ the on4 evi%e approa%hes outline in the $olloCing se%tions.
!er4".> tra$$i% ata may or may not be available, epen ing upon the evi%e
0etCork 6ra$$i% >etail &v. 1.B' Corks, but oes not %onsi er that ban Ci th is only reporte per ".>, not per appli%ation. As a result, it reports the same tra$$i% multiple times, one $or ea%h appli%ation sharing a ".>. 6ra$$i% Monitor &v. 2.-.2' a vertises itsel$ as an appli%ation, but oes not put an i%on in the laun%her $or it, $or%ing you to install an app
8:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Ci get instea in or er to get to the a%tual appli%ation. While it reports evi%e4level ban Ci th, an it has a task manager, the task list oes not report ban Ci th $or those tasks.
/an Ci th Monitor &v. 1.0.5' Corks an is perhaps in%rementally easier to use than the other alternatives, though its toute bar %hart o$ ban Ci th %onsumption la%ks any in i%ator o$ the value o$ the ? a<is.
6here are %ertainly others on the Market to ay an more Cill shoC up over time. (or your oCn use, these sorts o$ apps may be very help$ul. )oCever, sin%e you %ontrol nothing over Chat is %olle%te an hoC &an , in the %ase o$ some, even Chen it is %olle%te ', it may be i$$i%ult $or you to get a soli grasp on Chere your %o e is %onsuming ban Ci th this Cay. 6here are also various apps that provi e more in the Cay o$ pa%ket4sni$$ing %apability. )oCever, these re=uire you to root your phone an run the app Cith root privileges.
@ff%,evice Aeasurement
6he biggest limitation o$ Traffic#tat" is that it only gives you gross metri%s* numbers o$ bytes, pa%kets, an so on. #ometimes, that is not enough to help you un erstan Chy those bytes, pa%kets, an so on are a%tually being sent or re%eive . #ometimes, it Coul be ni%e to un erstan the tra$$i% in more etail, $rom the ports an .! a resses to perhaps the a%tual ata being transmitte . (or obvious se%urity reasons, this is not something an or inary An roi #>F appli%ation %an o. )oCever, there are te%hni=ues $or a%%omplishing this, mostly $or use over Wi(i in your oCn home or o$$i%e netCork. #ome o$ these are outline in the $olloCing se%tions.
Wireshar*
Wireshark, $ormerly knoCn as Athereal, is perhaps the Corl 8s lea ing open sour%e netCork tra$$i% analyIer an pa%ket inspe%tor. "sing it, you %an learn in great etail Chat is going on Cith your lo%al netCork. An , An roi
8-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
provi es a itional options $or you to leverage Wireshark to make sense o$ appli%ation behavior. Wireshark is available $or Linu<, +# P, an Win oCs. 6here is a lightly4 o%umente -tcpdump sCit%h available on the An roi emulator. .$ you laun%h the emulator $rom the %omman line Cith that sCit%h &plus -a$d to i enti$y the A,> $ile you Cant to use', all netCork a%%ess is umpe to your spe%i$ie log $ile. ?ou %an then loa that ata into Wireshark $or analysis, via (ileX+pen $rom the main menu. (or e<ample, here is a s%reenshot o$ Wireshark e<amining ata $rom su%h an emulator ump $ile, in Chi%h the emulator Cas use to %on u%t a 9oogle sear%h*
6his s%reenshot shoCs an )66! re=uest in the highlighte line in the list, Cith the he< an A#C.. %ontents o$ the re=uest shoCn in the bottom pane. .n terms o$ using Wireshark to monitor tra$$i% $rom a%tual har Care, that is in ubitably possible. )oCever, Wi(i pa%ket %olle%tion is a tri%ky pro%ess Cith Wireshark, being very epen ent upon operating system an possibly even the Wi(i a apter %hipset. ?ou also get mu%h loCer4level in$ormation, making it a bit more %hallenging to $igure out Chat is going on. Attempting
8(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
to %over all o$ this is Cell beyon the s%ope o$ this book an the author8s Wireshark e<pertise.
.etwor*ing Hardware
#ophisti%ate $ireCalls sometimes have pa%ket tra%ingMsni$$ing %apability. .n this %ase, Ksophisti%ate K oes not ne%essarily mean Ke<pensiveK, as open sour%e routerM$ireCall istributions, like +penWrt, %an be use $or this sort o$ Cork. .n this %ase, the router %aptures the pa%kets an , in many %ases, routes them to Wireshark $or analysis. #ome might o$$er on4boar analysis &e.g., Web inter$a%e to pa%ket %apture logs'. 6his is parti%ularly use$ul on a Win oCs Cireless netCork. Wireshark has limits, impose by Win oCs, that %ause some problems Chen trying to %apture Wi(i pa%kets. /y o$$loa ing the pa%ket %apture to netCorking har Care, those limits %an be bypasse .
84
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER ?
9iven that you are %olle%ting metri%s about ban Ci th %onsumption, you %an noC start to etermine Cays to re u%e that %onsumption. ?ou may be able to permanently re u%e that %onsumption &at least on a per4operation basis'. ?ou may be able to shunt that %onsumption to times or netCorks that the user pre$ers. 6his %hapter revieCs a variety o$ means o$ a%%omplishing these en s.
Ban#+i#th "avings
6he best Cay to re u%e ban Ci th %onsumption is to %onsume less ban Ci th. &in other breaking neCs, Cater is Cet' .n re%ent years, evelopers have been able to be relatively pro$ligate in their use o$ ban Ci th, pretty mu%h assuming everyone has an unlimite high4 spee .nternet %onne%tion to their esktop or notebook an the esktop or Web apps in use on them. )oCever, those o$ us Cho live through the early ays o$ the .nternet remember $ar too Cell the %hallenges that ial4up mo em a%%ounts Coul present to users &an perhaps ourselves'. Aven to ay, as Web apps try to Ks%ale to the Moon an ba%kK, ban Ci th savings
85
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
be%omes important not so mu%h $or the en user, but $or the Web app host, so its oCn ban Ci th is not sCampe as its user base groCs. (ortunately, Ci esprea evelopment problems ten to bring rise to a variety o$ solutions J a variant on the Kmany eyes make bugs shalloCK %ollaborative evelopment phenomenon. )en%e, there are any number o$ trie 4an 4true te%hni=ues $or re u%ing ban Ci th %onsumption that have ha use in Web apps an elseChere. Many o$ these are vali $or native An roi apps as Cell, an a $eC o$ them are pro$ile in the $olloCing se%tions.
67ip Encoding
/y e$ault, )66! re=uests an response are un%ompresse . )oCever, you %an enable 9Rip en%o ing an thereby re=uest that the server %ompress its response, Chi%h is then e%ompresse on the %lient. 6his tra es o$$ C!" $or ban Ci th savings an there$ore nee s to be one Hu i%iously. Anabling 9Rip %ompression is a tCo4step pro%ess* 1. A ing the ccept-/ncodingQ gEip hea er to the )66! re=uest response Cas %ompresse an , i$ so,
/ear in min that the Web server may or may not honor your 9Rip re=uest, $or Chatever reason &e.g., response is too small to make it CorthChile'. (or e<ample, using the )ttpClient library in An roi , you %oul a hea er on the re=uest*
86
the
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
&ttpGet get8new ,ttp-et(url): get.add,eader(9 ccept-/ncoding9D 9gEip9): 44 re"t of configuration -ereD if an* 44 execute t-e re)ue"t gi$en an &ttpClient object named client &ttp'e"pon"e re"pon"e8client.e"ecute(get):
6hen, you %an %he%k the response an get a vali %nput#tream $or either the %ompresse or the not4%ompresse %ases*
44 a""ume" &ttp'e"pon"e re"pon"e a" in abo$e code "nippet %nput#tream "tream8re"pon"e.get$ntity().get ontent(): &eader enc8re"pon"e.get.irst,eader(9Content-/ncoding9): if (encW8null ZZ enc.get!alue().e(uals%gnore ase(9gEip9)) 7 "tream8new -/%#%nputStream("tream): > 44 at t-i" pointD "tream will work for eit-er encoding
A=uivalents e<ist $or using &ttpMrlConnection, i$ you pre$er to use that )66! A!. in An roi .
f!Modified!Since / f!/one!Match
+$ %ourse, avoi ing a oCnloa o$$ers near4100Q %ompression. .$ you are %a%hing ata, you %an take a vantage o$ )66! hea ers to try to skip oCnloa s that are the same %ontent as Chat you alrea y have, spe%i$i%ally %f-+odified-#ince an %f-2one-+atc-. An )66! response %an %ontain either a !a"t-+odified hea er or an /Tag hea er. 6he $ormer Cill %ontain a timestamp an the latter Cill %ontain some opa=ue value. ?ou %an store this in$ormation Cith the %a%he %opy o$ the ata &e.g., in a atabase table'. Later on, Chen you Cant to ensure you have the latest version o$ that $ile, your )66! 9A6 re=uest %an in%lu e an %f-+odified-#ince hea er &Cith the %a%he Last4Mo i$ie value' or an %f2one-+atc- hea er &Cith the %a%he /Tag value'. .n either %ase, the server shoul return either a J?= response, in i%ating that your %a%he %opy is up to ate, or a G?? response Cith the up ate ata. As a result, you avoi the
87
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
oCnloa entirely &other than )66! hea ers' Chen you o not nee the up ate ata. (or e<ample, using )ttpClient, you %an %he%k $or the e<isten%e o$ an /Tag hea er in an )66! response*
&ttpGet get8new ,ttp-et(url): 44 execute t-e re)ue"t gi$en an &ttpClient object named client &ttp'e"pon"e re"pon"e8client.e"ecute(get): &eader etag8re"pon"e.get.irst,eader(9/Tag9): if (etagW8null) 7 44 cac-e t-i" > 44 proce"" t-e download
44 execute t-e re)ue"t gi$en an &ttpClient object named client &ttp'e"pon"e re"pon"e8client.e"ecute(get): int "c8re"pon"e.getStatusLine().getStatus ode(): if ("cW8&ttp#tatu".#C023T0+3,%@%/,) 7 44 cac-e in$alidD "o proce"" t-e download andD per-ap"D grab fre"- /Tag >
"sing !a"t-+odified an %f-+odified-#ince is mostly a matter o$ sCit%hing hea ers. An , on%e again, there are e=uivalent Cays to use these hea ers Cith &ttpMrlConnection.
,inar" Pa"loads
While PML an @#+0 are relatively easy $or humans to rea , that very %hara%teristi% means they ten to be bloate in terms o$ ban Ci th %onsumption. 6here are a variety o$ tools, su%h as 9oogle8s !roto%ol /u$$ers an Apa%he8s 6hri$t, that alloC you to %reate an parse binary ata
88
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
stru%tures in a %ross4plat$orm $ashion. 6hese might alloC you to trans$er the same ata that you Coul in PML or @#+0 in less spa%e. As a si e bene$it, parsing the binary responses is likely to be $aster than parsing PML or @#+0. /oth o$ these tools involve the %reation o$ an .>L4type $ile to es%ribe the ata stru%ture, then o$$er %o e generators to %reate @ava %lasses &or e=uivalents $or other languages' that %an rea an Crite su%h stru%tures, %onverting them into plat$orm4neutral on4the4Cire byte arrays as nee e .
Minification
.$ you are loa ing @ava#%ript or C## into a .ebView, you shoul %onsi er stan ar tri%ks $or %ompressing those s%ripts, %olle%tively re$erre to as Kmini$i%ationK. 6hese te%hni=ues eliminate all unne%essary Chitespa%e an su%h $rom the $iles, rename variables to be short, an otherCise %reate a synta%ti%ally4i enti%al s%ript that takes up a $ra%tion o$ the spa%e. 6here are servi%es like bo<.Hs that %an even aggregate several s%ripts into one $ile an mini$y them, to $urther re u%e )66! overhea .
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
(or e<ample, Remember the Milk J a task management Web site an set o$ mobile apps J uses C2>M to alert the evi%e o$ task %hanges you make through the Web site. Rather than the Remember the Milk app having to %onstantly poll to see i$ tasks Cere a e , %hange , or elete , the app simply Caits $or C2>M events. ?ou %oul %reate your oCn push me%hanism, perhaps using a Web#o%ket or Comet4style long4poll te%hni=ue. 6he oCnsi e is that you Cill nee a servi%e in memory all o$ the time to manage the so%ket an threa that monitors it. .$ you only nee this Chile your servi%e is in memory $or other reasons, that is $ine. )oCever, keeping a servi%e in memory 2-<2 has its oCn set o$ issues, not the least o$ Chi%h is that users Cill ten to sma%k it oCn using a Ktask killerK or the Manage #ervi%es s%reen in the #ettings app. C2>M itsel$ is %overe in greater A van%e An roi >evelopment. etail in 6he /usy Co er8s 9ui e to
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
the album %overs, this option might still be available to you i$ you %an run your oCn server $or the purposes o$ generating su%h thumbnails. ?ou %an see a similar e$$e%t Cith the map tiles in 9oogle Maps. When Iooming out, the e<isting map tiles are s%ale oCn, Cith pla%ehol ers &the gri lines' $or the remaining spots, until the tiles $or those spots are oCnloa e . When Iooming in, the e<isting map tiles are s%ale up Cith a slight blurring e$$e%t, to give the user some imme iate $ee ba%k Chile the $ull set o$ more4 etaile tiles is oCnloa e . An , i$ the user pans, you on%e again get pla%ehol ers Chile the tiles $or the neCly un%overe areas are oCnloa e . .n this $ashion, 9oogle Maps is able to minimiIe ban Ci th %onsumption by giving users partial results imme iately an ba%k4$illing in the $inal results only Chen nee e . 6his same sort o$ approa%h may be use$ul Cith your oCn imagery.
Colla8orative :andwidth
(or some %ommon servi%es, perhaps sharing is the best option to re u%e ban Ci th usage. (or e<ample, %onsi er 6Citter. .t is entirely possible that a user might have multiple appli%ations all polling an oCnloa ing the user8s timeline*
A regular 6Citter app that the user employs $or normal stu$$ A separate 6Citter app Ci get, be%ause the other 6Citter apps on the evi%e either la%k an app Ci get or the user oes not like it ?et another appli%ation that uses 6Citter as one o$ several ata sour%es &e.g., monitoring $or re$eren%es to %ertain keyCor s, su%h as a %ompany name, a%ross multiple so%ial netCorks'
.n an i eal Corl , all o$ these apps Coul use one %ommon engine that han les %olle%ting the tCeets an making them available J se%urely J to the other appli%ations. 6his Coul ramati%ally %ut ban Ci th by eliminating re un ant polling.
9-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ your ata sour%e is use by other appli%ations, %onsi er rea%hing out to those evelopers an %reating a %ommon engine, perhaps using a Content(ro$ider $or ata sharing, an %ntent#er$ice or syn% provi er $or %olle%ting the ata, plus %ommon a%tivities $or pre$eren%es. >istribute the %o e to all o$ the evelopment teams as an An roi library proHe%t. #hip these %omponents isable in your mani$est, enabling them i$ you %annot $in another implementation on the evi%e, in i%ating that you are the only one o$ this Kappli%ation $amilyK installe . .$ you o $in another implementation, use that one instea o$ your oCn. 6here are %ertainly issues to be ealt Cith here &e.g., Chat i$ the user uninstalls the app that the others are epen ing upon', but it is Corth %onsi ering $or share evelopment %osts as Cell as share ban Ci th.
Ban#+i#th "haping
#ometimes, you have no ability to re u%e the ban Ci th itsel$. !erhaps you o not %ontrol both en s o$ the %ommuni%ations pipeline. !erhaps the ata you are trying to e<%hange is alrea y %ompresse &e.g., oCnloa ing an M!- vi eo'. !erhaps some o$ the te%hni=ues in the pre%e ing se%tion Cere unavailable to you &e.g., %annot route ata through thir 4party servers like 9oogle8s $or C2>M'. 6here still may be Cays $or you to help your users, by shaping your ban Ci th use. Rather than Hust blin ly oing Chatever you Cant Chenever you Cant, you learn Chat the user Cants an Chat other applications Cant an tailor your ban Ci th use on the $ly to mat%h those nee s. 6he $olloCing se%tions outline some Cays o$ a%hieving this.
Driven 8 Pre7erences
.$ you are %onsuming enough ban Ci th that this %hapter is relevant to you, you probably are %onsuming enough ban Ci th that you shoul be asking the user hoC best to %onsume that ban Ci th. A$ter all, they are the one paying the pri%e J in time as Cell as money J $or that %onsumption.
9(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he $olloCing se%tions present some possible strategies $or pre$eren%e4 base ban Ci th shaping.
,udgets
+ne strategy is $or the user to give you a bu get &e.g., 20M/M ay' an $or you to sti%k Cithin that bu get. Colle%ting the bu get is $airly easy J Hust use #-ared(reference". Aither use a !i"t(reference Cith likely bu get value or an /ditText(reference an a bit o$ vali ation $or a $ree4$orm bu get amount. 0e<t, you Cill nee to have some i ea hoC mu%h ban Ci th any given netCork operation Cill %onsume. (or some things, this might be an estimate base on your e<periments as a eveloper, or perhaps it is base on histori%al averages $or this user an type o$ operation. (or e<ample, a Kpo %at%herK &$ee rea er esigne to oCnloa po %ast episo es' shoul have some i ea hoC big a given R## or Atom $ee oCnloa shoul be. .n some %ases, it might be CorthChile to get a better estimate J $or e<ample, the po %at%her might use an )66! &/ , re=uest to etermine the siIe o$ the M!B or +99 $ile be$ore e%i ing Chether to oCnloa it. 6hen, you nee to be keeping tra%k o$ your bu get. 6his %oul be a simple $lat $ile Cith the initial Traffic#tat" ban Ci th values $or your pro%ess. Re4 initialiIe that $ile on the $irst netCork operation o$ the ay &or Chatever perio you %hose $or your bu get'. /e$ore oing another netCork operation, %ompare the %urrent Traffic#tat" values Cith the initial ones an see hoC %lose you are to the bu get. .$ the neC netCork operation Cill e<%ee the bu get, skip the operation, perhaps putting it in a Cork =ueue to per$orm in the ne<t bu get. ?ou might even hol a reserve $or %ertain types o$ operations. (or e<ample, the po %at%her might ensure there is at least 10Q o$ the bu get available $or oCnloa ing the $ee s, even i$ it means putting a po %ast on the =ueue $or oCnloa tomorroC. 6hat Cay, you %an present to the user the latest po %ast in$ormation, Cith i%ons in i%ating Chi%h are oCnloa e an Chi%h are =ueue $or oCnloa J the user might be able to then re=uest to overri e the bu get an oCnloa something on eman .
94
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
(or evi%es that la%k per4".> Traffic#tat" support, you Cill have to K$ake itK a bit. "se your oCn %al%ulations o$ hoC mu%h ban Ci th ea%h operation %onsumes an tra%k that in$ormation, even i$ you Cin up missing out on some bytes here or there.
Connectivit"
.$ the user might not %are hoC mu%h ban Ci th you %onsume, so long as it is un4metere ban Ci th, you might in%lu e a C-eckBox(reference to in i%ate i$ large netCork operations shoul be limite to Wi(i an avoi mobile ata. ?ou %oul then use Connecti$it*+anager an get cti$e2etwork%nfo() to see Chat %onne%tion you have be$ore per$orming a netCork operation. .$ it is a ba%kgroun operation &e.g., the po %at%her %he%king $or neC po %asts every hour', i$ the netCork is not the esire one, you %an skip the operation or put it on a Cork =ueue $or re4trying later. .$ it is a $oregroun operation &e.g., the user %li%ke a Kre$reshK menu %hoi%e', you %oul pop up a %on$irmation lert,ialog to Carn the user that they are on mobile ata J perhaps this time they are intereste in oing the operation anyCay. Another approa%h $or han ling the ba%kgroun operations is to register a Broadca"t'ecei$er $or the C322/CT%V%TN0 CT%32 broa %ast & e$ine on Connecti$it*+anager'. .$ the %onne%tivity sCit%hes to mobile ata, %an%el your outstan ing larm+anager alarmsG i$ %onne%tivity sCit%hes to Wi(i, re4 enable those alarms. +$ %ourse, you shoul also %onsi er monitoring the ba%kgroun ata setting J the global #ettings %he%kbo< in i%ating Chether ba%kgroun netCork operations are alloCe . +n Connecti$it*+anager, getBackground,ata#etting() tells you the state o$ this %he%kbo<, an CT%320B CAG'3M2,0, T 0#/TT%2G0C& 2G/, alloCs you to set up a Broadca"t'ecei$er to Cat%h $or %hanges in its state.
9'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Windows
.$ your user is less %on%erne about the ban Ci th or the netCork, but oes %are about the time o$ ay &e.g., oes not Cant your appli%ation %onsuming signi$i%ant ban Ci th Chen they might be getting a ,+.! %all', you %oul o$$er pre$eren%es $or that as Cell. Cook up a Time(reference &you %an $in an e<ample o$ one in the sour%e $or ndroid Programming Tutorials' an use that to %olle%t start an stop times $or the high4ban Ci th Cin oC. 6hen, set up alarms Cith larm+anager $or those points in time. 6he alarm $or the start time o$ the Cin oC sets up a thir alarm Cith your regular polling interval. 6he alarm $or the stop time o$ the Cin oC %an%els the polling interval alarm.
95
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
A ing a one4o$$ alarm using set&' on larm+anager to give you %ontrol again in a minute, Cith the %urrent tra$$i% ata pa%kage as an e<tra on the .ntent, so you %an make a e%ision a$ter a bigger sample siIe o$ ban Ci th %onsumption, or A ing an entry in a persistent Cork =ueue, so you knoC later on to try again i$ ban Ci th %ontention has improve
?ou %oul try to get more sophisti%ate , by using cti$it*+anager an the per4".> values $rom Traffic#tat" to see i$ it is a $oregroun appli%ation that is the one %onsuming the ban Ci th. .t is un%lear hoC reliable this Cill be, both in etermining Cho is %onsuming the ban Ci th &again, per4".> tra$$i% is not available on many evi%es' an in avoi user angst. .t may be simpler Hust to assume the Corst an si e4step your .M+ until the other apps have =uiete oCn.
96
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER @
RAM. >evelopers noCa ays are use to having lots o$ it, an a virtual ma%hine %apable o$ using as mu%h o$ it as e<ists &an more, given sCap $iles an page $iles'. K9raybear sK J like the author o$ this book J istin%tly remember a time Chen Ce ha 15F/ o$ RAM an Cere happy $or it. #u%h graybear s Coul also appre%iate it i$ you Coul get o$$ their respe%tive laCns. An roi %omes someChere in the mi le. We have or ers o$ magnitu e more RAM than, say, the 6R#430 Mo el .... We o not have nearly as mu%h RAM as oes the mo ern notebook, let alone a Web server. As su%h, it is easy to run out o$ RAM i$ you o not take su$$i%ient %are. 6his part o$ the book e<amines memory4relate issues. 6hese are not to be %on$use Cith any memory4relate issues inherent to graybear s.
.ou Are in a
eap of Trouble
When Ce think o$ KmemoryK an @ava4style programming, the primary $orm o$ memory is the heap. 6he heap hol s all o$ our @ava obHe%ts J $rom an cti$it* to a Ci get to a #tring.
99
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6ra itional @ava appli%ations have an initial heap siIe etermine by the virtual ma%hine, possibly %on$igure via %omman 4line options Chen the program Cas run. 6ra itional @ava appli%ations %an also re=uest a itional memory $rom the +#, up to some ma<imum, also %on$igurable. An roi appli%ations have the same basi% stru%ture, Cith very limite %on$igurability an mu%h loCer ma<imums than you might e<pe%t. +l er An roi evi%es, parti%ularly those Cith ),9A s%reens like the 64 Mobile 91, ten to have a ma<imum o$ 15M/ o$ heap spa%e. 0eCer An roi phones Cith higher4resolution s%reens might have 2-M/ &Motorola >R+.>' or B2M/ &0e<us +ne' o$ heap spa%e. 6ablets might have -3M/ o$ heap spa%e. 6his heap limit %an be problemati%. (or e<ample, ea%h Ci get or layout manager instan%e takes aroun 1F/ o$ heap spa%e. 6his is Chy dapterView provi es the hooks $or vieC re%y%ling J Ce %annot have a !i"tView Cith literally thousan s o$ roC vieCs Cithout potentially running out o$ heap. A!. Level 11 noC supports appli%ations re=uesting a Klarge heapK. 6his is $or appli%ations that spe%i$i%ally nee tons o$ RAM, su%h as an image e itor to be use on a tablet. 6his is not $or appli%ations that run out o$ heap ue to leaks or sloppy programming. /ear in min that users Cill $eel e$$e%ts $rom large4heap appli%ations, in that their other appli%ations Cill be ki%ke out o$ memory more =ui%kly, possibly irritating them. Also, garbage %olle%tion on large4heap appli%ations runs more sloCly, %onsuming more C!" time. 6o enable the large heap, a androidQlarge&eap89true9 to the 5application6 element o$ your mani$est. ?ou %an %all get!arge+emor*Cla""() on cti$it*+anager to learn hoC large your Klarge heapK a%tually is.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
the $a%t that most image $ormats, like @!A9 an !09, are %ompresse , an An roi nee s the un%ompresse image to knoC Chat to raC the $a%t that ea%h pi<el may take up several bytes &2 bytes per pi<el $or 'GB0XYX, B bytes per pi<el $or 'GB0TTT' Chat matters is the resolution o$ the bitmap in its original $orm, as mu%h &i$ not more' than the siIe in Chi%h it Cill be ren ere J an 300<-30 image isplaye in an 30<-3 %mageView still %onsumes 300<-30 Corth o$ pi<el ata there are an aC$ul lot o$ pi<els in an image J 300 times -30 is B3-,000
An roi %an make some optimiIations, su%h as only loa ing in one %opy o$ a >raCable resour%e no matter hoC many times you ren er it. )oCever, in general, ea%h bitmap you loa takes a e%ent siIe %hunk o$ your heap, an too many bitmaps means not enough heap. .t is not unhear o$ $or an appli%ation to have more than hal$ o$ its heap spa%e tie up in various bitmap images. Compoun ing this problem is that bitmap memory, be$ore )oney%omb, Cas i$$i%ult to measure. .n the a%tual >alvik heap, a /itmap Coul nee T30 bytes or so, regar less o$ image siIe. 6he a%tual pi<el ata Cas hel in Knative heapK, the spa%e that a CMCSS program Coul obtain via %alls to malloc(). While this spa%e Cas still subtra%te $rom the available heap spa%e, many iagnosti% programs J su%h as MA6, to be e<amine in the ne<t %hapter J Cill not knoC about it. An roi B.0 &%o e4name K)oney%ombK' move the pi<el ata into the >alvik heap, Chi%h Cill improve our ability to $in an eal Cith memory leaks or overuse o$ bitmaps. 6his part o$ the book Cill %over te%hni=ues to i enti$y Chere you might be leaking memory an Chat is %onsuming all o$ your heap spa%e i$ you are running out o$ it. We Cill also e<amine Cays to avoi su%h leaks an be more e$$i%ient in your memory %onsumption, parti%ularly Cith bitmaps.
-:-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
-:(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 1A
6he A%lipse Memory AnalyIer &MA6' is your O1 tool $or i enti$ying memory leaks an the %ulprits behin running out o$ heap spa%e. !arti%ularly Chen use Cith )oney%omb or neCer versions o$ An roi , MA6 %an i enti$y*
Who are the maHor sour%es o$ memory %onsumption, both ire%tly &e.g., bitmaps' or in ire%tly &e.g., leake a%tivities hol ing onto lots o$ Ci gets' What is keeping obHe%ts in memory une<pe%te ly, e$ying stan ar garbage %olle%tion J the Cay that you leak memory in a manage runtime environment like >alvik
6his %hapter Cill i enti$y hoC to %olle%t heap ata $or use Cith MA6 an hoC to use MA6 to make sense o$ Chat the heap is trying to tell us about Chat is going on insi e o$ your app.
"etting /p AAT
MA6 is an o$$i%ial A%lipse proHe%t, hoste on the A%lipse Web site. .t %omes in tCo $lavors*
A plug4in $or A%lipse itsel$, provi ing a neC KMemory AnalysisK perspe%tive an relate tools A stan alone version, running in the A%lipse RC! $rameCork
-:4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
#ome evelopers may pre$er the stan alone version, be%ause they run into problems Chen their A%lipse Corkspa%es have too many plugins. #ome evelopers may pre$er the integrate version, be%ause tCo A%lipse4base apps Coul %onsume too mu%h RAM. With MA6, you have your %hoi%e. 6here is a tra itional oCnloa link to get the stan alone e ition. As Cith other A%lipse plug4ins, you Cill nee to a the MA6 up ate site to A%lipse J $or e<ample, in A%lipse 9alileo*
Choose )elpX.nstall 0eC #o$tCare... $rom the main menu Cli%k the A ... button in the upper4right %orner o$ the ialog, $ill in as the Lo%ation an Chatever name you Cant, then %li%k +F
-ttpQ44download.eclip"e.org4mat4F.F4update-"ite4
Choose Memory AnalyIer $or A%lipse .>A an %omplete the rest o$ the neC4so$tCare CiIar
Getting
eap ,umps
6he $irst step to analyIing Chat is in your heap is to a%tually get your han s on Chat is in your heap. 6his is re$erre to as %reating a Kheap umpK J Chat amounts to a log $ile %ontaining all your obHe%ts an Cho points to Chat. 6here are multiple Cays o$ obtaining a heap ump, epen ing on your tools an use %ases. 0ote that you Cill $in some blog post an the like in i%ating you %an %reate a heap ump via the adb "-ell kill %omman , but this has been isable in neCer versions o$ An roi .
"ro% DD$#
?ou %an get a heap ump any time you Cant $rom >>M#, using either the >>M# perspe%tive or the stan alone >>M# utility.
-:'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.n the evi%e4an 4pro%ess tree &the >evi%es tool in A%lipse', you Cill $in a toolbar button that looks like a hal$4empty %an Cith a oCnCar 4pointing arroC*
Cli%king this J a$ter %hoosing your esire pro%esss J >>M# Cill %reate a heap ump $or you. )oCever, the pro%ess varies at this point, epen ing on Chether you are using the >>M# perspe%tive in A%lipse or stan alone >>M#.
DDMS Perspective
+n%e you %li%k the toolbar button $or the heap ump, >>M# Cill %reate the ump $or you, in a $ile generate in your evelopment ma%hine8s temporary4$iles ire%tory &e.g., 4tmp'. .$ you Cish to save this ump $or some reason, you Cill Cant to rename it an move it to some other lo%ation.
Standalone DDMS
+n%e you %li%k the toolbar button $or the heap ump, >>M# Cill %reate the ump $or you, in a $ile %hosen by you via your plat$orm8s stan ar $ile4save ialog. 6hen, hoCever, you Cill nee to run the -prof-con$ utility, $rom the tool"4 ire%tory o$ your #>F, to %onvert the heap ump into the $ormat that MA6 Cill use. 6his is automati% i$ you use the >>M# perspe%tive in A%lipse.
-:5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
"ro% Code
Another possibility is to trigger the heap ump yoursel$ $rom %o e. 6he dump&prof,ata() stati% metho on the ,ebug %lass &in the android.o" pa%kage' Cill Crite out a heap ump to the $ile you in i%ate. #in%e these $iles %an be big, an sin%e you Cill nee to trans$er them o$$ the evi%e or emulator, it Cill be best to spe%i$y a path to a $ile on e<ternal storage, Chi%h means that your proHe%t Cill nee the .'%T/0/1T/'2 !0#T3' G/ permission. 6o vieC the results in MA6, you Cill nee to trans$er the $ile to your evelopment ma%hine &e.g., >>M# (ile Manager, adb pull, using M6!4 mounte e<ternal storage on )oney%omb'.
-:6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
package com.common"ware.android.contact"."pinner": import import import import import import ja$a.io.@ile: ja$a.io.%3/xception: android.o".Bundle: android.o".,ebug: android.o"./n$ironment: android.te"t.%n"trumentationTe"t'unner:
public cla"" &profTe"t'unner extend" %n"trumentationTe"t'unner 7 O3$erride public $oid finish(int re"ultCodeD Bundle re"ult") 7 tr* 7 ,ebug.dump,prof*ata(new .ile(/n$ironment.get$"ternalStorage*irectory()D 9-prof.dmp9).getAbsolute#ath()): > catc- (%3/xception e) 7 e.printStackTrace(): > "uper.finish(re"ultCodeD re"ult"): > >
6o a %o e at the en o$ a test run, simply overri e the fini"-() metho , o your Cork, then %hain to the super%lass. )ere, Ce %reate an -prof.dmp $ile out in the root o$ e<ternal storage. 0ote that the runner oes not log to LogCat, Chi%h is Chy this %o e uses the %lassi% print#tackTrace() to ump any e<%eptions to the test runner8s oCn error log. 6o use the &profTe"t'unner, you nee to up ate the androidQname attribute in the 5in"trumentation6 element in your mani$est to re$eren%e this runner %lass*
5Sxml $er"ion89F.?9 encoding89utf-T9S6 5W-- package name mu"t be uni)ue "o "uffix wit- 9te"t"9 "o package loader doe"nPt ignore u" --6 5manife"t androidQ$er"ionCode89F9 androidQ$er"ion2ame89F.?9 package89com.common"ware.android.contact"."pinner".te"t"9 xmln"Qandroid89-ttpQ44"c-ema".android.com4apk4re"4android96 5W-- .e add an application tag -ere ju"t "o t-at we can indicate t-at t-i" package need" to link again"t t-e android.te"t librar*D w-ic- i" needed w-en building te"t ca"e". --6 5application6 5u"e"-librar* androidQname89android.te"t.runner9 46 54application6
-:7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
5W-T-i" declare" t-at t-i" application u"e" t-e in"trumentation te"t runner targeting t-e package of com.common"ware.android.databa"e. To run t-e te"t" u"e t-e commandQ 9adb "-ell am in"trument -w com.common"ware.android.databa"e.te"t"4android.te"t.%n"trumentationTe"t'unner9 --6 5in"trumentation androidQlabel89Te"t" for Contact#pinner"9 androidQname89com.common"ware.android.contact"."pinner".&profT e"t'unner9 androidQtarget(ackage89com.common"ware.android.contact"."pinne r"9 46 54manife"t6
Also, in your build.xml $ile $or Ant, you Cill nee to a the te"t.runner property, i enti$ying the same %lass, be$ore the 5"etup46 tag*
5propert* name89te"t.runner9 $alue89com.common"ware.android.contact"."pinner".&profTe"t'unner946 5"etup 46
6hen, running the tests via ant run-te"t" Cill use your runner an Cill ump the )!R+( $ile at the en o$ the run. ?ou %oul also ele%t to automate retrieving the )!R+( $ile by a ing an Ant task that Cill use adb pull to retrieve the $ile $rom Chere it is store . .$ you Cish to run your tests through A%lipse, you Cill nee to %hange the .nstrumentation property o$ your test proHe%ts to point to your %ustom %n"trumentationTe"t'unner sub%lass.
-:8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.$ you use stan alone >>M# or the %o e4base Cay o$ getting a heap ump, a$ter using -prof-con$ to %reate a MA64%ompatible version o$ your ump, you %an open it using the (ileX+pen )eap >ump... menu $rom the A%lipse &or stan alone MA6' main menu. 6he $irst time you run MA6, you Cill be presente Cith the K9etting #tarte WiIar K &see above s%reenshot', Chi%h you %an use or ismiss as you see $it. 6he +vervieC tool gives you, Cell, an overvieC o$ the %ontents o$ the heap ump*
-:9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$igure -60 The @vevie+ tool insi#e the AAT 3clipse perspective
6he +vervieC tool also has links an toolbar buttons to get you to the other maHor $un%tional areas Cithin MA6.
--:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he histogram initially isplays the top %ulprits in terms o$ KshalloC heapK J the amount o$ memory those obHe%ts hol onto ire%tly*
---
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6o see Chat obHe%ts o$ yours might still be in the heap, you %an type in a regular e<pression &e.g., com.common"ware.*' in the Rege< roC at the top o$ the table, then press UAnterV to vieC a $iltere list o$ obHe%ts base upon that regular e<pression*
--(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
)ere, Ce see one instan%e o$ a com.common"ware %lass is still lurking aroun a heap ump.
--4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he big $ilters are $or Kso$t re$eren%esK an KCeak re$eren%esK. 6hese re$er to the #oft'eference an .eak'eference %lasses in @ava, respe%tively. /oth are Cays to hol onto an obHe%t yet still alloC it to be garbage %olle%te Chen nee e . 6he big i$$eren%e is that an obHe%t only re$eren%e by .eak'eference obHe%ts %an be garbage %olle%te imme iately, Chile an obHe%t re$eren%e only by #oft'eference obHe%ts &or a mi< o$ #oft'eference an .eak'eference obHe%ts' shoul be kept aroun until the >alvik ,M is loC on memory. "sually, you %an ignore Ceak re$eren%es, as those Hust in i%ate obHe%ts that the garbage %olle%tor has not =uite ete%te are eligible $or re%lamation. Whether you Cant to also $ilter out so$t re$eren%es Coul epen a bit on the obHe%ts in =uestion J $or e<ample, i$ you are using #oft'eference Cith a %a%he, you might $ilter out so$t re$eren%es as Cell to %on$irm that nothing other than your %a%he is hol ing onto these obHe%ts. (iltering out Ceak re$eren%es &or Chatever' brings up another tab %ontaining the 9C roots preventing our a%tivity $rom being garbage %olle%te *
6his is shoCing that the class $or our a%tivity has a ata member &do2ot,oT-i"(lea"e' that has a View, an that in turn is hol ing onto our
--'
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
a%tivity via an mContext ata member. #tati% ata members &i.e., ata members o$ %lass obHe%ts' are %lassi% sour%es o$ memory leaks in @ava. 6he Retaine )eap %olumn on the $ar right shoCs hoC mu%h memory that in ivi ual obHe%t &an everything it points to' is keeping aroun J in this %ase, about 2.EF/.
$igure ((0 The icon use# for the ,ominator Tree toolbar button
--5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6his Cill open up another tab in the same tool, shoCing Kthe biggest obHe%tsK by retaine heap*
?ou %an isplay more by right4%li%king over the 6otal roC at the bottom an %hoosing K0e<t 2EK. )ere too, the roster Cill mostly be system obHe%ts &e.g., org.bounc*ca"tle $or the ja$ax.cr*pto implementation'. What you Coul be looking $or are obHe%ts that you might be intera%ting Cith more ire%tly that perhaps you are leaking, su%h as a /itmap. .$ you $in something o$ interest, right4%li%king over the obHe%t an %hoosing K!ath to 9C RootsK or KMerge #hortest !aths to 9C RootsK Cill help you tra%k oCn Chat is hol ing onto the obHe%t, akin to the similar $eature in the )istogram.
--6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): > > do2ot,oT-i"(lea"e8find!iewBy%d('.id.make0me0"tatic):
We take a Ci get &spe%i$i%ally the auto4generate TextView' an put it in a stati% ata member, an never repla%e it Cith null. As a result, even i$ the user presses /ACF to get out o$ the a%tivity, the stati% ata member hol s onto TextView, Chi%h itsel$ has a re$eren%e ba%k to our A%tivity. "sually, you Cill pi%k this sort o$ leak up by s%anning on your oCn appli%ation8s pa%kage, as your a%tivity Cill appear in there. .$ you are using multiple pa%kages in your appli%ation &e.g., yours an a thir 4party a%tivity', you might nee to also %he%k the thir 4party pa%kage to see i$ any o$ its obHe%ts are being leake . Whether those leaks are the $ault o$ your %o e or the thir party8s oCn %o e Cill vary, o$ %ourse.
!ea*ed Thread
?ou %an see similar results Chen you leak a threa , su%h as in the MA6MLeake 6hrea sample proHe%t*
--7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
package com.common"ware.android.tuning.mat: import android.app. cti$it*: import android.o".Bundle: import android.o".#*"temClock: public cla"" !eakedT-read cti$it* extend" cti$it* 7 O3$erride public $oid on reate(Bundle "a$ed%n"tance#tate) 7 "uper.on reate("a$ed%n"tance#tate): set ontent!iew('.la*out.main): new Thread() 7 public $oid run() 7 w-ile(true) 7 #*"temClock.sleep(F??): > > >.start(): > >
istogram
As Cith other pla%es in @ava &e.g., sta%k tra%es', the L synta< in a %lass name re$ers to an inner %lass, an LF re$ers to the $irst anonymous inner %lass. .$ Ce look at the 9C roots $or the a%tivity, Ce see*
6he root is a threa , as enote by the K6hrea K annotation on the en o$ the root entry. We see that the T-read obHe%t itsel$ is our Y1 inner %lass instan%e, an it hol s onto the a%tivity via the impli%it re$eren%e every non4 stati% inner %lass has to its outer %lass instan%e &t-i"L?'.
--8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Any running threa Cill %ause anything it %an rea%h to remain in the heap an not get garbage %olle%te . An inner %lass implementation o$ the T-read J Chi%h most %o e e<amples Cill use, in one $orm or $ashion J Cill leak the outer %lass instan%e. )en%e, the lessons to be learne here are*
Leaking threa s leaks memory Consi er using stati% inner %lasses, or separate %lasses, rather than non4stati% inner %lasses, so you o not %ause obHe%ts to be hel onto unne%essarily an une<pe%te ly
--9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6o $igure out Chat those obHe%ts are, you %an right4%li%k over a %lass in the )istogram an %hoose KList +bHe%tsK $rom the %onte<t menu. 6he $ly4out sub4menu Cill let you %hoose to shoC in%oming re$eren%es &Cho points to these obHe%ts' or outgoing re$eren%es &Chat these obHe%ts point to'. .n this %ase, shoCing in%oming re$eren%es Cill bring up the $olloCing*
-(:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$igure (80 The incoming references for the other Weather,emo instance
6he eight4 igit he< numbers shoCn a$ter the O sign are the obHe%t i enti$iers $or ea%h o$ the re$erre 4to obHe%ts. ?ou %an use this to istinguish Chi%h obHe%ts are the same. What you Cill noti%e is that both .eat-er,emo instan%es are pointe to by the #tate obHe%t. .n one, it is re$erre to by the acti$it* ata member. .n the other, it is re$erre to by t-i"L? J the impli%it re$eren%e an inner %lass instan%e has on the outer %lass instan%e. #in%e both .eat-er,emo instan%es hol onto the #tate via the "tate ata member, this means that one .eat-er,emo instan%e &the $oregroun one' is hol ing an in ire%t re$eren%e, via the #tate, to the other noC4 estroye .eat-er,emo instan%e. 6his is a leak. 6he solution $or this Coul be to use a stati% inner %lass $or #tate, eliminating the impli%it re$eren%e an breaking this %onne%tion.
-(-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6ra%ing through the in%oming re$eren%es, Ce see that the Context%mpl %lass hol s a stati% re$eren%e to the !ocation+anager system servi%e in our pro%ess, an !ocation+anager has an m!i"tener" ata member Chi%h is a list o$ all registere !ocation!i"tener instan%es. Alas, in .eat-er,emo, Ce are registering a !ocation!i"tener an never unregistering it. #in%e our !ocation!i"tener is an inner %lass, not only is the
-((
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
itsel$ leake , but it prevents our obHe%t $rom being garbage %olle%te .
!ocation!i"tener
estroye
.eat-er,emo
6his same pattern %an be seen $or many o$ the system servi%es J i$ you register a listener, you must ensure that you unregister it to prevent leaks.
-(4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 11
Most An roi evi%es are poCere by batteries J 9oogle 6, is the biggest %lass o$ evi%e that is not. /atteries are Con er$ul giImos Cith one maHor problem* they are always running out o$ poCer. )en%e, users are very sensitive to battery %onsumption. 6heir ability to use their phones as a%tual phones, let alone $or An roi apps, epen s on having enough battery poCer. 6he more apps rain the battery, the more $re=uently the user has to $in a Cay to re%harge the phone, an the more $re=uently the user $ails an their phone shuts oCn. 6he %at%h is that you may not noti%e the battery issues in your ay4to4 ay evelopment. 6he An roi emulator8s emulate battery oes not rain base on you running your app. ?our evi%es are o$ten %onne%te to your evelopment ma%hine via "#/ $or testing an ebugging, meaning they are perpetually being %harge . "nless you are a regular user o$ your oCn app, you might not noti%e any in%rease poCer rain. 6his part o$ the book is $o%use on helping you un erstan Chat is raining poCer an Chat you %an o to be kin er an gentler on your users8 batteries.
-(7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
UU s%reenshot VV
6his lists both evi%e $eatures &e.g., the isplay' an appli%ations. An roi in%rementally improves the a%%ura%y o$ this s%reen Cith ea%h passing release, trying to make sure the user un erstan s Chat spe%i$i%ally is %onsuming the poCer. .$ your appli%ation starts appearing on this s%reen, an the user oes not $eel that it is Husti$ie , the user is likely to be%ome irritate Cith you. 0oC, your appearan%e on this list might be per$e%tly reasonable. .$ you have Critten a vi eo player app, an the user has Hust Cat%he a $eC hours8 Corth o$ vi eo, it is very likely that you Cill appear on this list an Cill be Husti$ie in your battery %onsumption. )oCever, anything that you %an o to not appear on this s%reen, or appear loCer in the list, Cill help Cith user a%%eptan%e o$ your app. 6his part o$ the book Cill shoC you hoC to measure your poCer usage an Cays o$ trying to use less o$ it.
-(8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
-(9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 12
Rip open a evi%e enough to hook up a multi4tester to the proper lea s to measure physi%ally on the evi%e hoC mu%h poCer is being raine $rom the battery. ?ou Cill nee to either get a very sophisti%ate re%or ing multi4tester, or perhaps %ross4train a %ourt stenographer to be able to re%or the poCer levels %onsume as $ast as possible. ?ou $in a evi%e that %an o this sort o$ re%or ing automati%ally.
#in%e re%or ing multi4testers an %ourt stenographers are e<pensive, you might hea in the latter ire%tion. (ortunately, Nual%omm makes a series o$ evi%es J the Mobile >evelopment !lat$orm, or M>! J that %an re%or real4time poCer %onsumption. Nual%omm also makes a tool that %an interpret this in$ormation, %alle 6repn. .n this %hapter, Ce Cill e<amine the M>! an 6repn in greater etail, so you %an etermine Chat sorts o$ in$ormation this evi%e %an give you.
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6repn is largely useless Cithout a%%ess to an M>!8s poCer re%or ings, only those Cho have run a%ross an M>! are likely to have also hear o$ 6repn. +$ %ourse, sin%e you are rea ing this book, it is %lear that you are an e<emplary An roi eveloper, one thirsting $or knoCle ge an Cho there$ore might be intereste in learning more about these hi en gems.
WhatBs an $DP?
6he Nual%omm M>! is a mobile phone, but not one esigne $or %onsumer use. Rather, it is a re$eren%e plat$orm $or a Nual%omm mobile C!". 6here are tCo M>! mo els, one ea%h $or tCo Nual%omm pro%essors* the M#M3550 an the M#M35EE. As a re$eren%e plat$orm, this evi%e is not ne%essarily esigne to be regularly use . .nstea , it is esigne to shoC o$$ a number o$ a van%e har Care %apabilities an alloC evelopers to test on them. (or e<ample, the M>! $or the M#M3550 has*
>ual %ores &1.E9)I ea%h' 1030p vi eo re%or ing an playba%k B> output via )>M. a 1B megapi<el main %amera
6hese are all at or above most mainstream evi%es, as o$ the evi%e8s release in late spring 2011. 6he M>! also has a itional instrumentation esigne testing appli%ations, an that is Chere 6repn %omes in. to assist Cith
WhatBs a Trepn?
6he M>! has spe%ialiIe hooks in the $irmCare to monitor poCer %onsumption by various %omponents* C!", ra ios, isplay, et%. 6repn is an appli%ation, built into the M>!, that %an %olle%t, re%or , an isplay that
-4(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
ata an relate in$ormation. >evelopers %an use 6repn to etermine hoC mu%h poCer their appli%ation uses Chile it runs through a test suite, $or e<ample. 6repn runs on the evi%e itsel$, though it oes save its results as C#, $iles $or possible o$$line analysis. 6repn, there$ore, is not something that y0u run on your evelopment ma%hine or in your Web broCser, but on the M>! itsel$.
-44
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
UU s%reenshot VV 6hen, %li%k the K/egin !ro$ilingK button. 6his Cill bring up a ialog bo< Chere you %an sele%t an appli%ation on the M>! that 6repn shoul laun%h an monitor. UU s%reenshot VV 0ote that this means you %annot rea ily use 6repn to measure the poCer %onsume by a unit test suite or other $orm o$ instrumentation. ?ou may Cish to organiIe your %o e into an An roi library proHe%t Cith a separate proHe%t $or the ". $ront en , Cith a itional proHe%ts $or testing various poCer %onsumption s%enarios that you use Cith 6repn. +n%e you %hoose an appli%ation an %li%k the #tart button in the ialog, 6repn Cill gather a $eC se%on s o$ KCarmupK ata, then run your app. ?ou are Cel%ome to intera%t Cith your appli%ation at this point, i$ your app is intera%tive an you have not otherCise automate the testing. When you are one, return to the 6repn !ro$iler a%tivity &e.g., through the 0oti$i%ation in the status bar' an %li%k the K#top !ro$ilingK button. ?ou Cill be prompte $or the name o$ a ire%tory in Chi%h to save the ata. An that8s it;
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
some integer J it Cill be up to you to map integers to various portions o$ your appli%ation logi% &e.g., 1 is normal, 2 is uring your ata oCnloa , B is uring your ata e<port pro%ess'. .$ you tell 6repn the states o$ your appli%ation, it Cill not only re%or the overall results but the KsplitsK $or ea%h one o$ your states. (or e<ample, the (ower4,ownloader sample appli%ation is a slightly mo i$ie version o$ one $rom The !usy "oder#s $uide to ndroid %evelopment . .n that book, the sample app ha a large button J %li%king the button Coul ki%k o$$ a oCnloa o$ a T200F/ !>( $ile in a ba%kgroun threa via an %ntent#er$ice. 6his book8s version o$ the sample skips the button J laun%hing the a%tivity Cill intro u%e a $ive4se%on pause, then the oCnloa Cill begin automati%ally. 6he a%tivity Cill be $inishe on%e the oCnloa is %omplete. Along the Cay, Ce let 6repn knoC Chen the oCnloa Cork begins*
O3$erride public $oid on,andle%ntent(%ntent i) 7 %ntent trepn8new %ntent(9com.)uicinc.Trepn.Mpdate pp#tate9): trepn.put$"tra(9com.)uicinc.Trepn.Mpdate pp#tate.Value9D FJJU): sendBroadcast(trepn):
to %reate an %ntent $or the com.)uicinc.Trepn.Mpdate pp#tate a an e<tra Cith your integer keye as com.)uicinc.Trepn.Mpdate pp#tate.Value, then sen the broa %ast. 6he $a%t that 6repn uses broa %asts here means you Cill Cant your appli%ation states to be $airly %oarse4graine . ?ou %annot realisti%ally up ate the state more than on%e every %ouple o$ se%on s, an the asyn%hronous nature o$ sen ing broa %asts means that your Cork might begin be$ore the state itsel$ is re%or e .
-45
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
&n6Device
Aither be$ore stopping pro$iling, or by reloa ing the 6repn session via the K,ieC #ave #essionsK button, you %an vieC a graph o$ poCer %onsumption* UU s%reenshot VV or %li%k K,ieC #tatsK $or a tabular ren ition o$ the ata* UU s%reenshot VV /y e$ault, 6repn Cill re%or a han $ul o$ values, su%h as the poCer %onsume overall an by the tCo C!" %ores. .n the 6repn settings a%tivity, though, you %an toggle on or o$$ any number o$ other values to re%or , plus in i%ate i$ they shoul be isplaye in the resulting graph. /oth the graph an the table Cill shoC your appli%ation states. +n the graph, the %hanges in your appli%ation state value Cill be graphe along Cith everything else. 6he table Cill shoC hoC mu%h time an poCer Cas %onsume in ea%h o$ your states J probably a more valuable means o$ interpreting the results.
&776Device
.$ you broCse the e<ternal storage o$ the M>!, you Cill $in ire%tory that %ontains the save sessions $rom your tests* a trepn
-46
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
(or ea%h %olle%te statisti% $or ea%h save session, there Cill be a C#, $ile %ontaining the raC ata. 6he %olumns $or the C#, $ile Cill vary by statisti%, though all Cill have a time o$$set %olumn to in i%ate Chen the value Cas re%or e . (or e<ample, here is an e<tra%t $rom the Batter* (ower.c"$ $ile $rom one 6repn run Cith ellipses a e to shoC Chere portions o$ the $ile Cere remove $or brevity*
Time (m")DBatter* (ower (u )DBatter* (ower (u.) -=KF=DGY??DF?UT= -=TF=DGY??DF?UT= -=UF=DGY??DF?UT= ... -F?=DGY??DF?UT= -GDGY??DF?UT= KKDGY??DF?UT= FKTDGY??DF?UT= GKKDGY??DF?UT= ...
-47
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
X?G=DGY??DF?UT= XFGXDGY??DF?UT= XGG=DGY??DF?UT= XJGXDGY??DF?UT= X=GUDGY??DF?UT= XXGXDGY??DF?UT= XYJ?DGY??DF?UT= XUJGDGY??DF?UT= XTJJDGY??DF?UT= XKJFDJKT??DFYX?K? Y?JFDJ???DFG==J YFJ=DGY??DF?UT= YGJ=DGY??DF?UT= ...
6ime values less than 0 represent the KCarmupK perio be$ore 6repn a%tually runs your appli%ation. .n this %ase, the battery poCer is shoCn both in mi%ro4amps &uA' an mi%ro4Catts &uW'. 6o %orrelate these events Cith your appli%ation states, you Cill also nee to e<amine the pplication #tate.c"$ $ile*
Time (m")D pplication #tate -=KX?D? -=T=KD? -=U=KD? ... -FJ=D? -J=D? YYD? FYUD? GYUD? JYUD? ... X?KGD? XFJYDFJJU XFKJDFJJU XGKJDFJJU XJKJDFJJU X=K=DFJJU XXK=DFJJU XYK=DFJJU XUK=DFJJU XTKXDFJJU XKKYDFJJU Y?KYDFJJU YFKYDFJJU YGKUDFJJU ...
-48
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6he time o$$sets Cill not line up pre%isely &$or Chatever reason', but Cill shoC the save appli%ation state value at the spe%i$i% o$$sets. #o, betCeen E.012 an E.1B5 se%on s a$ter the a%tual test began, our appli%ation state shi$te $rom the e$ault to 1BB2, %orrespon ing to the value Ce sent over in the broa %ast %ntent e<tra. All poCer levels a$ter that point Coul be relate to the oCnloa operation. .n prin%iple, one %oul import these into a sprea sheet or %ra$t tools to parse the C#, ata an %reate other visual representations, parti%ularly in Cays that %an be use Cithout the M>! being aroun .
-49
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
CHAPTER 1)
9iven the sheer e<pense o$ the Nual%omm M>!, $eC evelopers Cill have ire%t a%%ess to one, espite the etaile poCer statisti%s one %an glean $rom 6repn. 6here are $ree alternatives, but they all have substantial limits Chen %ompare to the %ombination o$ the M>! an 6repn.
Po+erTutor
!erhaps the best4knoCn thir 4party poCer analyIer is !oCer6utor. !oCer6utor is the out%ome o$ a resear%h proHe%t $rom the "niversity o$ Mi%higan, Cith a bit o$ assistan%e $rom 9oogle. .n prin%iple, !oCer6utor is %apable o$ letting you knoC poCer %onsumption on a evi%e, mu%h along the lines o$ Chat 6repn %an re%or on a Nual%omm M>!. .n pra%ti%e, !oCer6utor is signi$i%antly less poCer$ul an sophisti%ate . !oCer6utor Cas %reate Cith the )6C >ream &64Mobile 91', )6C Magi% &64Mobile 92', an 0e<us +ne in min . .ts poCer output values Cill be as a%%urate as they %oul make it $or those evi%es. .$ you run !oCer6utor on other har Care, the results Cill be less a%%urate. ?ou %an obtain !oCer6utor $rom the An roi Market, or $rom the !oCer6utor Web site, or you %an %ompile it $rom sour%e.
-'-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
!oCer6utor is not tie to testing a parti%ular appli%ation. As su%h, you %an simply run !oCer6utor Chenever you Cant $rom its laun%her i%on, then press K#tart !oCer !ro$ilerK in the main a%tivity*
At this point, you %an start playing Cith your appli%ation, or running your unit test suite, or Chatever. When you Cant to get an i ea o$ hoC mu%h poCer you have been %onsuming, you %an sCit%h ba%k to the !oCer6utor a%tivity an %hoose K,ieC Appli%ation !oCer "sageK. 6his brings up a list o$ pro%esses an toggle buttons to shoC various poCer %onsumption values $or ea%h*
-'(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
6apping the list entry brings up a graph $or that parti%ular pro%ess, though sin%e this in$ormation is only available Chile !oCer6utor is re%or ing neC ata, the graph is usually empty unless you have logi% running in the ba%kgroun *
-'4
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$igure 440 The Po+erTutor live charts for a single process current po+er consumption
?ou %an also bring up a %harts shoCing Chat portion o$ your poCer %onsumption %ame $rom various sour%es $or the Chole evi%e, su%h as a pie %hart o$ %urrent %onsumption*
-''
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
$igure 4'0 The Po+erTutor pie chart for current overall po+er consumption
9iven that the sour%e %o e is available, one might augment !oCer6utor to*
#aving results, both as ata $iles $or o$$line analysis &akin to 6repn8s C#, $iles' or $or vieCing %harts an tables on the evi%e Chen ata is not being a%tively %olle%te AlloCing one to re%or appli%ation states, akin to 6repn, to better %orrelate appli%ation $un%tionality to save poCer results
-'5
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
UU s%reenshot VV A$ter all, this is Chat users Cill ten to $o%us on J anything shoCing up in here is a sour%e o$ blame $or Chatever poCer Coes the user believes she is e<perien%ing. Conversely, i$ your appli%ation oes not shoC up in this s%reen uring normal operation, then there is no %ompelling reason $or you to o $urther analysis, as users Cill ten to be oblivious to your a%tual poCer %onsumption. .$ you o shoC up in the list, tapping on your entry %an give you some more etails o$ Chat poCer you %onsume an Chy* UU s%reenshot VV
Batter!Info ,ump
?et another possibility is to use the adb "-ell dump"*" batter*info %omman $rom your %omman prompt or terminal on your evelopment Corkstation. 6his Cill emit a $air amount o$ ata that probably means something to somebo y, su%h as general evi%e in$ormation*
Batter* &i"tor*Q -F-??mXY"=YJm" ?KY G??J???G "tatu"8di"c-arging -ealt-8good plug8none temp8FKF $olt8=?Y? ;"creen ;wake0lock ;"en"or brig-tne""8medium -F-??mXG"=K?m" ?KY GG?J?J?G ;wifi p-one0"tate8off -F-??mXF"T==m" ?KY GU?JdF?G ;p-one0"canning ;wifi0running p-one0"tate8out data0conn8ot-er -F-??m=K"J?Jm" ?KY GU=JdF?G ;wifi0"can0lock -XUm=T"UYYm" ?KX GU=JdF?G -XJmG="YGUm" ?KX GU=JdF?? brig-tne""8dark -XJmFU"YG?m" ?KX ?U=FdF?? -"creen -wake0lock -XJmFU"F?Um" ?KX ?U=?dF?? -"en"or -JTmFU"??Um" ?KX ?Y=GdF?? -wifi0running ;wake0lock -JTm?T"KKTm" ?KX ?Y=?dF?? -wake0lock -X="UTFm" ?KX =Y=?dF?? "tatu"8full plug8u"b temp8FKJ $olt8=?T= ;plugged (er-(%, #tat"Q (%, KY wake timeQ ;FG"UXm" (%, FUU wake timeQ ;F"FJm" (%, =XT wake timeQ ;F"TKTm" (%, JGY wake timeQ ;J"KGXm" (%, G?X wake timeQ ;G"F?Um" (%, =FX wake timeQ ;T=Jm"
-'6
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
(%, KY wake timeQ ;GTFm" #tati"tic" "ince la"t c-argeQ #*"tem "tart"Q ?D currentl* on batter*Q fal"e Time on batter*Q F- ?m F" YTGm" (?.J[) realtimeD Tm GF" TTJm" (?.?[) uptime Total run timeQ FYd FF- FJm J=" YX=m" realtimeD G- Km JU" =?=m" uptimeD #creen onQ Um JU" TYTm" (FG.U[)D %nput e$ent"Q ?D cti$e p-one callQ ?m" (?.?[) #creen brig-tne""e"Q dark U" Um" (F.X[)D medium Um J?" TYFm" (KT.X[) Aernel .ake lock 9#+,0,#9Q G" JYTm" (J time") realtime Aernel .ake lock 9mmc0dela*ed0work9Q F" GF?m" (F time") realtime Aernel .ake lock 9#+,0'(CC !!9Q XYm" (=JX time") realtime Aernel .ake lock 9power-"uppl*9Q XUXm" (= time") realtime Aernel .ake lock 9radio-interface9Q J" Fm" (J time") realtime Aernel .ake lock 9 pmCommandT-read9Q =m" (F? time") realtime Aernel .ake lock 9d"GUT=-batter*9Q G" Ym" (GF time") realtime Aernel .ake lock 9m"mfb0idle0lock9Q F=m" (GGUJ time") realtime Aernel .ake lock 9kg"l9Q XF" =TGm" (YFJ time") realtime Aernel .ake lock 9rpc0read9Q FY=m" (GUG time") realtime Aernel .ake lock 9main9Q Um JK" U?Tm" (? time") realtime Total recei$edQ ?BD Total "entQ ?B Total full wakelock timeQ F=Km" D Total partial waklock timeQ JF" F=m" #ignal le$el"Q none XKm XU" YJm" (KK.K[) Fx #ignal "canning timeQ XKm XU" YJm" 'adio t*pe"Q none Y=Fm" (?.?[) FxD ot-er XKm XY" KUJm" (KK.K[) Fx 'adio data uptime w-en unpluggedQ ? m" .ifi onQ XKm XU" U?Km" (KK.K[)D .ifi runningQ GGm JX" =G=m" (JU.Y[)D BluetootonQ ?m" (?.?[) ,e$ice mount mount mount mount batter* u"e "ince la"t full c-arge di"c-arged (lower bound)Q ? di"c-arged (upper bound)Q F di"c-arged w-ile "creen onQ F di"c-arged w-ile "creen offQ ?
by !oCer6utor
-'7
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
.n prin%iple, one might %reate tools that use this output J or perhaps steal a peek at the ata use by the #ettings appli%ation J to %reate something a bit more eveloper4$rien ly.
-'8
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Ce!+or# In#ex
Class...............................................
Abstra%t!re$s!ersist#trategy.......................E2, EB A%tivity.........................................................BB, 11 A%tivityManager........................................15, 100 A apter....................................................2, -2, -3 A apter,ieC........................................-B, -2, 100 AlarmManager...................................E, E5, 1-415 Alert>ialog........................................................1ArrayList............................................................2B Asyn%Re%eiver....................................................E1 Asyn%6ask..........................11, 12, 12, BB, -3, E2, EE /aseA apter......................................................-2 /itmap...............................................................-3 /itmap(a%tory...................................................-3 /roa %astRe%eiver............B, -E, -14E1, 23, 31, 1/uil er................................................................13 /utton............................................................2, E0 Che%k/o<!re$eren%e.........................................1Conne%tivityManager.......................................1Content!rovi er............................................B, 12
ContentResolver...............................................-Conte<t.mpl.....................................................122 Cursor.....................................................13, -2, -1 CursorA apter...................................................-2 CursorLoa er....................................................->ebug...........................................................5, 105 A it6e<t........................................................E0, E1 A it6e<t!re$eren%e............................................1B 9eo!oint............................................................-0 9ri ,ieC..............................................................2 )ashMap............................................................21 )ash#et..............................................................2B )pro$6estRunner......................................105, 102 )ttp"rlConne%tion....................................32, 33 .mage,ieC........................................................101 .nput#tream......................................................32 insert&'...............................................................EE .nstrumentation6estRunner...........................103 .ntent.........................................................1BE, 1B1 .ntent#ervi%e.....................................B, E5, 12, 1BE
-'9
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Ce!+or# In#ex
List!re$eren%e...................................................1B List,ieC.......................2, 15, --, 10, 100, 102, 105 Loa er................................................................-1 Lo%ation.............................................................-0 Lo%ationListener.......................................122, 12B Lo%ationManager.......................................-E, 122 0onAsyn%Re%eiver............................................E0 +ut+$MemoryArror........................................100 !a%kageManager................................................21 !ar%elable..........................................................-2 !en ingResult....................................................E1 !oCerManager..................................................E5 !ro%ess...............................................................EE !rogress>ialog..................................................E#ervi%e..................................................................B #ervi%eConne%tion...........................................12B #hare !re$eren%es.......................................E2, 1B #hare !re$eren%es.A itor.................................E2 #o$tRe$eren%e....................................................11#pinner.............................................................105 #ta%k+ver$loCArror.........................................102 #tate............................................................111, 121 #tri%tMo e..................................12411, -5, -3, -1 #tring................................................1B, -E, 20, 11 #tring/u$$er.......................................................-0 #tring/uil er...........................................1B, 1-, -0 #tring!er$/uil er...............................................1B #tring!er$Con%at...............................................10 #ystem..........................................................B2, -E 6ab)ost............................................................102 6e<t,ieC............................................2, BB, 22, 112 6hrea ........................................................113, 111 6ime!re$eren%e.................................................1E 6imer6ask............................................................E 6imingLogger....................................................15 6ra$$i%MonitorA%tivity.......................................21 6ra$$i%Re%or ................................................20, 21 6ra$$i%#napshot............................................20422 6ra$$i%#tats................52451, 25, 22, 30, 31, 1B415 ,eri$yArror.........................................................E,ieC.......................................................-2, -3, 11,ieC)ol er.......................................................-E Weak/en%h..............................................23, B14BB WeakRe$eren%e.................................................11Weather>emo......................................111, 121412B Web,ieC...........................................................31
Command......................................
a b pull.................................................1, 105, 103 a b shell umpsys batteryin$o........................1-5 a b shell kill.....................................................10a b shell setprop log.tag.L+9Z6A9 ,AR/+#A ............................................................................ 15 am broa %ast.....................................................23 an roi up ate proHe%t 4p ...............................<vi ant run4tests.....................................................103 hpro$4%onv................................................10E, 101 Hava%....................................................................1B n k4buil ............................................................B1 p $tk [.p $ %at output %ombine .p $.................< su o aptitu e install make gaCk.....................22
-5:
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Ce!+or# In#ex
tra%evieC.............................................................1 Y0>FMn k4buil ................................................B1 getMobile6<!a%kets&'......................................53 get6ag&'.............................................................-3 get6otalR</ytes&'........................................52, 20
0ethod...........................................
abort/roa %ast&'................................................E1 appen &'........................................................1B, 1appen 0&'...........................................................1apply&'..........................................................E2, Earray%opy&'........................................................-E begin6ransa%tion&'............................................EE bin #ervi%e&'.....................................................-B bulk.nsert&'.......................................................-%ommit&'......................................................E24Eelete&'.........................................................--, EE o6est&'..............................................................1B ump)pro$>ata&'...........................................105 ump6oLog&'.....................................................15 emitLog&'.....................................................2B, 2enable>e$aults&'................................................13 e<e%#NL&'..........................................................EE $in ,ieC/y. &'..................................................-3 $inish&'.........................................................E1, 102 getA%tive0etCork.n$o&'...................................1get/a%kgroun >ata#etting&'...........................1get.tem,ieC6ype&'...........................................-2 getLargeMemoryClass&'..................................100 getLastFnoCnLo%ation&'..................................-E getMobileR</ytes&'..........................................53 getMobileR<!a%kets&'......................................53 getMobile6</ytes&'..........................................53
get6otalR<!a%kets&'..........................................53 get6otal6</ytes&'........................................52, 20 get6otal6<!a%kets&'..........................................53 get"i R</ytes&'..........................................53, 20 get"i R<!a%kets&'............................................53 get"i 6%p6</ytes&'..........................................53 get"i 6</ytes&'..........................................53, 20 get,ieC&'.................................................2, -2, -3 get,ieC6ypeCount&'.........................................-2 goAsyn%&'......................................................-14E1 in e<+$&'...........................................................-E insert&'...............................................................-is#%reen+n&'.....................................................E5 loa Library&'......................................................B2 mallo%&'......................................................101, 12B manage Nuery&'...............................................-nsievenative&'..............................................B0, BB onCli%k&'..............................................................2 onCreate&'................................................2, 13, 22 on)an le.ntent&'................................................B onRe%eive&'..............................................B, -1, E0 onResume&'.......................................................-1 onRetain0onCon$iguration.nstan%e&'............111 on#tartComman &'.............................................B persist&'..............................................................E2 print#ta%k6ra%e&'.............................................102 =uery&'.................................................................B
-5-
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC
Ce!+or# In#ex
registerRe%eiver&'..............................................-E retainAll&'..........................................................2B sen Asyn%&'.......................................................E0 sen /roa %ast&'..........................................-E, E0 sen 0onAsyn%&'...............................................E0 set+n#%rollListener&'........................................12 set6ag&'..............................................................-3 set6hrea !riority&'...........................................EE set"p&'...............................................................22 spe%native&'.................................................B0, BB split&'..................................................................15 startA%tivity&'....................................................-E startManagingCursor&'.....................................-1 startMetho 6ra%ing&'.....................................5, 2 start#ervi%e&'.........................................--, -E, -1 stopMetho 6ra%ing&'..........................................2 take#napshot&'............................................22, 2B tear>oCn&'........................................................22 to#tring&'............................................................1B up ate&'.......................................................--, EE value+$&'............................................................12
-5(
This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC