Sunteți pe pagina 1din 173

Tuning Android Applications

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

Welcome to the Warescription!

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

Welcome to the Book!


Writing An roi appli%ations is not that har . Writing An roi appli%ations that run %risply an stay Cithin the %on$ines o$ the limite %apabilities o$ mobile evi%es is someChat more i$$i%ult. 6his book aims to help you Cith these issues. .$ you %ome to this book having rea other CommonsWare An roi books in the Wares%ription, thanks $or sti%king Cith the series; CommonsWare aims to have the most %omprehensive set o$ An roi evelopment resour%es &outsi e o$ the +pen )an set Allian%e itsel$', an . appre%iate your interest. .$ you %ome to this book having learne about An roi $rom other sour%es J or i$ you are neC to An roi entirely J thanks $or Hoining the CommonsWare %ommunity; An roi , Chile aime at small evi%es, is a surprisingly vast plat$orm, making it i$$i%ult $or any given book, training, Ciki, or other sour%e to %ompletely %over everything one nee s to knoC. An , most o$ all, thanks $or your interest in this book; . sin%erely hope you $in it use$ul an at least o%%asionally entertaining.

xi

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

What This Book Is All About


Mobile evi%es Cill alCays be %ompare to their higher poCere brethren in esktops an notebooks. (rom a per$orman%e stan point, there$ore, mobile evi%es Cill lag behin $or the $oreseeable $uture. Mobile evi%es Cill have Ceaker C!"s, less RAM, less storage, tiny batteries, an so on. ?et, users Coul pre$er to not hear e<%uses as to Chy appli%ations per$orm poorly or evi%es not eliver Chat they e<pe%t. )en%e, it is in%umbent upon An roi appli%ation evelopers to o Chat they %an to make their apps Cork Cell given the limitations o$ your average mobile phone, tablet, an set4top bo<. 6his book aims to help evelopers i enti$y Chere they have problems an hoC to a ress them. 6his book is ivi e tuning* 1. into $ive parts, $or $ive maHor areas o$ per$orman%e

C!", $or appli%ation spee

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.

Book Bug Bount!


(in a problem in one o$ our booksD Let us knoC;

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

)oCever, those Kso$terK issues program.

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.

Creative Commons an# the $our%to%$ree &'($) Guarantee


Aa%h CommonsWare book e ition Cill be available $or use un er the Creative Commons Attribution40on%ommer%ial4#hare Alike B.0 li%ense as o$ the $ourth anniversary o$ its publi%ation ate, or Chen -,000 %opies o$ the e ition have been sol , Chi%hever %omes $irst. 6hat means that, on%e $our years have elapse &perhaps sooner;', you %an use this prose $or non4 %ommer%ial purposes. 6hat is our (our4to4(ree 9uarantee to our rea ers an the broa er %ommunity. (or the purposes o$ this guarantee, neC Wares%riptions an reneCals Cill be %ounte as sales o$ this e ition, starting $rom the time the e ition is publishe . 6his e ition o$ this book Cill be available un er the a$orementione Creative Commons li%ense on @uly 1 9 )41#. +$ %ourse, Cat%h the CommonsWare Web site, as this e ition might be reli%ense sooner base on sales. (or more etails on the Creative Commons Attribution40on%ommer%ial4 #hare Alike B.0 li%ense, visit the Creative Commons Web site. 0ote that $uture e itions o$ this book Cill be%ome $ree on later ates, ea%h $our years $rom the publi%ation o$ that e ition or base on sales o$ that spe%i$i% e ition. Releasing one e ition un er the Creative Commons li%ense oes not automati%ally release all e itions un er that li%ense.

xvi

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

*ifec!cle of a CommonsWare Book


CommonsWare books generally go through a series o$ stages. (irst are the pre4release e itions. 6hese Cill have version numbers beloC 0.1 &e.g., 0.2'. 6hese e itions are in%omplete, o$ten times having but a $eC %hapters to go along Cith outlines an notes. )oCever, Ce make them available to those on the Wares%ription so they %an get early a%%ess to the material. Release %an i ates are e itions Cith version numbers en ing in K.1K &0.1, 1.1, et%.'. 6hese e itions shoul be %omplete. +n%e again, they are ma e available to those on the Wares%ription so they get early a%%ess to the material an %an $ile bug reports &an re%eive bounties in return;'. MaHor e itions are those Cith version numbers en ing in K.0K &1.0, 2.0, et%.'. 6hese Cill be $irst publishe igitally $or the Wares%ription members, but Cill shortly therea$ter be available in print $rom booksellers Corl Ci e. ,ersions betCeen a maHor e ition an the ne<t release %an i ate &e.g., 1.1, 1.2' Cill %ontain bug $i<es plus neC material. Aa%h o$ these e itions shoul also be %omplete, in that you Cill not see any K6/>K &to be one' markers or the like. )oCever, these e itions may have bugs, an so bug reports are eligible $or the bounty program, as Cith release %an i ates an maHor releases. A book usually Cill progress $airly rapi ly through the pre4release e itions to the $irst release %an i ate an ,ersion 1.0 J o$ten times, only a $eC months. >epen ing on the book8s s%ope, it may go through another %y%le o$ signi$i%ant improvement &versions 1.1 through 2.0', though this may take several months to a year or more. Aventually, though, the book Cill go into more o$ a Kmaintenan%e mo eK, only getting up ates to $i< bugs an eal Cith maHor e%osystem events J $or e<ample, a neC release o$ the An roi #>F Cill ne%essitate an up ate to all An roi books.

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

PART I CPU Performance

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

Issues +ith "pee#

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 .

Getting Things ,one


.n some %ases, you simply %annot seem to get the Cork one that you Cant to a%%omplish. ?our atabase =uery seems sloC. ?our en%ryption algorithm seems sloC. ?our image pro%essing logi% seems sloC. An so on. 6he limits o$ the evi%e Cill %ertainly make this more o$ a problem than it might otherCise be. Aven a %urrent4era ual4%ore evi%e Cill be sloC %ompare to your average notebook or esktop. Also, this sort o$ spee issue is pervasive throughout %omputing, Cith e%a es o$ e<perien%e to help evelopers learn hoC to Crite leaner %o e.

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith "pee#

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.

.our /I "eems000 1ank!


#ometimes, the spee Coul be less o$ an issue $or the user, i$ it Cas not $reeIing the ". or otherCise making it appear sluggish an KHankyK. 6he An roi Ci get $rameCork operates in a single4threa e mo e. All ". %hanges J $rom setting the te<t o$ a TextView to han ling s%rolling o$ a GridView J are pro%esse as events on an event =ueue by the main appli%ation threa . 6hat same threa is use $or most ". %allba%ks, in%lu ing a%tivity li$e%y%le metho s &e.g., onCreate()' an ". event metho s &e.g., onClick() o$ a Button, getView() o$ an dapter'. Any time you take in those metho s on the main appli%ation threa tie up that threa , preventing it $rom pro%essing other 9". events or ispat%hing user input. (or e<ample, i$ your getView() pro%essing in an dapter takes too long, s%rolling a !i"tView may appear sloC %ompare to other !i"tView Ci gets in other appli%ations. ?our obHe%tive is to i enti$y Chere things are sloC an move them into ba%kgroun operations. #ome o$ this has been a vise sin%e the early ays o$ An roi , su%h as moving all netCork .M+ to ba%kgroun threa s. #ome o$ this has arisen more re%ently, su%h as the move to use the Kloa erK $rameCork to help you get ata $rom ata stores in the ba%kgroun $or populating your ".. 6his part o$ the book Cill point out Cays $or you to $in out Chere you may be oing un$ortunate things on the main appli%ation threa an te%hni=ues $or getting that Cork han le by a ba%kgroun threa , or possibly eliminate outright.

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith "pee#

2ot $ar 3nough in the Backgroun#


#ometimes, even Cork you are trying to o in the ba%kgroun Cill seem to impa%t the $oregroun . (or e<ample, you might think that your #er$ice is automati%ally in the ba%kgroun . An %ntent#er$ice oes in ee use a ba%kgroun threa $or pro%essing %omman s via on&andle%ntent(). )oCever, all li$e%y%le metho s o$ any #er$ice, in%lu ing on#tartCommand(), are %alle on the main appli%ation threa . )en%e, any time you take in those li$e%y%le metho s Cill steal time aCay $rom 9". pro%essing $or the main appli%ation threa . 6he same hol s true $or on'ecei$e() o$ a Broadca"t'ecei$er an all the main metho s o$ a Content(ro$ider &e.g., )uer*()'. Aven your ba%kgroun threa s may not be su$$i%iently in the ba%kgroun . A pro%ess runs Cith a %ertain priority, using Linu< pro%ess management A!.s, base upon its state &e.g., i$ there is an a%tivity in the $oregroun , it runs at a higher priority than i$ the pro%ess solely hosts some servi%e'. 6his Cill help to %ap the C!" utiliIation o$ the ba%kgroun Cork, but only to a point. #imilarly, threa s that you $ork J ire%tly or via something like %ntent#er$ice J may run at e$ault priority rather than a loCer priority. Aven Cith loCer priorities $or the threa or pro%ess, every C!" instru%tion e<e%ute in the ba%kgroun is one %lo%k ti%k that %annot be utiliIe by the $oregroun . 6his part o$ the book Cill help you i enti$y Chere you are taking lots o$ time on various threa s an Cill help you manually manage priorities to help minimiIe the $oregroun impa%t o$ those threa s, in a ition to helping you re u%e the amount o$ Cork those threa s have to o.

Pla!ing +ith "pee#


9ames, more so than most other appli%ations, are highly spee 4 epen ent. Averyone is seeking the Kholy grailK o$ 50 $rames per se%on &(!#' ne%essary $or smooth animate e$$e%ts. 0ot a%hieving that $rame rate overall may mean the appli%ation Cill not appear =uite as smoothG spora i%ally $alling
4

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith "pee#

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

$in#ing CP/ Bottlenecks

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

$in#ing CP/ Bottlenecks

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.

Collecting Trace Data


)en%e, the $irst step $or $in ing Chere your C!" bottlene%ks lie %omes in the $orm o$ %olle%ting tra%e ata, to analyIe Cith 6ra%evieC. As mentione , there are tCo approa%hes $or re=uesting tra%e ata be logge * using the ,ebug %lass, an using >>M#.

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

$in#ing CP/ Bottlenecks

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$$*

$igure -0 Toolbar button to start an# stop metho# tracing

+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

$in#ing CP/ Bottlenecks

+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<'.

Performance While Tracing


Writing out ea%h metho invo%ation to a tra%e $ile a s signi$i%ant overhea to your appli%ation. Run times %an easily ouble or more. )en%e, absolute times Chile tra%ing is enable are largely meaningless J instea , as you analyIe the ata in 6ra%evieC, the goal is to e<amine relative times &i.e., su%h4an 4so metho takes up PQ o$ the C!" time shoCn in the tra%e'. Also, running 6ra%evieC isables the @.6 engine in >alvik, $urther harming per$orman%e. 0otably, this Cill not a$$e%t any native %o e you have a e via the 0>F, so an appli%ation run in 6ra%evieC Cill give you unusual results &mu%h Corse @ava per$orman%e, more normal native per$orman%e'.

Displa ing Trace Data


9iven that Ce have %olle%te a tra%e $ile Cith ata, the ne<t step is to open up 6ra%evieC on that $ile. >epen ing on hoC you %olle%te the $ile, 6ra%evieC may appear Kautomagi%allyK, or it may re=uire you to manually start it up an point it to the tra%e $ile.

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

$in#ing CP/ Bottlenecks

$igure (0 ,ebug perspective in 3clipse sho+ing Tracevie+ &mi##le left)

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

$in#ing CP/ Bottlenecks

Interpreting Trace Data


+$ %ourse, the %hallenge is in making sense o$ Chat 6ra%evieC is trying to present. (or e<ample, a %lassi% per$orman%e bug in @ava evelopment is using string %on%atenation*
protected #tring doTest() 7 #tring re"ult89T-i" i" a "tring9: re"ult;89 < t-at $arie" --9: re"ult;89 and al"o -a" 9: re"ult;8#tring.valueOf(=): re"ult;89 -*p-en" in it9: return(re"ult): >

)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

$in#ing CP/ Bottlenecks

$igure 40 3xpan#e# look at Tracevie+ tool

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.

$igure '0 ;oome# in look at the Trace<ie+ threa# timelines

?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

$in#ing CP/ Bottlenecks

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*

$igure 50 "ample application metho# calls in Tracevie+

+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*

$igure 60 ,rilling #o+n in Tracevie+

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

$in#ing CP/ Bottlenecks

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

$in#ing CP/ Bottlenecks

$igure 70 Tracevie+= sorte# b! exclusive time

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*

$igure 80 Tracevie+= sho+ing parents of a metho# call

)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*

$igure 90 Tracevie+= >oome# in on ?(4: millisecon#s of run time

-'

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$in#ing CP/ Bottlenecks

.$ 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$ &not 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.

@ther General CP/ Aeasurement Techniques


While 6ra%evieC is great $or narroCing oCn a general per$orman%e issue to a spe%i$i% portion o$ %o e, it oes assume that you knoC appro<imately Chere the problem is, or that you even have a problem in the $irst pla%e. 6here are other approa%hes to help you i enti$y i$ an &roughly' Chere you have problems, Chi%h you %an then atta%k Cith 6ra%evieC to try to re$ine.

-5

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$in#ing CP/ Bottlenecks

!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

$in#ing CP/ Bottlenecks

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'.

"trictAo#e for Aain Application Threa# Is% sues


0+6A* the $olloCing material is e<%erpte $rom 6he /usy Co er8s 9ui e to An roi >evelopment, Chi%h has a itional %overage o$ #trict+ode. "sers are more likely to like your appli%ation i$, to them, it $eels responsive. )ere, by KresponsiveK, Ce mean that it rea%ts sCi$tly an a%%urately to user operations, like taps an sCipes. Conversely, users are less likely to be happy Cith you i$ they per%eive that your ". is KHankyK J sluggish to respon to their re=uests. (or e<ample, maybe your lists o not s%roll as smoothly as they Coul like, or tapping a button oes not yiel the imme iate results they seek. While threa s an "*ncTa"k an the like %an help, it may not alCays be obvious Chere you shoul be applying them. )oCever, there are a $eC stan ar sorts o$ things that evelopers o, sometimes =uite by a%%i ent, on the main appli%ation threa that Cill ten to %ause sluggishness*

(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

$in#ing CP/ Bottlenecks

)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.

#etting up #trict $ode


Corks on a set o$ poli%ies. 6here are presently tCo %ategories o$ poli%ies* ,M poli%ies an threa poli%ies. 6he $ormer represent ba %o ing pra%ti%es that pertain to your entire appli%ation, notably leaking #NLite Cur"or obHe%ts an kin. 6he latter represent things that are ba Chen per$orme on the main appli%ation threa , notably $lash .M+ an netCork .M+.
#trict+ode

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*

Log a message to LogCat >isplay a ialog Crash your appli%ation &seriously;'

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

$in#ing CP/ Bottlenecks

Develop%ent &nl ' Please(


>o not use #trict+ode in pro u%tion %o e. .t is esigne $or use Chen you are buil ing, testing, an ebugging your appli%ation. .t is not esigne to be use in the $iel . 6o eal Cith this, you %oul *

#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 )

$ocus @nB 2,C

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.

The Dole of the 2,C


We start by e<amining >alvik8s primarily limitation J spee . 0e<t, Ce look at the reasons one might %hoose the 0>F, spee among them. We Crap up
(-

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

Cith some reasons Chy the 0>F may not be the right solution $or every An roi problem, espite its bene$its.

Dalvi*+ #ecure' ,es- #peed ' .ot #o $uch


>alvik Cas Critten Cith se%urity as a high priority. An roi 8s se%urity ar%hite%ture is built aroun Linu<8s user mo el, Cith ea%h appli%ation getting its oCn user .>. With ea%h appli%ation8s pro%ess running un er its oCn user .>, one pro%ess %annot rea ily a$$e%t other pro%esses, helping to %ontain any single se%urity $laC in an An roi appli%ation or subsystem. 6his re=uires a $air number o$ pro%esses. )oCever, phones have limite RAM, an the An roi proHe%t Cante to o$$er @ava4base evelopment. Multiple pro%esses hosting their oCn @ava virtual ma%hines simply %oul not $it in a phone. >alvik8s virtual ma%hine is esigne to a ress this, ma<imiIing the amount o$ the virtual ma%hine that %an be share se%urely betCeen pro%esses &e.g., via K%opy4on4CriteK'. +$ %ourse, it is Con er$ul that An roi has se%urity so Coven into the $abri% o$ its implementation. )oCever, inventing a neC virtual ma%hine re=uire tra eo$$s, an most o$ those are relate to spee . A $air amount o$ Cork has gone into making @ava $ast. #tan ar @ava virtual ma%hines o a remarkable Hob o$ optimiIing appli%ations on the $ly, su%h that @ava appli%ations %an per$orm at spee s near their CMCSS %ounterparts. 6his bor ers on the amaIing an is a testament to the many engineers Cho put %ountless years into @ava. >alvik, by %omparison, is very young. Many o$ @ava8s per$orman%e optimiIation te%hni=ues J su%h as a van%e garbage %olle%tion algorithms J simply have not been implemente to nearly the same level in >alvik. 6his is not to say they Cill never e<ist, but it Cill take some time. Aven then, though, there may be limits as to hoC $ast >alvik %an operate, %onsi ering that it %annot KthroC memory at the problemK to the e<tent @ava %an on the esktop or server.

((

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

.$ you nee spee , >alvik is not the ansCer to ay, an ansCer tomorroC, either.

may not be the

/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

$ocus @nB 2,C

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.

0nowing ,our !i%its


>evelopers love silver bullets. >evelopers are $orevermore seeking 6he +ne 6rue Approa%h to evelopment that Cill be problem4$ree. #isyphus Coul approve, o$ %ourse, as evelopment alCays involves tra eo$$s. #o Chile the 0>F8s spee may make it tantaliIing, it is not a solution $or general An roi appli%ation evelopment, $or several reasons, e<plore in this se%tion.

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

$ocus @nB 2,C

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

$ocus @nB 2,C

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.

2,C Installation an# ProEect "etup


6he An roi 0>F is bliss$ully easy to install, in some Cays even easier than is the An roi #>F. #imilarly, setting up an 0>F4e=uippe proHe%t is rather straight$orCar . )oCever, the o%umentation $or the 0>F is mostly a set o$ te<t $iles &3V/'V%/..T1T prominent among them'. 6hese are Cell4Critten but su$$er $rom the limits o$ the plain4te<t $orm $a%tor, plus are $o%use stri%tly on the 0>F an not the larger issue o$ An roi proHe%ts that use the 0>F. 6his %hapter Cill $ill in some o$ those gaps.

Installing the .D0


As Cith the An roi #>F, the An roi 0>F %omes in the $orm o$ a R.! $ile, %ontaining everything you nee to buil 0>F4enable An roi appli%ations. )en%e, setting up the 0>F is $airly trivial, parti%ularly i$ you are eveloping on Linu<.
(6

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

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.

Download and %npac&


6he An roi 0>F per4plat$orm &Linu<M+# PMWin oCs' R.! $iles %an be oCnloa e $rom the 0>F page on the An roi >evelopers site. 6hese R.! $iles are not small &TE0M/ ea%h', be%ause they %ontain the entire tool%hain J that is Chy there are so $eC prere=uisites. ?ou are Cel%ome to unpa%k the R.! $ile anyChere it makes sense on your evelopment ma%hine. )oCever, putting it inside the An roi #>F ire%tory may not be a Cise move J a peer ire%tory Coul be a sa$er %hoi%e. ?ou are Cel%ome to rename the ire%tory i$ you %hoose.

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

$ocus @nB 2,C

/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.

#etting 1p an .D0 Pro2ect


At its %ore, an 0>F4enhan%e An roi proHe%t is a regular An roi proHe%t. ?ou still nee a mani$est, layouts, @ava sour%e %o e, an all the other trappings o$ a regular An roi appli%ation. 6he 0>F simply enables you to a CMCSS %o e to that proHe%t an have it in%lu e in your buil s, re$eren%e $rom your @ava %o e via the @ava 0ative .nter$a%e &@0.'. 6he e<amples shoCn in this se%tion are $rom the B2%4.eakBenc- proHe%t, Chi%h implements a pair o$ ben%hmarks in @ava an C, to help emonstrate the per$orman%e i$$eren%es betCeen the environments.

Writing (our C/C)) Code


6he $irst step toCar s a ing 0>F %o e to your proHe%t is to %reate a jni4 ire%tory an pla%e your CMCSS %o e insi e o$ it. While there are Cays to use a i$$erent base ire%tory, it is un%lear Chy you Coul nee to. )oC you organiIe the %o e insi e o$ jni4 is up to you. CSS %o e shoul use .cpp as $ile e<tensions, though this too is %on$igurable. ?our CMCSS %o e Cill be ma e up o$ tCo $a%ets* 1. 6he %o e oing the real Cork

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

$ocus @nB 2,C

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

$ocus @nB 2,C

$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

$ocus @nB 2,C

Writing (our Ma&efile*s+


6o tell the 0>F tools hoC to buil your %o e, you Cill nee one or tCo make$iles.

,uilding (our -ibrar"


Any time you mo i$y your CMCSS %o e, or the make$iles, you Cill nee to buil your 0>F library. 6o o that, $rom a %omman prompt in your proHe%t8s root ire%tory, run the ndk-build s%ript $oun in the 0>F8s root ire%tory. .n other Cor s, i$ you set up an 0>F environment variable to point to Chere you have the 0>F installe , e<e%ute L2,A4ndk-build $rom your proHe%t root. 6his Cill %ompile an link your CMCSS %o e into a library &or %on%eivably several libraries, i$ you have a %omple< set o$ ndroid.mk $iles'. 6hese Cill Cin up in your proHe%t8s lib"4 ire%tory, in sub ire%tories base on your C!" ar%hite%tures in i%ate by your pplication.mk $ile. (or e<ample, i$ you run L2,A4ndk-build $rom the .eakBenc- proHe%t root, you Cill Cin up Cith a lib"4armeabi4libweakbenc-."o $ile. 6he armeabi portion is be%ause that is the e$ault C!" ar%hite%ture that the 0>F supports, an .eakBenc- i not %hange the e$aults via an pplication.mk $ile. 6he KCeakben%hK portion o$ libweakbenc-."o is be%ause our !3C !0+3,M!/ value in our ndroid.mk $ile is weakbenc-. 6he lib pre$i< is automati%ally a e by the buil tools. 6he ."o $ile e<tension is be%ause our ndroid.mk $ile in i%ate that Ce are buil ing a share library &via the BM%!,0#& '/,0!%B' 'N ire%tive', an ."o is the stan ar $ile e<tension $or share libraries in Linu< &an , hen%e, An roi '. ?ou are Cel%ome to a this to your buil pro%ess, su%h as a Ant buil s%ript, though it is not automati%ally in%lu e pro%ess as e$ine by An roi . ing it to your in the buil

4-

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

%sing (our -ibrar" 'ia ./


0oC that you have your base CMCSS %o e being su%%ess$ully %ompile by the 0>F, you nee to turn your attention toCar s %ra$ting the bri ge betCeen the >alvik ,M an the CMCSS %o e, $olloCing in the %onventions o$ the @ava 0ative .nter$a%e &@0.'. 6his se%tion, Chile e<plaining the various steps involve in using the @0., is $ar $rom a %omplete treatise on the subHe%t. .$ you are going to spen a lot o$ time Corking Cith @0., you are en%ourage to seek a itional resour%es on this topi%, su%h as Core @ava* ,olume .., Chi%h has a %hapter on @0.. We %reate tCo C $un%tions $or a%%essing ben%hmarks* 1.
Ba$a0com0common"ware0abj0weakbenc-0.eakBenc-0n"ie$enati$e

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

$ocus @nB 2,C

"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

$ocus @nB 2,C

pri$ate cla"" Ba$a#ie$eTa"k extend" long "tart8?: TextView re"ult8null:

"*ncTa"k5VoidD VoidD Void6 7

O3$erride protected $oid on#re$"ecute() 7 re"ult8(TextView)find!iewBy%d('.id.n"ie$e0ja$a): > re"ult.setTe"t(9running...9):

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

pri$ate cla"" Ba$a#pecTa"k extend" long "tart8?: TextView re"ult8null:

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

$ocus @nB 2,C

Appro"imate(F???): > 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'%SieveTask().e"ecute():

> >

pri$ate cla"" B2%#ie$eTa"k extend" long "tart8?: TextView re"ult8null:

"*ncTa"k5VoidD VoidD Void6 7

O3$erride protected $oid on#re$"ecute() 7 re"ult8(TextView)find!iewBy%d('.id.n"ie$e0jni): > re"ult.setTe"t(9running...9):

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

pri$ate cla"" B2%#pecTa"k extend" long "tart8?: TextView re"ult8null:

O3$erride protected $oid on#re$"ecute() 7 re"ult8(TextView)find!iewBy%d('.id."pec0jni): re"ult.setTe"t(9running...9): >

45

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

O3$erride protected Void do%nBackground(Void... unu"ed) 7 "tart8#*"temClock.uptime&illis(): specnative(): > 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)): > >

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

$ocus @nB 2,C

> 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.

,uilding and Deplo"ing (our Pro0ect


9iven that you have one all o$ this, the rest is per$e%tly normal J you buil an eploy your An roi proHe%t no i$$erently than i$ you i not have any CMCSS %o e. ?our native library is embe e in your A!F $ile, so you o not have to Corry about istributing it separately. /ear in min that your appli%ation Cill only Cork on plat$orms $or Chi%h you have versions o$ your library. #in%e the vast maHority o$ An roi evi%es run ARM %hipsets, this Cill not be a signi$i%ant issue right noC. As Ce en%ounter Atom4poCere 9oogle 6,s an the like, in time, you may Cish
47

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB 2,C

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

Improving CP/ Performance in 1ava

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.

De#uce CP/ /tili>ation


+ne %lass o$ C!"4relate problems %ome $rom purely sluggish %o e. 6hese are the sorts o$ things you Cill see in 6ra%evieC, $or e<ample J metho s or bran%hes o$ %o e that seem to take an inor inately long time. 6hese are also some o$ the most i$$i%ult to have general solutions $or, as o$ten times it %omes oCn to Chat the appli%ation is trying to a%%omplish. )oCever, the $olloCing se%tions provi e suggestions $or %onsuming $eCer C!" instru%tions Chile getting the same Cork one. 6hese are presente in no parti%ular or er.

49

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

#tandard 4ava &pti%i5ations


Most o$ your algorithm $i<es Cill be stan ar @ava optimiIations, no i$$erent than have been use by @ava proHe%ts over the past e%a e an %hange. 6his se%tion outlines a $eC o$ them. (or more, %onsi er rea ing Effective Java by @oshua /lo%h or Java Performance Tuning by @a%k #hiraIi.

Avoid E#cessive S"nchroni1ation


(eC obHe%ts in ja$a.* namespa%es are intrinsi%ally threa 4sa$e, outsi e o$ ja$a.util.concurrent. 6ypi%ally, you nee to per$orm your oCn syn%hroniIation i$ multiple threa s Cill be a%%essing non4threa 4sa$e obHe%ts. )oCever, sometimes, @ava %lasses have syn%hroniIation that you neither e<pe%t nor nee . #yn%hroniIation a s unne%essary overhea . 6he %lassi% e<ample here is #tringBuffer an #tringBuilder. #tringBuffer Cas part o$ @ava $rom early on, an , $or Chatever reason, Cas Critten to be threa 4sa$e J tCo threa s that appen to the bu$$er Cill not %ause any problems. )oCever, most o$ the time, you are only using the #tringBuffer $rom one threa , meaning all that syn%hroniIation overhea is a Caste. Later on, @ava a e #tringBuilder, Cith the same basi% set o$ metho s as has #tringBuffer, but Cithout the syn%hroniIation. #imilarly, in your oCn %o e, only syn%hroniIe Chere is is really nee e . >o not toss the "*nc-roniEed keyCor aroun ran omly, or use %on%urrent %olle%tions that Cill only be use by one threa , et%.

Avoid 2loating!Point Math


6he $irst generation o$ An roi evi%es la%ke a $loating4point %opro%essor on the ARM C!" pa%kage. As a result, $loating4point math spee Cas atro%ious. 6hat is Chy the 9oogle Maps a 4on $or An roi uses Geo(oint, Cith latitu e an longitu e in integer mi%ro egrees, rather than the stan ar An roi !ocation %lass, Chi%h uses @ava ouble variables hol ing e%imal egrees.

':

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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.

Don3t Assume ,uilt! n Algorithms are ,est


?ears upon years o$ Cork has gone into the implementation o$ various algorithms that un erlie @ava metho s, like sear%hing $or substrings insi e o$ strings. #omeChat less Cork has gone into the implementation o$ the Apa%he )armony versions o$ those metho s, simply be%ause the proHe%t is younger, an it is a mo i$ie version o$ the )armony implementation that you Cill $in in An roi . While the %ore An roi team has ma e many improvements to the original )armony implementation, those improvements may be $or optimiIations that o not $it your nee s &e.g., optimiIing to re u%e memory %onsumption at the e<pense o$ C!" time'. /ut beyon that, there are oIens o$ string4mat%hing algorithms, some o$ Chi%h may be better $or you epen ing on the string being sear%he an the string being sear%he $or. )en%e, you may Cish to %onsi er applying your oCn sear%hing algorithm rather than relying on the built4in one, to boost per$orman%e. An , this same %on%ept may hol $or other algorithms as Cell &e.g., sorting'.

'-

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

+$ %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.

#upport Hardware6Accelerated /raphics


An easy KCinK is to a androidQ-ardware ccelerated89true9 to your 5application6 element in the mani$est. 6his toggles on har Care a%%eleration $or 2> graphi%s, in%lu ing mu%h o$ the sto%k Ci get $rameCork. (or ma<imum ba%kCar s %ompatibility, this har Care a%%eleration is o$$, but a ing the a$orementione attribute Cill enable it $or all a%tivities in your appli%ation. 0ote that this is only available starting Cith An roi B.0. .t is sa$e to have the attribute in the mani$est $or ol er An roi evi%es, as they simply Cill ignore your re=uest. ?ou also shoul test your appli%ation thoroughly a$ter enabling har Care a%%eleration, to make sure there are no une<pe%te issues. (or or inary Ci get4base appli%ations, you shoul en%ounter no problems. 9ames or other appli%ations that o their oCn raCing might have issues. .$ you $in that some o$ your %o e runs into problems, you %an overri e har Care a%%eleration on a per4a%tivity basis by putting the androidQ-ardware ccelerated on 5acti$it*6 elements in the mani$est.

$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

Improving CP/ Performance in 1ava

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

4emote ,ound Service


"sing a remote servi%e is $airly obvious Chen you o it J it is i$$i%ult to mistake %opying the A.>L into your proHe%t an su%h. 6he pro<y obHe%t generate $rom the A.>L %onverts all your metho %alls on the inter$a%e into .!C operations, an this is relatively e<pensive. .$ you are e<posing a servi%e via A.>L, esign your A!. to be %oarse4graine . >o not re=uire the %lient to make 1,000 metho invo%ations to a%%omplish something that %an be one in 1 via slightly more %omple< arguments an return values. .$ you are %onsuming a remote servi%e, try not to get into situations Chere you have to make lots o$ %alls in a tight loop, or per roC o$ a s%rolle dapterView, or anything else Chere the overhea may be%ome troublesome. (or e<ample, in the C(M-Ba$a4 %,!3$er-ead ire%tory o$ the book8s sour%e %o e, you Cill $in a pair o$ proHe%ts implementing the same o4nothing metho in e=uivalent servi%es. +ne uses A.>L an is boun to remotely $rom a separate %lient appli%ationG the other is a lo%al servi%e in the %lient appli%ation itsel$. 6he %lient then %alls the o4nothing metho 1 million times $or ea%h o$ the tCo servi%es. +n average, on a #amsung 9ala<y 6ab 10.1, 1 million %alls takes aroun 120 se%on s $or the remote servi%e, Chile it takes aroun 120 milliseconds $or the lo%al servi%e. )en%e, the overhea o$ an in ivi ual remote metho invo%ation is small &T120 mi%rose%on s', but
'4

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

oing lots o$ them in a loop, or as the user $lings a !i"tView, might be%ome noti%eable.

4emote Content Provider


"sing a %ontent provi er %an be someChat less obvious o$ a problem. "sing Content'e"ol$er or managedRuer*() or a Cur"or!oader looks the same Chether it is your oCn %ontent provi er or someone else8s. )oCever, you knoC Chat %ontent provi ers you CroteG anything else is probably running in another pro%ess. As Cith remote servi%es, try to aggregate operations Cith remote %ontent provi ers, su%h as*

"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

Improving CP/ Performance in 1ava

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.

Android6#peci7ic 4ava &pti%i5ations


6he Cay that the >alvik ,M Cas implemente an operates is subtly i$$erent than a tra itional @ava ,M. 6here$ore, there are some optimiIations that are more important on An roi than you might $in in regular esktop or server @ava. 6he An roi eveloper o%umentation has a roster o$ su%h optimiIations. #ome o$ the highlights in%lu e*

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

Improving CP/ Performance in 1ava

De#uce Time on the Aain Application Threa#


Another %lass o$ C!"4relate problem is Chen your %o e may be e$$i%ient, but it is o%%urring on the main appli%ation threa , %ausing your ". to rea%t sluggishly. ?ou might have tune your e%ryption algorithm as best as is mathemati%ally possible, but it may be that e%rypting ata on the main appli%ation threa simply takes too mu%h time. +r, perhaps #trict+ode %omplaine about some isk or netCork .M+ that you are per$orming on the main appli%ation threa . 6he $olloCing se%tions re%ap some %ommonly4seen patterns $or moving Cork o$$ the main appli%ation threa , plus a $eC neCer options that you may have misse .

/enerate !ess /ar8age


Most evelopers think o$ having too many allo%ations as being solely an issue o$ heap spa%e. 6hat %ertainly has an impa%t, an epen ing on the nature o$ the allo%ations &e.g., bitmaps', it may be the ominant issue. )oCever, garbage has impa%ts $rom a C!" stan point as Cell. Avery obHe%t you %reate %auses its %onstru%tor to be e<e%ute . Avery obHe%t that is garbage4%olle%te re=uires C!" time both to $in the obHe%t in the heap an to a%tually %lean it up &e.g., e<e%ute the $inaliIer, i$ any'. Worse still, on ol er versions o$ An roi &e.g., An roi 2.2 an oCn', the garbage %olle%tor interrupts the entire pro%ess to o its Cork, so the more garbage you generate, the more times you Kstop the Corl K. 9ame evelopers have ha to eal Cith this sin%e An roi 8s in%eption. 6o maintain a 50 (!# re$resh rate, you %annot a$$or any garbage %olle%tions on ol er evi%es, as a single 9C run %oul easily take more than the T15ms you have per raCing pass. As a result o$ all o$ this, game evelopers have ha to %are$ully manage their oCn obHe%t pools, pre4allo%ating a bun%h o$ obHe%ts be$ore game play

'6

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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.

9iew Rec cling


!erhaps the best4%overe An roi 4spe%i$i% optimiIation is vieC re%y%ling Cith dapterView. 6his is is%usse in any e%ent intro u%tory An roi te<t, in%lu ing the author8s oCn 6he /usy Co er8s 9ui e to An roi >evelopment. .n a nutshell, i$ you are e<ten ing Ba"e dapter, or i$ you are overri ing getView() in another a apter, please make use o$ the View parameter supplie to getView() &re$erre to here as con$ertView'. .$ con$ertView is not null, it is one o$ your previous View obHe%ts you returne $rom getView() be$ore, being o$$ere to you $or re%y%ling purposes. "sing con$ertView saves you $rom in$lating or manually %onstru%ting a $resh View every time the user s%rolls, an both o$ those operations are relatively e<pensive. .$ you have been ignoring con$ertView be%ause you have more than one type o$ View that getView() returns, your dapter shoul be overri ing getViewT*peCount() an get%temViewT*pe(). 6hese Cill alloC An roi to
'7

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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

Improving CP/ Performance in 1ava

#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

As nchronous :roadcastReceiver &perations


11.--Q o$ the time &appro<imately' that An roi %alls your %o e in some sort o$ event han ler, you are being %alle on the main appli%ation threa . 6his in%lu es mani$est4registere Broadca"t'ecei$er %omponents J on'ecei$e() is %alle on the main appli%ation threa . #o any Cork you o in on'ecei$e() ties up that threa &possibly impa%ting an a%tivity o$ yours in the $oregroun ', an i$ you take more than 10 se%on s, An roi Cill terminate your Broadca"t'ecei$er Cith e<treme preHu i%e. Classi%ally, mani$est4registere Broadca"t'ecei$er %omponents only live as long as the on'ecei$e() %all oes, meaning you %an o very little Cork in the Broadca"t'ecei$er itsel$. 6he typi%al pattern is to have it sen a %omman to a servi%e via "tart#er$ice(), Chere the servi%e K oes the heavy li$tingK. An roi B.0 a e a go "*nc() metho on Broadca"t'ecei$er that %an help a bit here. While un er4 o%umente , it tells An roi that you nee more time to %omplete the broa %ast Cork, but that you %an o that Cork on a ba%kgroun threa . 6his oes not eliminate the 104se%on rule, but it oes mean that the Broadca"t'ecei$er %an o some amount o$ .M+ Cithout having to sen a %omman to a servi%e to o it Chile still not tying up the main appli%ation threa .

'9

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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"")):

public $oid send'onAsync(View $) 7 sendBroadcast(new %ntent(t-i"D 2on "*nc'ecei$er.cla"")): > >

6he 2on "*nc'ecei$er simulates oing time4%onsuming Cork in on'ecei$e() itsel$*


5:

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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

Improving CP/ Performance in 1ava

.$ 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

Improving CP/ Performance in 1ava

#-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

Improving CP/ Performance in 1ava

> >

+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

>

O3$erride $oid persistAsync(/ditor editor) 7 editor.apply(): >

/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.

Improve Throughput an# Desponsiveness


/eing e$$i%ient an oing Cork on the proper threa may still not be enough. .t %oul be that your Cork is not %onsuming e<%essive C!" time, but is taking too long in KCall %lo%k timeK &e.g., the user sits Caiting too long at a (rogre"",ialog'. +r, it %oul be that your Cork, Chile e$$i%ient an in the ba%kgroun , is %ausing i$$i%ulty $or $oregroun operations. 6he $olloCing se%tions outline some %ommon problems an solutions in this area.

5'

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

$ini%i5e Dis* Writes


Aarlier in this book, Ce emphasiIe moving isk Crites o$$ to ba%kgroun threa s. Aven better is to get ri o$ some o$ the isk Crites entirely. A big %ulprit here %omes in the $orm o$ atabase operations. /y e$ault, ea%h in"ert(), update(), or delete(), or any exec#R!() invo%ation that mo i$ies ata, Cill o%%ur in its oCn transa%tion. Aa%h transa%tion involves a set o$ isk Crites. Many times, this is not a problem. /ut, i$ you are oing a lot o$ these J su%h as importing re%or s $rom a C#, $ile J hun re s or thousan s o$ transa%tions Cill mean thousan s o$ in ivi ual isk Crites, an that %an take some time. ?ou may Cish to Crap those operations in your oCn transa%tion, using metho s like beginTran"action(), simply to re u%e the number o$ transa%tions an , there$ore, isk Crites. .$ you are oing your oCn isk .M+ beyon atabases, you may en%ounter similar sorts o$ issues. +verall, it is better to o a $eC larger Crites than lots o$ little ones.

#et Thread Priorit


6hrea s by e$ault, run at a e$ault priority* as e$ine on the (roce"" %lass. 6his is a loCer priority than the main appli%ation threa &T&'/ ,0('%3'%TN0,%#(! N'.
T&'/ ,0('%3'%TN0,/@ M!T

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

Improving CP/ Performance in 1ava

?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 &not 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 "..

Do the Wor* #o%e &ther Ti%e


@ust be%ause you %oul o the Cork noC oes not mean you shoul o the Cork noC. !erhaps a better ansCer is to o the Cork later, or o part o$ the Cork noC an part o$ the Cork later. (or e<ample, suppose that you have your oCn atabase o$ points o$ interest $or your %ustom map appli%ation. !erio i%ally, you publish a neC atabase on your Web site, Chi%h your An roi app shoul oCnloa . + s are e%ent that the user is not in esperate nee $or this neC atabase right aCay. .n $a%t, the C!" time an isk .M+ time to oCnloa an save the atabase might in%rementally inter$ere Cith the $oregroun appli%ation, espite your best e$$orts. .n this %ase, not only shoul you %he%k $or an oCnloa the atabase Chen the user is unlikely to be using the evi%e &e.g., be$ore aCn', but you shoul %he%k Chether the s%reen is on via i"#creen3n() on (ower+anager, an elay the Cork to sometime Chen the s%reen is o$$. (or e<ample, you %oul have larm+anager set up to have your %o e %he%k $or up ates every 2hours at -am. .$, at -am, the s%reen is on, your %o e %oul skip the oCnloa an Cait until tomorroC, or skip the oCnloa an a a one4

56

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Improving CP/ Performance in 1ava

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

PART II Bandwidth Performance

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 ;

Issues +ith Ban#+i#th

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

Issues +ith Ban#+i#th

.ouFre /sing Too Auch of the "lo+ "tuff


6o paraphrase Ameri%a8s (oun ing (athers, Kall .nternet %onne%tions are not %reate e=ualK. +ne $orm o$ ine=uality is spee . >i$$erent %lasses o$ %onne%tion have i$$erent theoreti%al upper boun s. WiMAP an other K-9K %onne%tions are theoreti%ally $aster than B9 %onne%tions, Chi%h are theoreti%ally $aster than 29 or A>9A %onne%tions. Wi(i J typi%ally 302.11g in to ay8s evi%es J is theoreti%ally ri i%ulously $ast though it is typi%ally limite by the .#! %onne%tion, an .#! %onne%tions %an run the gamut $rom really $ast to merely goo . )oCever, Ktheoreti%alK boun s ten to run a$oul o$ reality. 6here are plenty o$ pla%es Chere high4spee mobile ata %onne%tions are non4e<istent, espite Chat the %arriers8 %overage maps %laim. 29 mobile ata Corks, but is not espe%ially spee y. 6his layers on top o$ the typi%al .nternet %ongestion issues, along Cith typi%ally transitory problems &e.g., trying to get %onne%tivity Chile atten ing a te%hnology %on$eren%e keynote presentation'. )en%e, Chat runs =ui%kly in the lab may run mu%h more sloCly in users8 han s. .$ you $olloCe the instru%tions in previous %hapters on C!" bottlene%ks, the limite ban Ci th Cill not %ause your ". to be%ome KHankyK, in that it Cill be responsive to tou%hes an taps. )oCever, poor %onne%tivity Cill mean that you are simply sloC to respon to user re=uests. (or e<ample, %li%king the K%he%k $or neC emailK menu button has no imme iate e$$e%t. .$ you $eel that you nee a splash s%reen or progress in i%ator to tell the user that KCe are really %he%king $or neC email, honestK, then you knoC that your .nternet a%%ess is sloCer than is i eal. +bviously, some o$ this is unavoi able. )oCever, the obHe%tive o$ the %hapters in this part o$ the book is to give you an i ea o$ Cays to re u%e

6(

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith Ban#+i#th

your ban Ci th %onsumption, making those annoying $or your users.

elays be that mu%h less

.ouFre /sing Too Auch of the 3xpensive "tuff


Mobile ata ten s to %ome Cith more strings atta%he than oes Wi(i. .n the "#, it use to be that mobile ata %onne%tions in%lu e unlimite usage. 0oC, at best, a mobile ata plan has Kunlimite K usage $or a %urious e$inition o$ the term Kunlimite K. More an more %arriers are moving toCar s a har %ap J go above the %ap, an you either %annot use more ban Ci th, have your spee s %urtaile , or pay signi$i%antly $or a itional ban Ci th. +utsi e o$ the "#, the Kpay signi$i%antly $or ban Ci thK approa%h is $airly typi%al. #o4%alle Kmetere K ata plans simply %harge you su%h4an 4so per M/ or 9/ o$ ban Ci th. An , to top it o$$, roaming almost alCays is a metere plan. #o, a "# resi ent traveling overseas, even Cith a #.M an phone that supports international usage, Coul pay a ri i%ulous sum $or ban Ci th. #tories o$ phone bills in the tens o$ thousan s o$ ollars aboun , Chere people simply use their phone as they normally Coul Chen they Cere outsi e o$ their home netCork. )en%e, i$ you use a $air bit o$ ban Ci th, it Coul be really ni%e i$ you o$$ere users means to %onsume less o$ it Chen they are on mobile ata %ompare to Wi(i &Chi%h is typi%ally unmetere '. ?ou %oul ele%t to poll your server less $re=uently, $or e<ample, giving the users the ability to spe%i$y separate polling perio s epen ing on Chi%h type o$ %onne%tion they have. An , o$ %ourse, there are other K%ostsK $or using ban Ci th besi es ire%t monetary %osts. (or e<ample, oCnloa ing ata over a sloCer mobile ata %onne%tion may %onsume more poCer than oCnloa ing the same ata over Wi(i J Chile the Wi(i ra io might %onsume a itional poCer, the
64

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith Ban#+i#th

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.

.ouFre /sing Too Auch of "omebo#! 3lseFs "tuff


.t is easy $or evelopers to think that they alone are using a user8s evi%e. Alas, this is in$re=uently the %ase, parti%ularly Chen it %omes to ba%kgroun .nternet a%%ess. While your appli%ation is busily oCnloa ing stu$$, some other appli%ation might be busily oCnloa ing stu$$. .n prin%iple, this shoul not be an issue, as multiple appli%ations %an a%%ess the .nternet simultaneously. )oCever, ban Ci th %an be%ome an issue. .$ you are in the ba%kgroun , an the other appli%ation is in the $oregroun , the user might noti%e that ban Ci th is an issue. (or e<ample, users might be unhappy i$ your oCnloa s are impe ing their ability to Cat%h streaming vi eo, or play their $avorite An roi 4base MM+R!9, or Chatever. A polite An roi appli%ation Cill test to see Chether the $oregroun appli%ation is heavily using the .nterent an Cill %urtail its oCn .nternet use Chile that is going on. 6his %hapter Cill help you learn hoC to make that etermination an hoC to respon .

.ouFre /sing Too Auch000 An# There Is 2one


0ot only might lo%ation i%tate hoC mu%h ban Ci th you have, but Chether you have any ban Ci th at all. While some people think that the entire planet has %onne%tivity, reality on%e again i%tates otherCise. MaHor metropolitan areas have
6'

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith Ban#+i#th

%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 <

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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.

Interpreting the Results


?ou Cill get one o$ tCo types o$ return value $rom these metho s. .n theory, you Cill get the value the metho %alls $or &e.g., number o$ bytes, number o$ pa%kets'. 6he o%umentation oes not state the time perio $or that value, so Chile it is possible that it is really Knumber o$ bytes sin%e the evi%e Cas boote K, Ce o not knoC that $or %ertain. )en%e, Traffic#tat"
68

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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

$ocus @nB Traffic"tats

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

$igure --0 The TrafficAonitor sample application= as initiall! launche#

7'

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB Traffic"tats

6apping 6ake #napshot grabs a se%on snapshot an %ompares the tCo*

$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

$ocus @nB Traffic"tats

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?)

@ther Wa!s to 3mplo! Traffic"tats


+$ %ourse, there are more Cays you %oul use Traffic#tat" than simply having an a%tivity to report them on a button %li%k. Traffic+onitor is merely a emonstration o$ using the %lass an provi ing a lightCeight Cay to get value out o$ that ata. >epen ing upon your appli%ation8s operations, though, you may Cish to %onsi er using Traffic#tat" in other Cays, in your pro u%tion %o e or in your test suites.

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

$ocus @nB Traffic"tats

(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

$ocus @nB Traffic"tats

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 =

Aeasuring Ban#+i#th Consumption

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$*

by measuring your ban Ci th

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

Aeasuring Ban#+i#th Consumption

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.

,oursel7' via Tra77ic#tats


6he pre%e ing %hapter outline hoC to use the Traffic#tat" %lass to %olle%t metri%s on the ban Ci th %onsume by appli%ations &in%lu ing yours' an $or the evi%e as a Chole. 6his gives you the most $le<ibility, be%ause you %an Crite your oCn %o e to %olle%t Chatever portion o$ this ata you nee . .t %an a ress all o$ the bullets shoCn above, $or e<ample. .t is not per$e%t, though*

.t re=uires you to Crite your oCn %o e, a your plate

ing yet more Cork to

!er4".> tra$$i% ata may or may not be available, epen ing upon the evi%e

E>isting Android Applications


.$ you o not Cant to Crite %o e to use Traffic#tat", there are various appli%ations on the An roi Market that %an report that ata to you, mu%h along the lines o$ hoC Traffic+onitor oes. )ere are some notes about a $eC $ree ones teste by the author*

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

Aeasuring Ban#+i#th Consumption

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

Aeasuring Ban#+i#th Consumption

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*

$igure -40 Wireshark examining capture# emulator packets

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

Aeasuring Ban#+i#th Consumption

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 ?

Being "marter About Ban#+i#th

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

Being "marter About Ban#+i#th

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.

Classic HTTP #olutions


6rying to get lots o$ ata to $it on a narroC pipe J Chether that pipe is on the user8s en or the provi er8s en J has long been a struggle in Web evelopment. (ortunately, there are a number o$ Cays you %an leverage )66! intelligently to re u%e your ban Ci th %onsumption.

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,

2. >etermine i$ the e%ompressing it

/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

Being "marter About Ban#+i#th

&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

Being "marter About Ban#+i#th

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

+n subse=uent re=uests, you %an a both %ases*


&ttpGet get8new ,ttp-et(url): get.add,eader(9%f-2one-+atc-9D etag):

the %f-2one-+atc- hea er an han le

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

Being "marter About Ban#+i#th

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 .

Push versus Poll


Another Cay to %onsume less ban Ci th is to only make the re=uests Chen it is nee e . (or e<ample, i$ you are Criting an email %lient, the Cay to use the least ban Ci th is to oCnloa neC messages only Chen they e<ist, rather than $re=uently polling $or messages. +$$ the %u$$, this may seem %ounter4intuitive. A$ter all, hoC %an Ce knoC Chether or not there are any messages i$ Ce are not polling $or themD 6he ansCer is to use a loC4ban Ci th push me%hanism. 6he =uintessential e<ample o$ this is C2>M, the Clou 4to4>evi%e Messaging system, available $or An roi 2.2 an neCer. 6his servi%e $rom 9oogle alloCs your appli%ation to subs%ribe to push noti$i%ations sent out by your server. 6hose noti$i%ations are elivere asyn%hronously to the evi%e by Cay o$ 9oogle8s oCn servers, using a long4live so%ket %onne%tion. All you o is register a Broadca"t'ecei$er to re%eive the noti$i%ations an o something Cith them.
89

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Being "marter About Ban#+i#th

(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

Thu%8nails and Tiles


A general rule o$ thumb is* on8t oCnloa it until you really nee it. #ometimes, you o not knoC i$ you really nee a parti%ular item until something happens in the ".. 6ake a !i"tView isplaying thumbnails o$ album %overs $or a musi% app. Assuming the album %overs are not store lo%ally, you Cill nee to oCnloa them $or isplay. )oCever, Chi%h %overs you nee varies base upon s%rolling. >oCnloa ing a high4resolution album %over that might get tosse in a matter o$ millise%on s &a$ter an e<pensive res%ale to $it a thumbnail4siIe spa%e' is a Caste o$ ban Ci th. .n this %ase, either the album %overs are something you %ontrol on the server si e, or they are not. .$ they are, you %an have the server prepare thumbnails o$ the %overs, store at a spot that the app %an knoC about &e.g., ...4co$er.jpg it is ...4t-umbnail.jpg'. 6he app %an then oCnloa thumbnails on the $ly an only grab the $ull4resolution %over i$ nee e &e.g., user %li%ks on the album to bring up a etail s%reen'. .$ you o not %ontrol
9:

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Being "marter About Ban#+i#th

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 built4in 6Citter app that the user uninstall

oes not like, but %annot

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

Being "marter About Ban#+i#th

.$ 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

Being "marter About Ban#+i#th

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

Being "marter About Ban#+i#th

(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

Being "marter About Ban#+i#th

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.

Driven 8 &ther 1sage


.$ your netCork .M+ is part o$ a $oregroun appli%ation, one presumes that you are the most important thing in the user8s li$e right noC. +r, at least, the most important thing on the user8s phone right noC. )en%e, Chat other appli%ations might Cant to o Cith the .nternet %onne%tion is not a maHor %on%ern. .$, hoCever, your netCork .M+ is part o$ a ba%kgroun operation, it might be ni%e to try to avoi oing things that might upset the user. .$ the user is Cat%hing streaming vi eo or is on a ,+.! %all or otherCise is aCare o$ ban Ci th %hanges, the ban Ci th you use might impa%t the user in Cays that the user Cill not appre%iate very mu%h. 6his is unlikely to be a big problem $or small operations &e.g., oCnloa ing a 1F/ @#+0 $ile', but larger operations &e.g., oCnloa ing a EM/ po %ast' might be more noti%eable. ?ou %an use Traffic#tat" to help here. /e$ore oing the a%tual netCork .M+, grab the %urrent tra$$i% ata, Cait a %ouple o$ se%on s, an %ompare the latest to the previous values. .$ little to no ban Ci th Cas %onsume uring that perio , assume it is sa$e an go ahea an o your Cork. .$, hoCever, a bun%h o$ ban Ci th Cas %onsume , you might Cant to %onsi er*

#kipping this polling %y%le an trying again later, or

95

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Being "marter About Ban#+i#th

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

PART III Memory Performance

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 @

Issues +ith Aemor!

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

Issues +ith Aemor!

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.

WarningB Contains Graphic Images


)oCever, the most likely %ulprit $or 3ut3f+emor*/rror messages are bitmaps. /itmaps take up a remarkable amount o$ heap spa%e. >evelopers o$ten look at the siIe o$ a @!A9 $ile an think that Koh, Cell, that8s only a han $ul o$ F/K, Cithout taking into a%%ount*
-::

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

Issues +ith Aemor!

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

Issues +ith Aemor!

In Too ,eep &on the "tack)


)eap, hoCever, is not the only possible sour%e o$ memory errors. .t is also possible to get an #tack3$erflow/rror, in i%ating that you have run out o$ sta%k spa%e &or possibly that the lea ing An roi eveloper support resour%e is oCn $or maintenan%e'. .n sta%k4base programming languages like @ava, ea%h time you %all a metho , some sta%k spa%e is %onsume . While metho parameters are obHe%ts that live on the heap, the parameter re$eren%es are store on the sta%k, as is in$ormation about the metho being invoke . Re$eren%es to lo%al ata members to the metho or blo%ks insi e o$ it are also store on the sta%k. #in%e these re$eren%es only take up T- bytes ea%h, you Coul think it might take a minor eternity to run out o$ sta%k spa%e. )oCever, the main appli%ation threa in your An roi appli%ation has an 3F/ sta%k, Chi%h means you %an run out o$ sta%k spa%e Cith only a %ouple o$ thousan obHe%ts on it. Aven still, it Coul take hun re s an hun re s o$ neste metho invo%ations to put a %ouple o$ thousan obHe%ts onto the sta%k. .n normal programming, you might only en%ounter this Cith a runaCay bit o$ re%ursion, in Chi%h %ase no amount o$ sta%k Coul save you. )oCever, An roi 9".s are $airly sta%k4 riven. ?ou %an run out o$ sta%k spa%e i$ your ". be%omes too %omple<. More spe%i$i%ally, you might run out o$ sta%k spa%e i$ your vieC hierar%hy J $rom the root %ontainer o$ the An roi Cin oC to the Ci gets insi e o$ the %ontainers insi e o$ your roCs insi e o$ your !i"tView insi e o$ your Tab&o"t J gets too eep. A epth o$ 1E or so makes you very likely to run out o$ sta%k spa%e someChere along the line. #o i$ you get the sta%k4spa%e e<%eption an the sta%k tra%e seems to be all in An oi ". ren ering %o e, your vieC hierar%hy is probably too %omple<. .n this part o$ the book, Ce Cill e<amine hoC to measure your vieC hierar%hy epth an Cays o$ trying to simpli$y it.

-:(

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

CHAPTER 1A

$ocus @nB AAT

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

$ocus @nB AAT

#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

$ocus @nB AAT

.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*

$igure -'0 The icon use# for the G,ump

PD@$ $ileG toolbar button

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

$ocus @nB AAT

"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'.

Automating 8eap Dumps in Testing


+ne problem Cith using dump&prof,ata() is that there is no logi%al reason to have that %o e in your pro u%tion app. (ortunately, you %an use it $rom a @"nit test suite that uses the An roi instrumentation $rameCork. )oCever, the main proHe%t, not the test proHe%t, is the one that nee s .'%T/0/1T/'2 !0#T3' G/ J Cith lu%k, your app nee s this permission anyCay. 6he problem then be%omes a matter o$ $iguring out Chere in the @"nit test suite to %all dump&prof,ata(). +ne strategy is simply to a it to spe%i$i% test metho s or test %ases, i$ you Cant to have a ump at spe%i$i% points. .$, hoCever, you Cant a ump at the en o$ the %omplete battery o$ tests, you Cill nee to %reate your oCn test runner. (or e<ample, in + T4#pinner" in the book8s sour%e %o e, you Cill $in a near4 i enti%al %lone o$ the same proHe%t $rom 6he /usy Co er8s 9ui e to A van%e An roi >evelopment. .t simply runs through a patheti% little test suite $or an app that isplays %onta%t ata in a !i"tView, riven by a #pinner to sele%t Chat ata you Cant to see. 6he augmente version o$ this proHe%t a ump the heap at the en o$ the run* s an &profTe"t'unner that Cill

-:6

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

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

$ocus @nB AAT

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.

Basic AAT @peration


+n%e you have MA6 installe an you have obtaine a heap ump, you %an start oing some analysis.

-:8

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

!oading ,our Du%p


.$ you use the >>M# perspe%tive in A%lipse to %reate the heap ump, it shoul automati%ally pop you into MA6*

$igure -50 The AAT 3clipse perspective= as initiall! opene#

.$ 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

$ocus @nB AAT

$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.

"inding ,our &82ects


.$ you Cant to see i$ instan%es o$ your oCn %lasses are being kept in memory espite garbage %olle%tion, you %an sear%h $or obHe%ts base upon a regular e<pression on the $ully4=uali$ie %lass name. +ne Cay to a%%ess this is via the )istogram, rea%hable via a link in the +vervieC8s A%tions area or via a toolbar button*

--:

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

$igure -70 The icon use# for the

istogram toolbar button

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

$ocus @nB AAT

$igure -80 The

istogram tab insi#e the AAT 3clipse perspective

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

$ocus @nB AAT

$igure -90 A filtere# histogram= sho+ing com0commons+are0H obEects

)ere, Ce see one instan%e o$ a com.common"ware %lass is still lurking aroun a heap ump.

/etting :ac* to ,our Roots


)oCever, Hust be%ause Ce see an obHe%t in MA6 oes not ne%essarily mean that is has been leake . (or e<ample, this is an a%tivity J Hust looking at the above s%reenshot oes not in i%ate Chether that a%tivity Cas in the $oregroun , Cas in the ba%kgroun $or normal reasons, or is a%tually leake . 6o help etermine Chat is keeping the obHe%t in memory, you Cill nee to tra%e ba%k to the K9C rootsK J the obHe%ts that are preventing our a%tivity $rom being garbage %olle%te . 6o o this, you Cill right4%li%k over the obHe%t in =uestion an %hoose the K9C RootsK %onte<t menu %hoi%e &in the )istogram, it is KMerge #hortest !aths to 9C RootsK'. 6his Cill usually bring up a $lyout sub4menu Chere you %an $urther %onstrain Chat is reporte as a root*

--4

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

$igure (:0 A filtere# histogram= sho+ing com0commons+are0H obEects

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 *

$igure (-0 The GC roots hol#ing onto an activit!

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

$ocus @nB AAT

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/.

Identi7 ing What Else is "loating Around


6his helps us $in Chere your oCn obHe%ts are being leake . What happens i$ you are leaking other things, thoughD +ne possibility is to e<amine the rest o$ the )istogram tab, as it Cill point out the %lasses &an primitives' that have the most outstan ing instan%es or hol the most aggregate shalloC heap. .$ you applie a regular e<pression, you %an %li%k on the regular e<pression an elete it to return to the non4 $iltere roster. 6he )istogram ten s to report a lot o$ primitives &e.g., c-arHI', an it Cill take some e<perien%e to learn Chat is stan ar An roi appli%ation KnoiseK an Chat might represent problems. Another Cay to $in leaks is to e<amine the K ominator treeK. 6he term K ominator treeK %omes $rom graph theory J obHe%t A K ominatesK obHe%t / i$ the only paths to get to / go through A. .n MA6, the ominator tree Cill bubble up those obHe%ts Chose retaine heap J the total memory the obHe%t is responsible $or, in%lu ing obHe%ts it links to J are high. +r, as MA6 es%ribes it, it lists Kthe biggest obHe%tsK. 6o get to the ominator tree, you %an %li%k its link on the +vervieC tab, or you %an %li%k the %orrespon ing toolbar button*

$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

$ocus @nB AAT

6his Cill open up another tab in the same tool, shoCing Kthe biggest obHe%tsK by retaine heap*

$igure (40 The AAT ,ominator Tree tab

?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.

"ome *eaks an# Their AAT Anal!sis


Let8s noC take a look at some %ommon leak s%enarios in An roi an see hoC Ce $in out Chether Ce have a leak an Chat is %ausing it. All o$ the proHe%ts emonstrate beloC are in the + T ire%tory o$ the book8s sour%e %o e.

--6

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

Widget in #tatic Data $e%8er


6he s%reen shots $rom above are mostly taken $rom the + T4#tatic.idget sample proHe%t, Chere Ce o something naughty*
package com.common"ware.android.tuning.mat: import android.app. cti$it*: import android.o".Bundle: import android.$iew.View: public cla"" #tatic.idget cti$it* extend" OSuppressWarnings(9unu"ed9) "tatic pri$ate View do2ot,oT-i"(lea"e: 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): > > 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

$ocus @nB AAT

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(): > >

)ere, i$ Ce $ilter on com.common"ware in the )istogram, Ce see tCo entries*

$igure ('0 The *eake#Threa#Activit!

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*

$igure (50 The GC roots for *eake#Threa#Activit!

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

$ocus @nB AAT

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

All #orts o7 :ugs


Let8s noC e<ample + T4'andom pp3fCrap. 6his is a variation on an e<ample $rom 6he /usy Co er8s 9ui e to An roi >evelopment, shoCing using a boun servi%e that %onne%ts to a Web servi%e J in this %ase, the "# 0ational Weather #ervi%e. .n this mo i$ie version, a number o$ leak4relate bugs Cere intro u%e .

-ea&s 'ia Configuration Changes


6he .eat-er,emo a%tivity implements on'etain2onConfiguration%n"tance(), returning a #tate obHe%t. #tate is an inner %lass o$ .eat-er,emo, but not a stati% inner %lass. 6his is not a goo i ea. When you sear%h the )istogram $or com.common"ware a$ter loa ing a Ceather $ore%ast &e.g., run the app an use >>M# to push over a lo%ation $i<' an rotating the s%reen, you see that there are tCo instan%es o$ .eat-er,emo $loating aroun the heap*

--9

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

$igure (60 The com0commons+are obEects in the Dan#omApp@fCrap heap

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*

$igure (70 The incoming references for one Weather,emo instance

-(:

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB AAT

$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

$ocus @nB AAT

-ea&s from %nregistered S"stem -isteners


We also see $rom our $iltere )istogram that Ce have tCo retaine instan%es o$ the Y1 inner %lass. >isplaying in%oming re$eren%es to those obHe%ts shoCs us that those are the !ocation!i"tener obHe%ts Ce are using to get our 9!# $i<es*

$igure (90 The incoming references for the Weather,emoI- instances

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

$ocus @nB AAT

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.

What $AT WonBt Tell ,ou


MA6 is not a universal solution. .t may not tell you o$ all possible leaks. (or e<ample, i$ you bin to a servi%e, the #er$iceConnection obHe%t you %reate is hel onto, in ire%tly, by the +# itsel$. 6hat is hoC you %an use the #er$iceConnection to unbin $rom the servi%e later on. )oCever, i$ you e<amine MA6, you Cill see no evi en%e o$ this, as MA6 is limite to e<amining your own pro%ess an %annot report about re$eren%es that are triggere by other pro%esses. MA6 also Cill not report anything that is part o$ the native heap &i.e., Chat you get Cith a C malloc() %all' J it only reports on the >alvik heap. )en%e, MA6 Cill not re$le%t the a%tual memory %onsumption o$ bitmap images on 9ingerbrea an earlier environments. ?ou may Cish to o some testing o$ your app on )oney%omb, not Hust $or any tablet support you may o$$er, but to get more %omplete results $rom MA6.

-(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

PART IV Battery Performance

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

Issues +ith Batter! *ife

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

Issues +ith Batter! *ife

.ouFre Getting Blame#


"sers, $or better or Corse, have limite ability to etermine Chat is responsible $or raining the battery o$ their phone. 6heir O1 tool $or this is the K!oCer "sage #ummaryK s%reen in the #ettings app, sometimes re$erre to as the Kbattery blame s%reenK.

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

Issues +ith Batter! *ife

"tretching @ut the *ast mWh


#ometimes, Chat the user Cants your app to o in one %ase is not Chat the user Cants your app to o in other %ases. #erious poCer4 raining might be reserve $or Chen the evi%e is plugge in, or Chen the evi%e has at least su%h4an 4so poCer remaining. 6he user may value the last milliCatt4hours &mWh' more than others an Cant your appli%ation to use less poCer in those %ir%umstan%es. )en%e, i$ your appli%ation polls the .nternet, you might o$$er a $eature to poll less $re=uently, or perhaps not at all, Chen poCer is loC. .$ your appli%ation uses 9!# to $in a lo%ation &e.g., automati% K%he%k4insK to so%ial netCorks like (ours=uare', you might o$$er to skip su%h a%tions Chen the battery is loC. ?0u might Cant to signal to the user Chen the battery gets loC uring playba%k o$ a vi eo, or uring the game they are in. An so on. 6his part o$ the book Cill help you i enti$y Chen the battery is loC an strategies $or making use o$ that in$ormation.

-(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

$ocus @nB A,P an# Trepn

?ou %an measure poCer rain in one o$ tCo Cays*

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.

What Are .ou Talking AboutJ


.t is very likely that even seasone An roi evelopers Cill have never hear o$ M>! or 6repn. ?ou Cill not $in an M>! in your lo%al ele%troni%s store. ?ou Cill not even $in them on e/ay &most o$ the time'. An sin%e
-4-

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB A,P an# Trepn

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

$ocus @nB A,P an# Trepn

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$.

The :ig Pro8le%+ Cost


6he M>! M#M3550, at the time o$ this Criting, runs nearly Y1,-00. 6his means that $eC An roi appli%ation evelopers Cill have ire%t han s4on a%%ess to the M>!. A previous version o$ the M>! also ha issues Cith the pur%hase agreement you ha to abi e by Chen obtaining an M>! $rom /#N"ARA &Nual%omm8s retailerM$ront4line support $irm $or the M>!'. (or e<ample, the pur%hase agreement Coul have $orbi en this %hapter $rom being publishe , as it in%lu es results $rom running tests on the M>!. )oCever, the pur%hase agreement $or the M#M3550 M>! is more reasonable.

Dunning Trepn Tests


Measuring your poCer %onsumption using 6repn is $airly straight$orCar , parti%ularly $or simple %ases... Cith one big limitation. (irst, you Cill nee to get your app on the M>!. ?ou may even Cish to run the app on%e on the M>! J i$ your %on%erns are poCer %onsumption over the long haul, getting all o$ your app initialiIation logi% one be$ore you start measuring poCer is probably a goo move. 0e<t, run the K6repn !ro$ilerK appli%ation on the M>!, $oun laun%her like any other a%tivity. in the

-44

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB A,P an# Trepn

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;

Decor#ing Application "tates


6he problem is, 6repn oes not intrinsi%ally knoC mu%h about your appli%ation. .t is simply re%or ing poCer usage Chile your appli%ation is running. 6repn has no Cay o$ knoCing Chen %ertain $eatures o$ your app are use or %ertain %al%ulations are run. "nless you tell it. ?ou %an sen a broa %ast .ntent that 6repn Cill pi%k up, in i%ating Chat Kappli%ation stateK your app is noC in. )ere, an Kappli%ation stateK is simply
-4'

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

$ocus @nB A,P an# Trepn

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):

?ou nee a%tion,

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

$ocus @nB A,P an# Trepn

3xamining Trepn Desults


?ou have tCo Cays to look at the ata that 6repn %olle%ts. 6here is an on4 evi%e "., integrate as part o$ the 6repn appli%ation. +r, you %an grab the raC ata an per$orm your oCn o$$line analysis using your %hoi%e o$ tools.

&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

$ocus @nB A,P an# Trepn

$igure 4:0 3xternal storage on an A,P= sho+ing save# sessions

(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

$ocus @nB A,P an# Trepn

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

$ocus @nB A,P an# Trepn

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)

@ther Po+er Aeasurement @ptions

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

@ther Po+er Aeasurement @ptions

!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*

$igure 4-0 The Po+erTutor main activit!

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

@ther Po+er Aeasurement @ptions

$igure 4(0 The Po+erTutor application roster

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

@ther Po+er Aeasurement @ptions

$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

@ther Po+er Aeasurement @ptions

$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

Batter! "creen in "ettings Application


+$ %ourse, Chat evelopers ten to $o%us on most Cith poCer is the battery %onsumption s%reen in the #ettings appli%ation*

-'5

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

@ther Po+er Aeasurement @ptions

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

@ther Po+er Aeasurement @ptions

(%, 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 ?

(...and lot" more...)

an per4pro%ess in$ormation &here, shoCing poCer use itsel$'*


CF??XTQ .ake lock windowQ X" UFm" window (F time") realtime (roc edu.umic-.(owerTutorQ C(MQ FF" UX?m" u"r ; =" XJ?m" krn F proc "tart" pk edu.umic-.(owerTutorQ #er$ice edu.umic-.(owerTutor."er$ice.M+!ogger#er$iceQ Created forQ =m =" UX?m" uptime #tart"Q FD launc-e"Q F

by !oCer6utor

-'7

This document is licensed for Ateneo Android's exclusive use by CommonsWare, LLC

@ther Po+er Aeasurement @ptions

.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

S-ar putea să vă placă și