The Busy Coder's Guide to Android Development

by Mark L. Murphy

The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © 2008 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* +ul 2008* ,ersion -.0 .#/0* 12830318-42803031 relate tra e ress are

5he CommonsWare name an logo, 6/usy Co er7s 8ui e9, an tra emarks o$ CommonsWare, LLC.

All other tra emarks re$eren%e in this book are tra emarks o$ their respe%tive $irms. 5he publisher an author&s' assume no responsibility $or errors or omissions or $or amages resulting $rom the use o$ the in$ormation %ontaine herein.

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

Table of Contents

Welcome to the Warescription!..................................................................................xiii Preface..........................................................................................................................xv Wel%ome to the /ook:...........................................................................................................;v !rere<uisites..........................................................................................................................;v Wares%ription.......................................................................................................................;vi /ook /ug /ounty.................................................................................................................;vii #our%e Co e Li%ense..........................................................................................................;viii Creative Commons an the (our3to3(ree &=2(' 8uarantee............................................;viii The Bi Picture................................................................................................................! What An roi s Are Ma e >$.................................................................................................? A%tivities...........................................................................................................................? Content !rovi ers...........................................................................................................= .ntents..............................................................................................................................= #ervi%es.............................................................................................................................= #tu$$ At @our Aisposal.............................................................................................................B #torage..............................................................................................................................B 0etCork............................................................................................................................B Multime ia.......................................................................................................................B 8!#...................................................................................................................................B !hone #ervi%es.................................................................................................................4 Pro"ect #tructure............................................................................................................$ Root Contents..........................................................................................................................2 5he #Ceat >$$ @our /roC.......................................................................................................8
iii
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

An 0oC, 5he Rest o$ the #tory.............................................................................................8 What @ou 8et >ut >$ .t.........................................................................................................1 %nside the &anifest........................................................................................................!! .n 5he /eginning, 5here Was the Root, An .t Was 8oo .................................................-!ermissions, .nstrumentations, an Appli%ations &>h, My:'.............................................-2 @our Appli%ation Aoes #omething, RightD..........................................................................-? Creatin a #'eleton Application...................................................................................!$ /egin at the /eginning...........................................................................................................-2 5he A%tivity............................................................................................................................-8 Aisse%ting the A%tivity...........................................................................................................-1 /uil ing an Running the A%tivity.......................................................................................2(sin )&*+Based *ayouts............................................................................................,What .s an EML3/ase LayoutD...........................................................................................2? Why "se EML3/ase LayoutsD............................................................................................2= >F, #o What Aoes .t Look LikeD..........................................................................................2B What7s With the G #ignsD....................................................................................................24 An We Atta%h 5hese to the +ava...)oCD...........................................................................24 5he Rest o$ the #tory.............................................................................................................22 .mployin Basic Wid ets.............................................................................................,/ Assigning Labels....................................................................................................................21 /utton, /utton, Who7s 8ot the /uttonD..............................................................................?0 (leeting .mages......................................................................................................................?(iel s o$ 8reen. >r >ther Colors..........................................................................................?+ust Another /o; to Che%k....................................................................................................?= 5urn the Ra io "p.................................................................................................................?2 .t7s Huite a ,ieC....................................................................................................................?1 "se$ul !roperties...........................................................................................................?1 "se$ul Metho s..............................................................................................................?1 Wor'in 0ith Containers.............................................................................................1! 5hinking Linearly..................................................................................................................=2 Con%epts an !roperties...............................................................................................=2 I;ample..........................................................................................................................=B All 5hings Are Relative.........................................................................................................B0

iv
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Con%epts an !roperties...............................................................................................B0 I;ample..........................................................................................................................B? 5abula Rasa............................................................................................................................B4 Con%epts an !roperties...............................................................................................B4 I;ample..........................................................................................................................B1 #%rollCork..............................................................................................................................40 (sin #election Wid ets...............................................................................................23 A apting to the Cir%umstan%es............................................................................................4B "sing ArrayA apter......................................................................................................44 >ther Fey A apters.......................................................................................................42 Lists o$ 0aughty an 0i%e....................................................................................................48 #pin Control...........................................................................................................................20 8ri @our Lions &>r #omething Like 5hat...'.....................................................................2= (iel s* 0oC With ?BJ Less 5yping:.....................................................................................28 8alleries, 8ive >r 5ake 5he Art...........................................................................................82 .mployin 4ancy Wid ets and Containers..................................................................5!i%k an Choose....................................................................................................................8? 5ime Feeps (loCing Like a River.........................................................................................88 Making !rogress....................................................................................................................81 !utting .t >n My 5ab...........................................................................................................10 5he !ie%es.......................................................................................................................15he . iosyn%rasies..........................................................................................................1Wiring .t 5ogether........................................................................................................1? >ther Containers o$ 0ote.....................................................................................................14 Applyin &enus............................................................................................................/$ (lavors o$ Menu.....................................................................................................................12 Menus o$ >ptions.................................................................................................................18 Menus in Conte;t................................................................................................................-00 5aking a !eek.......................................................................................................................-02 .m6eddin the We67it Bro0ser................................................................................!8$ A /roCser, Writ #mall.........................................................................................................-02 Loa ing .t "p.......................................................................................................................-01 0avigating the Waters..........................................................................................................---

v
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Intertaining the Client.........................................................................................................--#ettings, !re$eren%es, an >ptions &>h, My:'....................................................................--= #ho0in Pop+(p &essa es..........................................................................................!!$ Raising 5oasts........................................................................................................................--2 Alert: Alert:............................................................................................................................--8 Che%king 5hem >ut.............................................................................................................--1 Dealin 0ith Threads..................................................................................................!,8etting 5hrough the )an lers............................................................................................-2? Messages.......................................................................................................................-2= Runnables.....................................................................................................................-22 Running .n !la%e..................................................................................................................-22 "tilities &An . Aon7t Mean Water Works'.......................................................................-28 An 0oC, 5he Caveats........................................................................................................-28 9andlin Activity *ifecycle .vents..............................................................................!-! #%hroe inger7s A%tivity.........................................................................................................-?Li$e, Aeath, an @our A%tivity.............................................................................................-?2 onCreate&' an onComplete5haC&'............................................................................-?2 on#tart&', onRestart&', an onResume&'.....................................................................-?? on!ause&', on(reeKe&', on#top&', an onAestroy&'...................................................-?= (sin Preferences........................................................................................................!-$ 8etting What @ou Want......................................................................................................-?2 #tating @our !re$eren%e.......................................................................................................-?8 A !re$eren%e (or A%tion......................................................................................................-?8 Accessin 4iles.............................................................................................................!1@ou An 5he )orse @ou Ro e .n >n.................................................................................-=? Rea in7 7n Writin7.................................................................................................................-=2 Wor'in 0ith :esources..............................................................................................!3! 5he Resour%e Lineup............................................................................................................-B#tring 5heory........................................................................................................................-B2 !lain #trings..................................................................................................................-B2 #tring (ormats..............................................................................................................-B? #tyle 5e;t.....................................................................................................................-B? #tyle (ormats..............................................................................................................-B=

vi
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

8ot the !i%tureD...................................................................................................................-B8 EML* 5he Resour%e Way.....................................................................................................-40 Mis%ellaneous ,alues...........................................................................................................-4? Aimensions...................................................................................................................-4? Colors............................................................................................................................-4= Arrays............................................................................................................................-4B Ai$$erent #trokes $or Ai$$erent (olks..................................................................................-44 &ana in and Accessin *ocal Data6ases...................................................................!$! A Hui%k #HLite !rimer........................................................................................................-22 #tart at the /eginning..........................................................................................................-2? #etting the 5able..................................................................................................................-2= Makin7 Aata..........................................................................................................................-2= What 8oes Aroun , Comes Aroun ...................................................................................-24 RaC Hueries..................................................................................................................-24 Regular Hueries............................................................................................................-22 /uil ing Cith /uil ers.................................................................................................-22 "sing Cursors...............................................................................................................-21 Change $or the #ake o$ Change...................................................................................-21 Making @our >Cn Cursors..........................................................................................-80 Aata, Aata, IveryChere.......................................................................................................-80 *evera in ;ava *i6raries............................................................................................!55he >uter Limits..................................................................................................................-8? Ants an +ars........................................................................................................................-8= Communicatin via the %nternet................................................................................!5$ RI#5 an Rela;ation............................................................................................................-82 )55! >perations via Apa%he Commons...................................................................-88 !arsing Responses........................................................................................................-10 #tu$$ 5o Consi er.........................................................................................................-12 Imail over +ava.....................................................................................................................-1? Creatin %ntent 4ilters................................................................................................!// What7s @our .ntentD............................................................................................................200 !ie%es o$ .ntents..........................................................................................................200 #to%k >ptions...............................................................................................................20-

vii
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

.ntent Routing.............................................................................................................202 #tating @our .ntent&ions'....................................................................................................20? 0arroC Re%eivers.................................................................................................................20B *aunchin Activities and #u6+Activities.....................................................................,8$ !eers an #ubs.....................................................................................................................208 #tart 7Im "p........................................................................................................................208 Make an .ntent............................................................................................................201 Make the Call...............................................................................................................201 4indin Availa6le Actions via %ntrospection...............................................................,!3 !i%k 7Im................................................................................................................................2-4 A aptable A apters.............................................................................................................220 Woul @ou Like to #ee the MenuD.....................................................................................22? Asking Aroun .....................................................................................................................22B (sin a Content Provider...........................................................................................,,/ !ie%es o$ Me.........................................................................................................................221 8etting a )an le.................................................................................................................2?0 Makin7 Hueries.....................................................................................................................2?A apting to the Cir%umstan%es..........................................................................................2?? Aoing .t /y )an .................................................................................................................2?B !osition.........................................................................................................................2?B 8etting !roperties.......................................................................................................2?4 #etting !roperties........................................................................................................2?2 8ive an 5ake......................................................................................................................2?8 /eCare o$ the /L>/:...........................................................................................................2?1 Buildin a Content Provider.......................................................................................,1! (irst, #ome Aisse%tion.........................................................................................................2=0e;t, #ome 5yping..............................................................................................................2=2 #tep L-* Create a !rovi er Class..........................................................................................2=? Content!rovi er..........................................................................................................2=? AatabaseContent!rovi er...........................................................................................2B2 #tep L2* #upply a "ri...........................................................................................................2B2 #tep L?* Ae%lare the !roperties..........................................................................................2B2 #tep L=* "p ate the Mani$est.............................................................................................2B?

viii
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

............................2B1 In$or%ing !ermissions via the Mani$est...................................................24= When ..........................................24= #ervi%e Cith Class................................// 5he /are /ones...............................................................................................................................................................288 (in ing @oursel$.......................................244 Write the A....................................................5esting....................................................................................288 >n the Move................................2B= :e<uestin and :e<uirin Permissions........................................................................................................................220 Where7s the RemoteD.................................................................................................................................242 ....................................................................................................................................................28Accessin *ocation+Based #ervices..................................nter$a%e.........224 Manual 5ransmission......................................................................242 Creatin a #ervice................211 ix Subscribe to updates at http://commonsware............................................................................................22= Re<uest $or #ervi%e...................................................................................................................................................................0 License Edition .............................................................mplement the ..........212 5esting..........2B8 )alt: Who 8oes 5hereD............................ May ...240 In$or%ing !ermissions IlseChere..........................................................!C Atta%ks:..........................248 Mani$est Aestiny...........................................................................................................................................................................................................................................................................................................280 ................................................com Special Creative Commons BY-SA 3........................................................................224 Alertin (sers =ia >otifications....................................................................................................................................................................................24May ....214 &appin 0ith &ap=ie0 and &apActivity..........................................................................................................................................................28etting /uKKe ............221 )ar Care 0oti$i%ations........$/oun $or #u%%ess...................................D....................................................... #ee @our Ao%umentsD..........................................................................................................................5$ Lo%ation !rovi ers* 5hey FnoC Where @ou7re )i ing..........................................................................................................................................................................................................................................................................................................224 !rometheus "nboun .............................................................................%ons.....................................................0oti$y3>n3Change #upport................................................AL..............................212 Are We 5here @etD Are We 5here @etD Are We 5here @etD.......................................................28Letting @our !resen%e /e (elt........................................22%nvo'in a #ervice.............................................$/ 5ypes o$ !estering...................................3$ Mother......................................................................................

......................................................................................................................................................................................com Special Creative Commons BY-SA 3.....................................................................................................................................?=2 Aemo Lo%ation !rovi er.........................................................................................................................................................................?0Moom................................??B Cra$t the #ear%h A%tivity........?BB x Subscribe to updates at http://commonsware..............mage Cith #ample 5our.................................?B0 Con$iguration A%tivity.....................................?08 )an ling #%reen 5aps...................................................................................................................................... (olloC Me........?-= Making 0oise.............?B= Map A%tivity..........................?29andlin Telephone Calls.....................................................................................t >ut.................................................................................................?02 >verlay Classes.......................................................................................?24 #earchin 0ith #earch&ana er............................................?0? 5ra$$i% an 5errain..................?24 @ou Make the Call:..................-!8et @our Me ia >n..........................................................................................................................................................................................?=8 Running 5our.................................................................?0? (olloC @ou.........................................................................................................................?B2 Cue #heet A%tivity..................??4 "p ate the Mani$est...........?08 AraCing the >verlay....................................................................................................................t..............t..............................................................?=0 5ry .............?0Center.................0 License Edition .......................................................................................................................................................?-0 Playin &edia......................................................................................................................!hone........................................................?02 Reti%le.....................................................................................................................................-1$ .........................................................................................-.................... 0o......?=2 The Tour%t #ample Application............................................................................................................................................................................................................................................................................................................................................................................................................?=1 Main A%tivity.......................?=2 #A Car ....................................?-B Moving !i%tures..................................--)unting #eason...........................................................er%ising @our Control...............................................3 0o...................................................... 0o N 0ot 5hat ...............................................................................................................................................................................................................................................................................nstalling 5our.......................................................................?24 What7s >ur #tatusD...................................................I.........................................??? #ear%h @oursel$...................................?0B Layers "pon Layers........................................................

........................................................................................?B8 5our.....t7s A%tivities....................................................................................................................................................?42 )elpA%tivity..........................................................................................................................?B2 )elp A%tivity................................................................................................................................................................?40 Aata #torage...................................................................................................................t7s Content........5our "p ate A%tivity.........................................................com Special Creative Commons BY-SA 3................................?B1 5our.....0 License Edition ..........................................................?42 5ourI itA%tivity................ieCA%tivity..........................................................................................................................................................................?42 5our...............................t7s Mani$est.................................................................................?4Content !rovi er.............................................................................................................?4? 5ourMapA%tivity............?42 Con$igA%tivity..............................?42 5ourListA%tivity.......................................?45our.......................?48 xi Subscribe to updates at http://commonsware.........................................................................................................................................................?4Mo el Classes........................................................................

0 License Edition .com Special Creative Commons BY-SA 3.Subscribe to updates at http://commonsware.

but otherCise being %omplete.$ you Cork $or a $irm an Cish to have several employees have a%%ess.1.1 are Qrelease %an i atesQ $or the ne. Also. MaOor releases &-.Welcome to the Warescription! We hope you enOoy this ebook an its up ates N keep tabs on the Wares%ription $ee o$$ the CommonsWare site to learn Chen neC e itions o$ this book.com Special Creative Commons BY-SA 3.' are available in both print an ebookP minor releases &0. Ia%h Wares%ription ebook is li%ense $or the e.%om. $olloC a so$tCare3 style numbering system. are available.0. print an ebook. or other books in your Wares%ription. 2. enterprise Wares%riptions are available. bear in min that eventually this e ition o$ this title Cill be release un er a Creative Commons li%ense N more on this in the pre$a%e. et%. #ome notes $or Fin le users* xiii Subscribe to updates at http://commonsware.0.t maOor release.' are available in ebook $orm $or Wares%ription subs%ribers only.0 License Edition . +ust %onta%t us at enterpriseG%ommonsCare.. .-.%lusive use o$ its subs%riber an is tagge Cith the subs%ribers name. We ask that you not istribute these books. Remember that the CommonsWare Web site has errata an resour%es &e. et%. 0.g. +ust visit the Web page $or the book you are intereste in an $olloC the links. All e itions o$ CommonsWare titles. sour%e %o e' $or ea%h o$ our titles. la%king perhaps an in e. Releases en ing in .

0 License Edition .• • @ou may Cish to rop your $ont siKe to level 2 $or easier rea ing #our%e %o e listings are in%orporate as graphi%s so as to retain the monospa%e $ont. though this means the sour%e %o e listings o not honor %hanges in Fin le $ont siKe xiv Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

thanks $or your interest in this book: .$ you have not programme in +ava be$ore.Preface Welcome to the Book! 5hanks: 5hanks $or your interest in eveloping appli%ations $or An roi : . su%h as mobile evi%es. An roi is neC N at the time o$ this Criting. sin%erely hope you $in it use$ul an at least o%%asionally entertaining. you probably shoul <ui%k learn hoC that Corks be$ore attempting to ive into programming $or An roi . xv Subscribe to updates at http://commonsware. An roi programming is one using +ava synta. An . 5he more Ce o in that spa%e noC. there are no shipping An roi 3poCere evi%es N but it likely Cill rapi ly groC in importan%e ue to the siKe an s%ope o$ the >pen )an set Allian%e. the more that people Cill help invest in that spa%e to make it easier to buil more poCer$ul mobile appli%ations in the $uture.0 License Edition .$ you are intereste in programming $or An roi . .com Special Creative Commons BY-SA 3. plus a %lass library that resembles a subset o$ the +ava #I library &plus An roi 3spe%i$i% e. people Cill a%%ess .nternet3base servi%es using so3%alle Qnon3tra itionalQ means. most o$ all.tensions'. you Cill nee at least basi% un erstan ing o$ hoC to program in +ava.n%reasingly.. Prerequisites .

0 License Edition . Chen neC releases o$ the An roi #AF are ma e available. (rom time to time. Also. install.5he book oes not %over in any etail hoC to oCnloa or install the An roi evelopment tools.AI $lavor or the stan alone $lavor. 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. both short arti%les an not3yet3publishe neC titles. subs%ribers Cill also re%eive a%%ess to subs%riber3only online material. 5he ebook versions o$ all CommonsWare titles are available via an annual subs%ription N the Wares%ription.AI or not. Ia%h subs%riber gets personaliKe e itions o$ all e itions o$ ea%h title* both those mirroring printe e itions an in3betCeen up ates that are only available in ebook $orm. an test out the An roi evelopment tools $rom the An roi Web site be$ore trying any o$ the e. Warescription 5his book Cill be publishe both in print an in igital &ebook' $orm. your ebooks are never out o$ ate $or long. 5he Wares%ription entitles you. you %an e. this book Cill be <ui%kly up ate to be a%%urate Cith %hanges in the A!. an it is in goo %lean %on ition Cith no marks or sti%kers. (or e. $or the uration o$ your subs%ription. not Oust the one you are rea ing.s. to ebook $orms o$ all CommonsWare titles. CommonsWare o$$ers !A( an Fin leP other ebook $ormats Cill be a e base on interest an the openness o$ the $ormat. either the I%lipse . 5hat Cay.ample.amples liste in this book. though usually Cith a link ba%k to the pre%e ing se%tion o$ relevan%e. i$ you oCn a print %opy o$ a CommonsWare book. !resently.com Special Creative Commons BY-SA 3. xvi Subscribe to updates at http://commonsware. 5he material in the book shoul be relevant Chether you use the . visit the Wares%ription se%tion o$ the CommonsWare Web site. #ome %hapters may re$eren%e material in previous %hapters. 5he An roi Web site %overs this <uite ni%ely. @ou shoul oCnloa . .$ you are intereste in a Wares%ription.%hange that %opy $or a is%ount o$$ the Wares%ription pri%e.

@ou %an use that %oupon to get a neC Wares%ription. We appre%iate hearing about Qso$terQ issues as Cell.g.isting material sample appli%ations. in the environment es%ribe in the book (a%tual errors that %annot be open to interpretation • /y Quni<ueQ. or e. Ia%h book has an errata page on the CommonsWare Web siteP most knoCn problems Cill be liste there. or some ran om person you meet on the subCay. Ce mean ones not yet reporte . xvii Subscribe to updates at http://commonsware.isting Wares%ription. but Chere Ce $eel our interpretation is reasonable !la%es Chere you think Ce %oul a upon the e.com Special Creative Commons BY-SA 3. an Ce7ll give you a %oupon $or a si.3month Wares%ription as a bounty $or helping us eliver a better pro u%t. reneC an e.pan • • #amples that o not Cork ue to Qshi$ting san sQ o$ the un erlying environment &e. %olleague.. or give the %oupon to a $rien . Ce mean things like* • • 5ypographi%al errors #ample appli%ations that o not Cork as a vertise .s Cith neC releases o$ an #AF' )oCever.%om. su%h as* • !la%es Chere you think Ce are in error. %hange A!.Book Bug Bounty (in a problem in one o$ our booksD Let us knoC: /e the $irst to report a uni<ue %on%rete problem. /y Q%on%reteQ problem. Huestions about the bug bounty. those Qso$terQ issues o not <uali$y $or the $ormal bounty program. or problems you Cish to report $or bounty %onsi eration.0 License Edition . shoul be sent to bountyG%ommonsCare.

ea%h $our years $rom the publi%ation o$ that e ition or base on sales o$ that spe%i$i% e ition.. you %an use this prose $or non3 %ommer%ial purposes.000 %opies o$ the e ition have been sol .0 li%ense as o$ the $ourth anniversary o$ its publi%ation ate. Cat%h the CommonsWare Web site. xviii Subscribe to updates at http://commonsware.8!. as this e ition might be reli%ense sooner base on sales. or Chen =. Creative Commons and the !our"to"!ree #$%!& 'uarantee Ia%h CommonsWare book e ition Cill be available $or use un er the Creative Commons Attribution30on%ommer%ial3#hare Alike ?. >$ %ourse. Chi%hever %omes $irst. (or more etails on the Creative Commons Attribution30on%ommer%ial3 #hare Alike ?. starting $rom the time the e ition is publishe . visit the Creative Commons Web site. on%e $our years have elapse &perhaps sooner:'.Source Code icense 5he sour%e %o e samples shoCn in this book are available $or oCnloa $rom the CommonsWare Web site. 0ote that $uture e itions o$ this book Cill be%ome $ree on later ates. in %ase you have the esire to reuse any o$ it. 5his e ition o$ this book Cill be available un er the a$orementione Creative Commons li%ense on .0 License Edition . 5hat means that.0 li%ense. All o$ the An roi proOe%ts are li%ense un er the Apa%he 2.0 Li%ense. Releasing one e ition un er the Creative Commons li%ense oes not automati%ally release all e itions un er that li%ense.uly !? . neC Wares%riptions an reneCals Cill be %ounte as sales o$ this e ition.com Special Creative Commons BY-SA 3. (or the purposes o$ this guarantee. 5hat is our (our3to3(ree 8uarantee to our rea ers an the broa er %ommunity.

PART I – Core Concepts Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition .

Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

are small ( • Subscribe to updates at http://commonsware.perien%e in programming $or !AAs or phones has $elt the pain o$ phones simply being small in all sorts o$ imensions* • #%reens are small &you Con7t get %omments like. this has bene$its an raCba%ks. $or the most part.perien%e Cith an interesting te%hnology &An roi ' in a $ast3moving market segment &. Chi%h is alCays a goo thing.t messaging an to pro u%ts like Apple7s i!hone. or.. by an large. While the An roi te%hnology is being is%usse $or use in other areas &e.nternet servi%es over mobile evi%es ates ba%k to the mi 3-1107s an the )an hel Aevi%e Markup Language &)AML'.nternet3enable phones'. only in re%ent years have phones %apable o$ . %ar ashboar Q!CsQ'. )oCever. >n the plus si e.DQ' Feyboar s. %ir%a 2008.0 License Edition . 0oC. i$ they e.g.nternet a%%ess taken o$$. 5he problem %omes Chen you a%tually have to program the arn things.y. Corking on An roi appli%ations gives you e.com Special Creative Commons BY-SA 3.ist.nternet a%%ess evi%es are rapi ly gaining popularity. Cill be mobile phones.CHAPTER 1 The Big Picture An roi evi%es. Anyone Cith e.. #o. (or evelopers. you %an think o$ An roi as being use on phones. thanks to tren s like te. >$$ering . An roi 3style smartphones are se.. phones that %an serve as . Qis that a 2=3in%h LCA in your po%ket.

so long as it Cas Chat the evi%e manu$a%turer %hose an burne into the phone7s sili%on An so on • • • Moreover. i$$erent3behaving $rameCorks. are annoying &as anyone Cho has lost their stylus Cill tell you' or ine.a%t &large $ingers an Qmulti3tou%hQ LCAs are not a goo mi...0 License Edition .The Big Picture • !ointing evi%es. #imilarly..eriKon Wireless has been popular $or the past $eC years. su%h that your appli%ation oesn7t <uietly $a e to the ba%kgroun Chen a %all %omes in or nee s to be pla%e ..g.ist. What An roi tries to o is meet you hal$Cay* • @ou get a %ommonly3use programming language &+ava' Cith some %ommonly use libraries &e. Cith support $or tools you may be use to &I%lipse' % Subscribe to updates at http://commonsware. those same people Cill get irritate at you i$ your program QbreaksQ their phone* • • . or ba%k3en server pro%esses. an Q i$$erent than you7re use toQ limitations on Chat you %an o Cith your program. @ou Cin up Cith i$$erent3looking tools.by not Corking properly Cith the rest o$ the phone7s >#....' C!" spee an memory are tight %ompare to esktops an servers you may be use to @ou %an have any programming language an evelopment $rameCork you Cant.perien%e than eveloping esktop appli%ations. !eople Cith mobile phones ten to get very irritate Chen those phones on7t Cork. Chi%h is Chy the Q%an you hear me noCDQ a %ampaign $rom . some Apa%he Commons A!.s'.by tying up the C!" su%h that %alls %an7t be re%eive . eveloping programs $or a phone is a i$$erent e. su%h as by leaking memory like a sieve • )en%e. i$ they e. Web sites. appli%ations running on a phone have to eal Cith the $a%t that they7re on a phone.com Special Creative Commons BY-SA 3.by %rashing the phone7s operating system.

you are your oCn Corl . you are Qmaster o$ your oCn omainQ. but largely ignorant o$ any other program that may be running on the %omputer at the same time. Subscribe to updates at http://commonsware. su%h as using +A/C &or $rameCorks atop it' to %ommuni%ate Cith My#HL or another atabase.es N that are nee e .. . (rom your stan point. it is typi%ally through an A!. While it is possible $or a%tivities to not have a user inter$a%e. most likely your Qhea lessQ %o e Cill be pa%kage in the $orm o$ %ontent provi ers or servi%es.com Special Creative Commons BY-SA 3.0 License Edition .$ you o intera%t Cith other programs.The Big Picture • @ou get a $airly rigi an un%ommon $rameCork in Chi%h your programs nee to run so they %an be Qgoo %itiKensQ on the phone an not inter$ere Cith other programs or the operation o$ the phone itsel$ As you might e. mu%h o$ this book eals Cith that $rameCork an hoC you Crite programs that Cork Cithin its %on$ines an take a vantage o$ its %apabilities. an stru%ture to Activities 5he buil ing blo%k o$ the user inter$a%e is the activity. i$$erently. What )ndroids )re *ade +f When you Crite a esktop appli%ation. es%ribe beloC. @ou laun%h your main Cin oC an any %hil Cin oCs N like ialog bo. leveraging $eatures supporte by the operating system. . An roi has similar %on%epts. @ou %an think o$ an a%tivity as being the An roi analogue $or the Cin oC or ialog in a esktop appli%ation. but pa%kage make phones more %rash3resistant.pe%t.

@ou might use a servi%e $or %he%king $or up ates to an R## $ee .. 5he An roi evelopment mo el en%ourages you to make your oCn ata available to other appli%ations. on the other han .0 License Edition .g..The Big Picture Content Providers Content provi ers provi e a level o$ abstra%tion $or any ata store on the evi%e that is a%%essible by multiple appli%ations. to laun%h other a%tivities.g. or to play ba%k musi% even i$ the %ontrolling a%tivity is no longer operating. an intent re%eivers are all short3live an %an be shut oCn at any time. Intents . i$ nee e . an #A %ar Cas inserte '. or to let you knoC Chen spe%i$i% situations arise &e.com Special Creative Commons BY-SA 3. $ Subscribe to updates at http://commonsware. in epen ent o$ any a%tivity.g. Services A%tivities. $rom har Care state %hanges &e. an #M# message arrive '. 0ot only %an you respon to intents. to appli%ation events &e.ntents are system messages. %ontent provi ers. Chile maintaining %omplete %ontrol over hoC your ata gets a%%esse . but you %an %reate your oCn. are esigne to keep running. #ervi%es... running aroun the insi e o$ the evi%e. raise su%h3an 3so intent Chen the user gets Cithin -00 meters o$ this3an 3su%h lo%ation'.g. your a%tivity Cas laun%he $rom the evi%e7s main menu'. noti$ying appli%ations o$ various events. to in%oming ata &e. as Cell as your oCn N buil ing a %ontent provi er lets you o that.

or use the mi%rophone $or au io note3taking. you %an isplay maps or otherCise take a vantage o$ the lo%ation ata. GPS An roi evi%es Cill $re<uently have a%%ess to lo%ation provi ers.isposal Stor !e @ou %an pa%kage ata $iles Cith your appli%ation. take pi%tures Cith the %amera. $or atabases or $iles %ontaining user3entere or retrieve ata nee e by your appli%ation. $rom raC +ava so%kets all the Cay up to a built3in WebFit3base Web broCser Ci get you %an embe in your appli%ation. su%h as 8!#. su%h as i%ons or help $iles. An . through one %ommuni%ations me ium or another. While the spe%i$i%s may vary $rom evi%e to evi%e.nternet a%%ess at any level you Cish. you %an rea an Crite $iles on there as nee e . / Subscribe to updates at http://commonsware. %ultimedi An roi evi%es have the ability to play ba%k an re%or au io an vi eo.n turn.The Big Picture Stuff )t -our .com Special Creative Commons BY-SA 3. @ou %an take a vantage o$ the .0 License Edition . @ou also %an %arve out a small bit o$ spa%e on the evi%e itsel$. i$ the user supplies bulk storage.nternet3rea y. you %an <uery the evi%e to learn its %apabilities an then take a vantage o$ the multime ia %apabilities as you see $it. like an #A %ar . $or things that o not %hange. Chether that is to play ba%k musi%. "et#or$ An roi evi%es Cill generally be . su%h as tra%king a evi%e7s movements i$ the evi%e has been stolen. . that %an tell your appli%ations Chere the evi%e is on the $a%e o$ the Iarth.

sen an re%eive #M# messages. o$ %ourse. An roi evi%es are typi%ally phones.com Special Creative Commons BY-SA 3. 0 Subscribe to updates at http://commonsware.0 License Edition .The Big Picture Phone Services An . an everything else you e. alloCing your so$tCare to initiate %alls.pe%t $rom a mo ern bit o$ telephony te%hnology.

layouts. Chi%h hol res/. mu%h like any other +ava proOe%t. to help you make sense o$ it all.com Special Creative Commons BY-SA 3. servi%es.xml. 8". build. though. that get pa%kage Cith the %ompile +ava in the appli%ation assets/. parti%ularly $or the sample %o e re$eren%e in this book.g. • Chi%h hol other stati% $iles you Cish pa%kage Cith the appli%ation $or eployment onto the evi%e 3 Subscribe to updates at http://commonsware.CHAPTER & Pro1ect Structure 5he An roi buil system is organiKe aroun a spe%i$i% ire%tory tree stru%ture $or your An roi proOe%t.xml. N are being supplie by that appli%ation Chi%h is an Ant s%ript $or %ompiling the appli%ation an installing it on the evi%e bin/. )ere7s a <ui%k primer on the proOe%t stru%ture. you get $ive key items in the proOe%t7s root ire%tory* • AndroidManifest. via activityCreator..py'. are $airly uni<ue to An roi an Chat it all oes to prepare the a%tual appli%ation that Cill run on the evi%e or emulator. Chi%h is an EML $ile es%ribing the appli%ation being built an Chat %omponents N a%tivities. • • • • s the appli%ation on%e it is %ompile s the +ava sour%e %o e $or the appli%ation Chi%h hol s Qresour%esQ. 2oot Contents When you %reate a neC An roi proOe%t &e. et%. su%h as i%ons. 5he spe%i$i%s.0 License Edition . Chi%h hol src/. an the like.

android.. plus a stub Activity sub%lass representing your main a%tivity &e. 5he $irst time you %ompile the proOe%t &e.g. imensions.java &e.Pro1ect Structure The S4eat +ff -our Bro4 When you %reate the proOe%t &e. +!I8. in later %hapters o$ this book.. an the like res/xml/ $or other general3purpose EML $iles you Cish to ship We Cill %over all o$ these. o%%asionally. re$erring to a layout7s i enti$ier via R. @ou are Cel%ome to mo i$y this $ile an a others to the src/ tree as nee e to implement your appli%ation. @ou shoul not mo i$y R. com. an more.g..java'. you supplie the $ully3<uali$ie %lass name o$ the QmainQ a%tivity $or the appli%ation &e. src/com/commonsware/ android/SomeDemo. @ou Cill then $in that your proOe%t7s src/ tree alrea y has the namespa%e ire%tory tree in pla%e..py'. $ile o$ a%%ount in$ormation' res/values/ • • $or strings. out in the QmainQ a%tivity7s namespa%e ire%tory. via activityCreator. et%.java yoursel$.main'. letting the An roi tools han le it $or you. layout spe%i$i%ations $or general3purpose $iles &e. via ant'.commonsware. a C#. )nd 5o46 The 2est of the Story @ou Cill also $in that your proOe%t has a res/ ire%tory tree.g. in a prepro%esse $orm.g.' $or EML3base ". 7 Subscribe to updates at http://commonsware. 5his hol s Qresour%esQ N stati% $iles that are pa%kage along Cith your appli%ation. #ome o$ the sub ire%tories you Cill $in or %reate un er res/ in%lu e* • • • res/drawable/ res/layout/ res/raw/ $or images &!08. @ou Cill see throughout many o$ the samples Chere Ce re$eren%e things in R.0 License Edition .java.SomeDemo'..layout.g. 5his %ontains a number o$ %onstants tie to the various resour%es you pla%e out in the res/ ire%tory tree. the An roi buil %hain Cill %reate R.com Special Creative Commons BY-SA 3. either in their original $orm or.g..

the %ompile e ition o$ your resour%es &resources.arsc'.dex $ile.apk is the a%tual An roi appli%ation &Chere yourapp is the name o$ your appli%ation' 5he . the results go into the bin/ ire%tory un er your proOe%t root. 9 Subscribe to updates at http://commonsware.e%utable %reate $rom those %ompile bin/classes.Pro1ect Structure What -ou 'et +ut +f 8t When you %ompile your proOe%t &via ant or the .AI'.com Special Creative Commons BY-SA 3.xml $ile.! ar%hive %ontaining the .dex +ava %lasses • bin/yourapp. #pe%i$i%ally* • • bin/classes/ hol s the %ompile +ava %lasses hol s the e. any un3%ompile resour%es &su%h as Chat you put in res/raw/' an the AndroidManifest.0 License Edition .apk $ile is a M.

Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition .

the servi%es.CHAPTER ' 8nside the *anifest 5he $oun ation $or any An roi appli%ation is the mani$est $ile* AndroidManifest. you in i%ate Chi%h a%tivity &or a%tivities' shoul appear on the evi%e7s main menu &a. emo suite is over -.a. the service element Cill be es%ribe in greater etail in the %hapter on %reating servi%es.ample. 8n The Beginning6 There Was the 2oot6 )nd 8t Was 'ood 5he root o$ all mani$est $iles is. the auto3generate mani$est Cill probably Cork out $ine. Most o$ the interesting bits o$ the mani$est Cill be es%ribe in greater etail in the %hapters on their asso%iate An roi $eatures..ample. not surprisingly. Ce Oust nee to un erstan Chat the role o$ the mani$est is an its general overall %onstru%tion. the mani$est $ile $or the An roi A!.0 License Edition . @ou also in i%ate hoC these pie%es atta%h themselves to the overall An roi systemP $or e.000 lines long.k. )ere is Chere you e%lare Chat all is insi e your appli%ation N the a%tivities. (or e. @our pro u%tion An roi appli%ations Cill probably $all someChere in the mi le. laun%her'.xml in the root o$ your proOe%t. o$$ering a single a%tivity an nothing else. or perhaps re<uire a $eC minor mo i$i%ations. When you %reate your appli%ation. (or a simple appli%ation. a manifest element* (( Subscribe to updates at http://commonsware. (or noC. >n the other en o$ the spe%trum. an so on.com Special Creative Commons BY-SA 3. you Cill get a starter mani$est generate $or you.

ample. sin%e com.8nside the *anifest <manifest xmlns!android"#$ttp!//sc$emas.com/apk/res/android# packa%e"#com. Curiously. (or e. sti%k Cith their pattern. 5he biggest pie%e o$ in$ormation you nee to supply on the manifest element is the packa%e attribute &also %uriously not3namespa%e '..android.android. )oCever. more etails are $orth%oming in the %hapter on permissions permission • • elements. su%h as starting up a%tivities.android is e$ine as the appli%ation7s pa%kage. </manifest& 0ote the namespa%e e%laration.. to in i%ate %o e that shoul be invoke on key system events.Snicklefrit'.commonsware.0 License Edition . Permissions6 8nstrumentations6 and )pplica" tions #+h6 *y!& "n erneath the manifest element. to in i%ate Chat permissions your appli%ation Cill nee in or er to $un%tion properly N see the %hapter on permissions $or more etails elements. it7s manifest. so unless An roi %hanges. i$ you nee e to re$er to com. everyChere else in the mani$est $ile that nee s a %lass name.commonsware.g.commonsware.searc$#& . not the elements &e. the generate mani$ests only apply it on the attributes. you Cill $in * • uses(permission elements. you %an Oust substitute a lea ing ot as shorthan $or the pa%kage. not android!manifest'. 5hen. that pattern Corks. )ere.com Special Creative Commons BY-SA 3.android. $or the purposes o$ logging or monitoring instrumentation • an application element.Snicklefrit' in this mani$est shoCn above. you %oul Oust use . you %an provi e the name o$ the +ava pa%kage that Cill be %onsi ere the QbaseQ o$ your appli%ation. e$ining the guts o$ the appli%ation that the mani$est es%ribes (% Subscribe to updates at http://commonsware. to e%lare permissions that a%tivities or servi%es might re<uire other appli%ations hol in or er to use your appli%ation7s ata or logi% N again..

+A2/C3)R# /& </intent(filter& </activity& </application& </manifest& 5his element supplies android!name $or the %lass implementing the a%tivity./ow# android!label"#/ow#& <intent(filter& <action android!name"#android.ample.intent. an &$re<uently' an intent(filter %hil element es%ribing un er Chat %on itions this a%tivity (. an Chatnot that make up the bulk o$ the appli%ation itsel$.n the pre%e ing e.permission. you get a single activity element* <manifest xmlns!android"#$ttp!//sc$emas.com Special Creative Commons BY-SA 3.8nside the *anifest <manifest xmlns!android"#$ttp!//sc$emas./# /& <uses(permission android!name"#android.. android!label $or the isplay name o$ the a%tivity.commonsware. servi%es.MA.oes Something6 2ight: 5he real meat o$ the mani$est $ile are the %hil ren o$ the application element.permission.com/apk/res/android# packa%e"#com.ACC)SS*C)++*.commonsware. An .ACC)SS*+. Chose %ontents Cill es%ribe the a%tivities.S-)D*01S# /& <uses(permission android!name"#android. there is the application element. Chen you %reate a neC An roi proOe%t.com/apk/res/android# packa%e"#com.CA-../# /& <cate%ory android!name"#android.ACC)SS*01S# /& <uses(permission android!name"#android.skeleton#& <application& <activity android!name"#.permission. /y e$ault.action.ACC)SS*ASS.. permissions to alloC the appli%ation to etermine its %urrent lo%ation.android#& <uses(permission android!name"#android.permission. Subscribe to updates at http://commonsware. -our )pplication .android.D# /& <application& .android. </application& </manifest& .android.intent.0 License Edition .cate%ory. the mani$est has uses(permission elements to in i%ate some evi%e %apabilities the appli%ation Cill nee N in this %ase.

so users %an %hoose to run it. in i%ating %ontent provi ers N %omponents that supply ata to your a%tivities an . 5hese are %alle intent re%eivers an are es%ribe mi 3 Cay through the book. ($ Subscribe to updates at http://commonsware. other a%tivities in other appli%ations on the evi%e. in i%ating non3a%tivities that shoul be triggere un er %ertain %on itions. 5he <uintessential e. i$ you so %hoose. 5Co %hapters late in the book %over hoC to %reate an use servi%es. (inally. Chere you Cant the musi% to keep playing even i$ the user pops open other a%tivities an the M!? player7s user inter$a%e is Qmispla%e Q.com Special Creative Commons BY-SA 3. @ou may also have one or more receiver elements. you may have one or more service elements. su%h as Chen an #M# message %omes in. 5hese Crap up atabases or other ata stores into a single A!. 5he sto%k activity element sets up your a%tivity to appear in the laun%her. that any appli%ation %an use.ample is the M!? player. Later.8nside the *anifest Cill be isplaye . @ou may have one or more provider elements. you %an have several a%tivities in one proOe%t. Cith your permission. es%ribing servi%es N long3running pie%es o$ %o e that %an operate in epen ent o$ any a%tivity. As Ce7ll see later in this book. Ce7ll see hoC to %reate %ontent provi ers an hoC to use %ontent provi ers that you or others %reate.0 License Edition .

0 License Edition .com Special Creative Commons BY-SA 3.PART II – Activities Subscribe to updates at http://commonsware.

com Special Creative Commons BY-SA 3.Subscribe to updates at http://commonsware.0 License Edition .

+ust pass activityCreator.$ you are using tools that are not An roi 3enable ..CHAPTER ( Creating a Skeleton )pplication Ivery programming language or environment book starts o$$ Cith the ever3 popular Q)ello.$ you are using an An roi 3enable . $oun in the tools/ ire%tory in your #AF installation. Worl :Q program has no intera%tivity &e. . you nee a proOe%t. An roi is more %omple. )oCever. an run it Cith java.py s%ript. but one using A van%e !ush3 /utton 5e%hnologyR an the %urrent time.g.0 License Edition . you %oul Oust Crite a program as a single $ile.AI &e. Begin at the Beginning 5o Cork Cith anything in An roi . Worl :Q emonstration* Oust enough o$ a program to prove you %an buil things.AI. an so is really boring. 5his %hapter emonstrates a simple proOe%t. Cithout any other support stru%tures. sele%t 4ile @ >e0 @ Pro"ect.py the pa%kage name o$ the a%tivity (3 Subscribe to updates at http://commonsware. the typi%al Q)ello. you %an use the activityCreator. to shoC you hoC a simple An roi a%tivity Corks. but to help keep it manageable. Oust umps the Cor s to a %onsole'. then %hoose Android @ Android Pro"ect'. 8oogle has supplie tools to help %reate the proOe%t. you %an %reate a proOe%t insi e o$ the . su%h as I%lipse Cith the An roi plugin..com Special Creative Commons BY-SA 3. not so mu%h that you %annot un erstan Chat is going on. With or inary +ava. %ompile it Cith javac. i$ you Cante . .g..

/ow @ou Cill Cin up Cith a han $ul o$ pre3generate $iles.7iew5 android.skeleton5 import import import import import android./activityCreator. (or e.java in your e itor an paste in the $olloCing %o e* packa%e com. The )ctivity @our proOe%t7s src/ ire%tory %ontains the stan ar +ava3style tree o$ ire%tories base upon the +ava pa%kage you %hose Chen you %reate the proOe%t &e..android results in src/com/commonsware/android/'.nClick+istener 8 6utton btn5 9.verride public void onCreate:6undle icicle.commonsware.py ((out /pat$/to/my/project/dir 4 com.py on those unpa%ke samples.g.Date5 public class /ow extends Activity implements 7iew.nsi e the innermost ire%tory you shoul $in a pre3generate sour%e $ile name /ow.Activity5 android.com Special Creative Commons BY-SA 3.android. you %an oCnloa their proOe%t ire%tories in a M. (or the purposes o$ the samples shoCn in this book.ample* . .os. 8 super. Chi%h Chere your $irst a%tivity Cill go.5 btn. com. as es%ribe in a previous %hapter.util.onCreate:icicle.! $ile on the CommonsWare Web site.commonsware.java. >pen /ow.5 (7 Subscribe to updates at http://commonsware.Creating a Skeleton )pplication you Cant to %reate an a ((out sCit%h in i%ating Chere the proOe%t $iles shoul be generate .android.setOnClickListener:t$is.commonsware..6utton5 java.0 License Edition .wid%et.6undle5 android.app.view.5 btn " new Button:t$is. 5hese proOe%ts are rea y $or useP you o not nee to run activityCreator.

. An .5 setContentView:btn. i$ you oCnloa the sour%e $iles o$$ the Web site. inheriting $rom the android.commonsware.setText:new Date:.Creating a Skeleton )pplication < updateTime:. $or simpli%ity..toString:. the a%tivity hol s a button &btn'. 8 updateTime:.0 License Edition .android.7iew5 android.5 < < >r.Activity base %lass.app. #in%e.. .skeleton5 import import import import import android.amine this pie%e by pie%e* packa%e com.issecting the )ctivity Let7s e.os. Most o$ the An roi 3spe%i$i% %lasses are in the android pa%kage..6undle5 android. 8 btn.6utton5 java.nClick+istener 8 6utton btn5 A%tivities are publi% %lasses.com Special Creative Commons BY-SA 3.wid%et.view.Date5 5he pa%kage e%laration nee s to be the same as the one you use Chen %reating the proOe%t.n this %ase.isit the An roi %lass re$eren%e to see Chat is an is not available. you nee to import any %lasses you re$eren%e.5 public void onClick:7iew view. Ce Cant (9 Subscribe to updates at http://commonsware.Activity5 android. Remember that not every +ava #I %lass is available to An roi programs: . like any other +ava proOe%t. you %an Oust use the /ow proOe%t ire%tly. public class /ow extends Activity implements 7iew.util.5 < private void updateTime:.

(or the moment.5 < %. 8 updateTime:.'. metho &see beloC'. 8 super.setOnClickListener:t$is.n An roi . %onsi er it an opa<ue han le that all a%tivities re%eive upon %reation. an then set the a%tivity7s %ontent vieC to be the button itsel$ &via setContent7iew:. %all a private update-ime:. public void onClick:7iew view..5 < .5 < 5he onCreate:.nClick+istener:.'.5 btn. so the sto%k An roi a%tivity initialiKation %an be one. tell it to sen all button %li%ks to the a%tivity instan%e itsel$ &via set. 8 btn. 5he listener is provi e the vieC that triggere the %li%k &in this %ase. the button'. 9. to be invoke in the .'.verride public void onCreate:6undle icicle.5 setContentView:btn. Subscribe to updates at http://commonsware. a =6utton %li%k raises an Action)vent.n our implementation.n #Cing. metho * private void updateTime:. All Ce o here is %all that private update-ime:.nClick+istener.Creating a Skeleton )pplication to trap all button %li%ks Oust Cithin the a%tivity itsel$. Ce also have the a%tivity %lass implement . a button %li%k %auses onClick:.0 License Edition . We Cill is%uss that magi%al 6undle icicle in a later %hapter. Chi%h is passe to the Action+istener %on$igure $or the button. . 5he $irst thing you shoul o is %hain upCar to the super%lass. .toString:.nClick+istener instan%e %on$igure $or the button. Ce then %reate the button instan%e &new 6utton:t$is.setText:new Date:. metho is invoke Chen the a%tivity is starte ..5 btn " new Button:t$is.com Special Creative Commons BY-SA 3.onCreate:icicle.5 updateTime:.

run tools/emulator $rom your An roi #AF installation' .. Ce up ate the button7s label to be the %urrent time via set-ext:. or run ant in the base ire%tory o$ your proOe%t. Chi%h $un%tions mu%h the same as the =6utton e<uivalent.ieC the list o$ installe appli%ations in the emulator an $in the Q0oCQ appli%ation !igure (< The )ndroid application =launcher= • >pen that appli%ation %( Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. Building and 2unning the )ctivity 5o buil the a%tivity. to run the a%tivity* • Laun%h the emulator &e.. either use your .nstall the pa%kage &e.' or Chen the button is %li%ke &onClick:.apk • run $rom tools/adb install your An roi #AF installation' • .g..'. 5hen.AI7s built3in An roi pa%kaging tool. /pat$/to/t$is/example/bin//ow.Creating a Skeleton )pplication When Ce open the a%tivity &onCreate:.0 License Edition .g.

0 License Edition . Chi%h Cill be %overe in a later %hapter. you %an %li%k the ba%k button on the emulator to return to the laun%her. pretty mu%h anyChere on the phone7s s%reen N Cill up ate the time shoCn in the button7s label. as those are the e$ault styles applie to button %aptions. We %an %ontrol that $ormatting.Creating a Skeleton )pplication @ou shoul see an a%tivity s%reen akin to* !igure %< The 5o4 demonstration activity Cli%king the button N in other Cor s. A$ter you are one gaKing at the aCesomeness o$ A van%e !ush3/utton 5e%hnologyR. 0ote that the label is %entere horiKontally an verti%ally. %% Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

an EML3base layout is a spe%i$i%ation o$ Ci gets7 relationships to ea%h other N an to %ontainers N en%o e in EML $ormat. that means that the te.. es%ribing hoC a Ci get shoul look or hoC a %ontainer shoul behave.CHAPTER ) >sing ?* "Based ayouts While it is te%hni%ally possible to %reate an atta%h Ci gets to our a%tivity purely through +ava %o e. populating a %olumn o$ ra io buttons base on ata retrieve o$$ the . Ia%h EML $ile %ontains a tree o$ elements spe%i$ying a layout o$ Ci gets an %ontainers that make up one 7iew. the more %ommon approa%h is to use an EML3base layout $ile. Aynami% instantiation o$ Ci gets is reserve $or more %ompli%ate s%enarios. i$ a 6utton element has an attribute value o$ android!textStyle " #bold#. 5he attributes o$ the EML elements are properties. it7s time to break out the EML an learn out to lay out An roi a%tivity vieCs that Cay. With that in min .ample. an as su%h layout $iles are store in the res/layout ire%tory insi e your An roi proOe%t. An roi %onsi ers EML3base layouts to be resour%es.0 License Edition . (or e. the Cay Ce i in the pre%e ing %hapter. Chere the Ci gets are not knoCn at %ompile3time &e.com Special Creative Commons BY-SA 3.t appearing on the $a%e o$ the button shoul be ren ere in a bol $a%e $ont style.nternet'. What 8s an ?* "Based ayout: As the name suggests. #pe%i$i%ally. Subscribe to updates at http://commonsware.g. %.

Ant7s build.. (or e. Moreover.>sing ?* "Based ayouts An roi 7s #AF ships Cith a tool &aapt' Chi%h uses the layouts. >$ parti%ular importan%e to you as a eveloper is that aapt generates the R. instea o$ using a property in an EML layout. to have a button ren er its te. $rameCorks.t in bol .com Special Creative Commons BY-SA 3. Ce nee goo reasons $or using su%h $iles.AI like I%lipse or a e i%ate An roi 8".0 License Edition . in prin%iple. esigner like Aroi AraC. Many less3 Cell3knoCn 8".. I%lipse. an MoKilla7s E"L all take a similar approa%h to that o$ An roi * put layout etails in an EML $ile an put programming smarts in sour%e $iles &e. Mi%roso$t7s EAML.ample. keeping the generate bits separate out $rom han 3Critten %o e makes it less likely that somebo y7s %ustom3%ra$te sour%e Cill get %lobbere by a%%i ent Chen the generate bits get re3generate . buil er in an .g.java sour%e $ile Cithin your proOe%t. #u%h 8".. it oes have the a vantage o$ helping to ease the transition into An roi $rom any other EML3%entere vieC es%ription language. su%h as MF.xml'. Also. buil ers %oul . EML $orms a ni%e mi le groun betCeen something that is easy $or tool3Criters to use an easy $or programmers to Cork Cith by han as nee e . 5he %hallenge is re3rea ing the e$inition in to support e its N that is $ar simpler i$ the ata is in a stru%ture $ormat like EML than in a programming language. generate +ava %o e instea o$ EML. 5his tool shoul be automati%ally invoke by your An roi tool %hain &e. you %oul use set-ypeface:. also use EML $or vieC e$inition. +avas%ript $or E"L'. alloCing you to a%%ess layouts an Ci gets Cithin those layouts ire%tly $rom your +ava %o e. su%h as a 8". A obe7s (le. as Cill be emonstrate . EML as a 8". Why >se ?* "Based ayouts: Most everything you o using EML layout $iles %an be a%hieve through +ava %o e. e$inition $ormat is be%oming more %ommonpla%e. %$ Subscribe to updates at http://commonsware. !erhaps the biggest reason is to assist in the %reation o$ tools $or vieC e$inition.g. While Q$olloCing the her Q is not ne%essarily the best poli%y. #in%e EML layouts are yet another $ile $or you to keep tra%k o$.

%onverte into an EML layout $ile* <>xml version"#?.oes 8t ook ike: )ere is the 6utton $rom the previous %hapter7s sample appli%ation.com/apk/res/android# All other elements Cill be %hil ren o$ the root an namespa%e e%laration. 5he remaining attributes are properties o$ this 6utton instan%e* • in i%ates the initial te. 5he root element nee s to e%lare the An roi EML namespa%e* xmlns!android"#$ttp!//sc$emas.t to be isplaye on the button $a%e &in this %ase. in this %ase the entire s%reen N these attributes Cill be %overe in greater etail in a later %hapter %/ Subscribe to updates at http://commonsware.7iew. Ce %an Oust use the bare %lass name.MyCid%et'.>sing ?* "Based ayouts +@6 So What .$ you %reate your oCn Ci gets as sub%lasses o$ android. .com/apk/res/android# android!id"#9Bid/button# android!text"## android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#/& 5he %lass name o$ the Ci get N 6utton N $orms the name o$ the EML element.android.android.commonsware. #in%e 6utton is an An roi 3supplie Ci get..0 License Edition . We Cill %over this %on%ept in greater etail .android.view.com Special Creative Commons BY-SA 3. an empty string' android!text android!layout*widt$ • an android!layout*$ei%$t tell An roi to have the button7s Ci th an height $ill the QparentQ. com. Cill inherit that /e%ause Ce Cant to re$eren%e this button $rom our +ava %o e. you Coul nee to provi e a $ull pa%kage e%laration as Cell &e.@# encodin%"#utf(A#>& <6utton xmlns!android"#$ttp!//sc$emas.g. Ce nee to give it an i enti$ier via the android!id attribute.

provi es a $eC spe%ial android!id values. Comple. a 6utton'. 5he An roi 3built 7iew..n the EML layout e.. . WhatAs With the B Signs: Many Ci gets an %ontainers only nee to appear in the EML layout $ile an o not nee to be re$eren%e in your +ava %o e. a stati% label &-ext7iew' $re<uently only nee s to be in the layout $ile to in i%ate Chere it shoul appear.0 License Edition .ample. %allba%k to use that layout* 5his is the same set+ayout7iew:.ample in the pre%e ing se%tion.. nee s an android!id. Ce only nee this single element. %onstru%te %0 Subscribe to updates at http://commonsware. as the id value. 5hese sorts o$ elements in the EML $ile o not nee to have the android!id attribute to give them a name. though.>sing ?* "Based ayouts #in%e this single Ci get is the only %ontent in our a%tivity7s vieC. vieCs Cill re<uire a Chole tree o$ elements..amples o$ more %omple. (or e.xml store in res/layout. layouts $or you to peruse. Chere the . represents your lo%ally3uni<ue name $or the Ci get in <uestion.. so there are oKens o$ other e. Ce use earlier. representing the Ci gets an %ontainers that %ontrol their positioning. N Ce Cill see some o$ these in various %hapters o$ this book.com Special Creative Commons BY-SA 3. 9Bid/button is the i enti$ier $or the 6utton Ci get. Anything you do Cant to use in your +ava sour%e. An roi )nd We )ttach These to the Cava<<<Do4: 8iven that you have painstakingly set up the Ci gets an %ontainers $or your vieC in an EML layout $ile name snicklefrit'. 5he %onvention is to use 9Bid/. all you nee is one statement in your a%tivity7s onCreate:. All the remaining %hapters o$ this book Cill use the EML layout $orm Chenever pra%ti%al. o$ the $orm 9android!id/. passing it an instan%e o$ a 7iew sub%lass &in that %ase..

id.Date5 public class /owRedux extends Activity implements 7iew.verride public void onCreate:6undle icicle.os. passing it the numeri% i enti$ier o$ the Ci get in <uestion.>sing ?* "Based ayouts $rom our layout. 5o a%%ess our i enti$ie Ci gets.5 btn":6utton.d:. The 2est of the Story . i$ the button ha not yet been pushe '.nClick+istener 8 6utton btn5 9.view. is a%%esse $rom that %o e3generate R %lass. %allba%k.onCreate:icicle.5 btn..somet$in% &Chere somet$in% is the spe%i$i% Ci get you are seeking'.wid%et.button. 8 %3 Subscribe to updates at http://commonsware.layouts5 import import import import import android.0 License Edition .5 < public void onClick:7iew view.main. the button7s $a%e Coul shoC the %urrent time.n the original /ow emo.Activity5 android.7iew5 android.layout. rather than instantiating the 6utton in our a%tivity7s onCreate:. keye by the base name o$ the layout $ile N snicklefrit'.5 updateTime:.snicklefrit'. even in this revise emo & /owRedux'.commonsware.layout. use find7iew6y.com Special Creative Commons BY-SA 3.. )oCever.6undle5 android. Ce %an re$eren%e the one $rom the EML layout* packa%e com.id.android.5 setContentView:R. 5hose Ci gets are simply sub%lasses o$ 7iew. 8 super. All o$ the layouts are a%%essible un er R. Oust like the 6utton instan%e Ce %reate in the previous %hapter. Most o$ that logi% still Corks.util.app.layout.6utton5 java.xml results in R.findViewById:R.setOnClickListener:t$is. Chi%h Coul re$le%t Chen the button Cas last pushe &or Chen the a%tivity Cas $irst shoCn. 5hat numeri% i enti$ier Cas generate by An roi in the R %lass as R.

java sour%e $ile Cill be up ate Chen Ce rebuil this proOe%t to in%lu e a re$eren%e to our layout $ile &store as main. Ce %an set the %allba%k an set the label as nee e .toString:.com Special Creative Commons BY-SA 3. 5he results look the same as Cith the original /ow emo* !igure . #in%e Ce i enti$ie our button as 9Bid/button. 8 btn. Cith the 6utton instan%e in han .< The 5o42edux sample activity %7 Subscribe to updates at http://commonsware. Ce %an re$eren%e the button7s i enti$ier as R.xml in our proOe%t7s res/layout ire%tory'.0 License Edition .id. $or Chi%h Ce use the find7iew6y. 5he other i$$eren%e is that Ce nee to get our han s on our 6utton instan%e.. %all.5 < < 5he $irst i$$eren%e is that rather than setting the %ontent vieC to be a vieC Ce %reate in +ava %o e.setText:new Date:. 0oC.>sing ?* "Based ayouts updateTime:.layout..d:. 5he R.5 < private void updateTime:.'.button. Ce set it to re$eren%e the EML layout &setContent7iew:R.main.

or bol an itali% &bold*italic' %9 Subscribe to updates at http://commonsware. you Cill %reate labels in EML layout $iles by a ing a -ext7iew element to the layout. . More %ommonly. as Cill be es%ribe later in this book. an the basi% Ci gets Cill provi e a goo intro u%tion as to hoC Ci gets Cork in An roi a%tivities. )ssigning abels 5he simplest Ci get is the label. you may Cish to use a resour%e re$eren%e in the EML instea . su%h as* to set the type$a%e to use $or the label &e. Like in most 8". labels. Cith an android!text property to set the value o$ the label itsel$. itali% &italic'. -ext7iew • has numerous other properties o$ relevan%e $or labels. An roi 7s toolkit is no i$$erent in s%ope.. you %an %reate a label by %reating a -ext7iew instan%e. android!typeface monospace' • android!textStyle to in i%ate that the type$a%e shoul be ma e bol &bold'. buttons. 5ypi%ally.CHAPTER * Employing Basic Widgets Ivery 8".g. labels are bits o$ te.n +ava. toolkits. they are use to i enti$y a Oa%ent Ci gets &e. . though. et%.g.t not e itable ire%tly by users. re$erre to in An roi as a -ext7iew.0 License Edition .$ you nee to sCap labels base on %ertain %riteria. su%h as internationaliKation. a Q0ame*Q label be$ore a $iel Chere one $ills in a name'..com Special Creative Commons BY-SA 3. toolkit has some basi% Ci gets* $iel s.

g. Cith the stub +ava sour%e provi e proOe%t buil er &e. so everything is%usse in the pre%e ing se%tion in terms o$ $ormatting the $a%e o$ the button still hol s. you Cill $in the $olloCing layout $ile* <>xml version"#?.Employing Basic Widgets • android!textColor to set the $ormat &e.com Special Creative Commons BY-SA 3.. 6utton is a sub%lass o$ -ext7iew. activityCreator'.g.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!text"#Fou were expectin% somet$in% profound># /& +ust that layout alone. DEE@@@@ $or re ' %olor o$ the label7s te. As it turns out.. . (or e.0 License Edition .ample..emo sample application Button6 Button6 WhoAs 'ot the Button: We7ve alrea y seen the use o$ the 6utton Ci get in the previous tCo %hapters.t.@# encodin%"#utf(A#>& <-ext7iew xmlns!android"#$ttp!//sc$emas.android. in the +abel proOe%t. Subscribe to updates at http://commonsware. gives you* by An roi 7s !igure $< The abel. in R8/ he.

to %on$igure the $iel android!sin%le+ine.g. • • to a%%ept only %ertain igits to %ontrol i$ the $iel is $or single3line input or multiple3line input &e. $or respon ing to %li%ks an Chatnot..( Subscribe to updates at http://commonsware. toolkits. Along Cith the stan ar -ext7iew properties &e. has many others that Cill be use$ul $or you in %onstru%ting $iel s.g. $irst name. . Chi%h is a sub%lass o$ the -ext7iew use $or labels. Ia%h Ci get takes an android!src attribute &in an EML layout' to spe%i$y Chat pi%ture to use.es in the stan ar /utton behaviors. %ity' android!di%its. respe%tively. @ou %an also set the image %ontent base on a 2ri $rom a %ontent provi er via set.t &e.:. android!textStyle'.com Special Creative Commons BY-SA 3. es%ribe in greater etail in the %hapter on resour%es. a sub%lass o$ .t Ci get or a a neClineD' /eyon those.g. android!password $or .ma%e2R. !ields of 'reen< +r +ther Colors< Along Cith buttons an labels. su%h as android!numeric $or numeri%3only input. they are image3base analogues to -ext7iew an 6utton. $iel s are the thir Qan%horQ o$ most 8"... 5hese usually re$eren%e a raCable resour%e. to %ontrol i$ the $iel spelling assistan%e shoul provi e automati% • android!capitali'e..0 License Edition . oes SInterT move you to the ne. they are implemente via the )dit7iew Ci get.Employing Basic Widgets !leeting 8mages An roi . to %ontrol i$ the $iel shoul automati%ally %apitaliKe the $irst letter o$ entere te.n An roi . mi. you %an %on$igure $iel s to use spe%ialiKe input metho s.ma%e7iew has tCo Ci gets to help you embe images in your a%tivities* an .ma%e7iew.ma%e6utton. . As the names suggest.ma%e6utton. in%lu ing* )dit7iew • android!auto-ext.

% Subscribe to updates at http://commonsware.basic5 import android. (or e.setText:#+icensed under t$e Apac$e +icenseG 7ersion H. 8 super. an android!p$one/umber $or entering in phone numbers.app.ample..ample o$ this in the appen i. Fou may # B #obtain a copy of t$e +icense at # B #$ttp!//www.@ # B #:t$e 4#+icense4#.findViewById:R. postal %o es.t sample appli%ation.apac$e.g. $rom the Eield proOe%t.)dit-ext5 public class EieldDemo extends Activity 8 9.6undle5 import android. #o%ial #e%urity numbers'.5 < < . @ou %an see an e.Employing Basic Widgets shrou e passCor input.verride public void onCreate:6undle icicle.Activity5 import android.or%/licenses/+.com/apk/res/android# android!id"#9Bid/field# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!sin%le+ine"#false# /& 0ote that android!sin%le+ine is $alse. you nee to %reate your oCn implementation o$ the .0 License Edition .android.onCreate:icicle.@# encodin%"#utf(A#>& <)dit-ext xmlns!android"#$ttp!//sc$emas. is%ussing the 5our.5 fld.wid%et.C)/S)(H.id. . (or this proOe%t.t.os.5 )dit-ext fld":)dit-ext.5 you may not use t$is file # B #except in compliance wit$ t$e +icense.java $ile populates the input $iel Cith some prose* packa%e com.5 setContentView:R.field. then %on$igure the $iel to use it via android!inputMet$od.nputMet$od inter$a%e. here is an EML layout $ile shoCing an )dit7iew* <>xml version"#?. so users Cill be able to enter in several lines o$ te.com Special Creative Commons BY-SA 3.layout.main.android.commonsware. the EieldDemo.$ you Cant to %reate your oCn input metho s%heme &e.@#.

is%usse in greater etail later in this book. reinstall the $ormerly3hi en appli%ation.basic pa%kage. i$ you have the LabelAemo appli%ation installe . Chere . Subscribe to updates at http://commonsware.. +abelDemo.#. 5hat is provi e in An roi as the AutoComplete-ext7iew Ci get. you Cill not see the (iel Aemo appli%ation in the laun%her.. is the name o$ the appli%ation7s A!F $ile &e... an it Cill shoC up in the laun%her.emo sample application >AT. 5o remove the LabelAemo appli%ation N or any appli%ation N use adb s$ell #rm /data/app/. Another $lavor o$ $iel is one that o$$ers auto3%ompletion. is* !igure /< The !ield.t. .com Special Creative Commons BY-SA 3.Employing Basic Widgets 5he result.g. on%e built an installe into the emulator.apk'.. to help users supply a value Cithout typing in the Chole te.commonsware.android. 5hen. #in%e all the emos in this %hapter share the com.0 License Edition .* An roi 7s emulator only alloCs one appli%ation in the laun%her per uni<ue +ava pa%kage..

nC$eckedC$an%e+istener' to be noti$ie Chen the state o$ the %he%kbo.g. QA rush elivery to my or erQ'.$ Subscribe to updates at http://commonsware. Within +ava.@# encodin%"#utf(A#>& <C$eck6ox xmlns!android"#$ttp!//sc$emas.. as i$ the user %he%ke it Also. has been %he%ke or un%he%ke state • to $or%e the %he%kbo.. you %an register a listener obOe%t &in this %ase. to toggle the %he%kbo. Cli%king the %he%kbo.onCreate:icicle.Employing Basic Widgets Cust )nother Box to Check 5he %lassi% %he%kbo.com Special Creative Commons BY-SA 3. an instan%e o$ . here is a simple %he%kbo. %hanges.ample. has tCo states* %he%ke an un%he%ke .* public class C$eck6oxDemo extends Activity implements Compound6utton. $rom the C$eck6ox proOe%t.5 . so you %an use -ext7iew properties like android!textColor to $ormat the Ci get.0 License Edition . layout* <>xml version"#?. (or e.verride public void onCreate:6undle icicle.android. to setC$ecked:. you %an invoke* • • isC$ecked:.java retrieves an %on$igures the behavior o$ the %he%kbo. 8 super. into a %he%ke to%%le:. . toggles betCeen those states to in i%ate a %hoi%e &e.n An roi . .t has -ext7iew as an an%estor. etermine i$ the %he%kbo.nC$eckedC$an%e+istener 8 C$eck6ox cb5 9.com/apk/res/android# android!id"#9Bid/c$eck# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#-$is c$eckbox is! unc$ecked# /& 5he %orrespon ing C$eck6oxDemo. there is a C$eck6ox Ci get to meet this nee .

state %hanges sin%e it implements the .c$eck. Chi%h re%eives the %he%kbo.5 cb":C$eck6ox.set.'.Employing Basic Widgets setContentView:R.nC$eckedC$an%e+istener:t$is..5 < public void onCheckedChanged:Compound6utton button7iewG boolean isC$ecked.layout.main.n this %ase.setText:#-$is c$eckbox is! c$ecked#.5 < < < 0ote that the a%tivity serves as its oCn listener $or %he%kbo.nC$eckedC$an%e+istener inter$a%e &via cb. Ce up ate the te.setOnCheckedChangeListener:t$is. %ontains. as shoCn beloC* . Chose state has %hange an Chat the neC state is.findViewById:R.0 License Edition .com Special Creative Commons BY-SA 3.t. 5he %allba%k $or the listener is onC$eckedC$an%ed:. .5 < else 8 cb.setText:#-$is c$eckbox is! unc$ecked#./ Subscribe to updates at http://commonsware. 8 if :isC$ecked. 5he resultD Cli%king the %he%kbo.5 cb. 8 cb.t o$ the %he%kbo. imme iately up ates its te. to re$le%t Chat the a%tual bo.id.

emo sample application6 4ith the checkbox unchecked !igure 3< The same application6 no4 4ith the checkbox checked .Employing Basic Widgets !igure 0< The CheckBox.0 Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition .

Employing Basic Widgets Turn the 2adio >p As Cith other implementations o$ ra io buttons in other toolkits.0 License Edition .A &e.g. on a Radio6utton to see i$ it is sele%te . %olor. #imilarly. here is an EML layout shoCing a Radio0roup Crapping a set o$ Radio6utton Ci gets* <>xml version"#?. Like C$eck6ox.. but %an be groupe su%h that only one ra io button in the group %an be %he%ke at any time. to %he%k a %roup. An roi 7s ra io buttons are tCo3state. you %an a%%ess the group $rom your +ava %o e an invoke* Radio0roup.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <Radio6utton android!id"#9Bid/radio?# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#Rock# /& . you %an %all isC$ecked:. spe%i$i% ra io button via its .c$eck:R. to get the ra io button &or (? i$ none are %he%ke (or e. like you %an Cith a C$eck6ox.id. all the stan ar -ext7iew properties $or $ont $a%e. to sele%t it. Most times. )en%e.@# encodin%"#utf(A#>& <Radio0roup xmlns!android"#$ttp!//sc$emas. to%%le:.$ you assign an android!id to your Radio0roup in your EML layout.d:.ample.rb?. an so on.3 Subscribe to updates at http://commonsware. . style. so none in the group are . • c$eck:.com Special Creative Commons BY-SA 3.es. like %he%kbo. are available $or %ontrolling the look o$ ra io buttons. • to %lear all ra io buttons. Radio6utton inherits $rom Compound6utton. Chi%h in turn inherits $rom -ext7iew. you Cill Cant to put your Radio6utton Ci gets insi e o$ a 5he Radio0roup in i%ates a set o$ ra io buttons Chose state is tie . $rom the Radio6utton sample appli%ation. meaning only one button out o$ the group %an be sele%te at any time.' clearC$eck:.A o$ the %urrently3%he%ke ' %he%ke • %etC$eckedRadio6utton. et%.android.

5o pre3set one o$ the ra io buttons to be %he%ke . %allba%k in your a%tivity. on the Radio6utton or c$eck:. . you get* !igure 7< The 2adioButton. use either setC$ecked:.Employing Basic Widgets <Radio6utton android!id"#9Bid/radioH# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#Scissors# /& <Radio6utton android!id"#9Bid/radioI# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#1aper# /& </Radio0roup& "sing the sto%k An roi 3generate +ava $or the proOe%t an this layout.emo sample application 0ote that the ra io button group is initially set to be %ompletely un%he%ke at the outset.0 License Edition . on the Radio0roup $rom Cithin your onCreate:.7 Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

D@@EE@@ $or green' to serve as the ba%kgroun +se. to $in %ontainers that make up an the parent Ci get or %ontainer . in%lu ing the ones shoCn above.com Special Creative Commons BY-SA 3. an as su%h give all Ci gets an array o$ use$ul properties an metho s beyon those alrea y es%ribe . Chi%h typi%ally provi es an &e.ul %ethods @ou %an toggle Chether or not a Ci get is enable via set)nabled:.. 5o help navigate the tree o$ Ci gets an a%tivity7s overall vieC.0 License Edition .ten 7iew. to ensure the proper Ci get has the $o%us on%e your isabling operation is %omplete. e. Chi%h %ontrols Chether the Ci get is initially R8/ %olor value $or the Ci get visible • android!back%round.g. >ne %ommon use pattern $or this is to isable some Ci gets base on a C$eck6ox or Radio6utton sele%tion. an see i$ it is enable via is)nabled:..ul Properties #ome o$ the properties on 7iew most likely to be use in%lu e* • Controls the $o%us se<uen%e* • • • • android!nextEocusDown android!nextEocus+eft android!nextEocusRi%$t android!nextEocus2p • android!visibility.9 Subscribe to updates at http://commonsware. you %an use* • %et1arent:.. an see i$ it is $o%use via isEocused:. @ou %an give a Ci get $o%us via reJuestEocus:. @ou might use this in %on%ert Cith isabling Ci gets as mentione above.Employing Basic Widgets 8tAs Fuite a Gie4 All Ci gets. +se.

g..d:.Employing Basic Widgets • %et1arent.g.0 License Edition .com Special Creative Commons BY-SA 3. $in the Radio0roup $or a Radio6utton' find7iew6y.A to get the root o$ the tree &e. • • a %hil Ci get Cith a %ertain .' $.. to $in %etRoot7iew:. to sear%h upCar s in the tree to $in a %ontainer o$ a %ertain %lass &e.f-ype:. Subscribe to updates at http://commonsware. Chat you provi e to the a%tivity via setContent7iew:.

. you Cill nee a %ontainer.t to one another. you have layout managers like 6ox+ayout an %ontainers that use them &e. +ust $rom a pure EML perspe%tive. .amine some more esoteri% %ontainers. $or e. through LinearLayout. ne. #ome toolkits sti%k stri%tly to the bo. mo el. but in a ition supports a range o$ %ontainers provi ing i$$erent layout rules. . $re<uently organiKe into %ontainers. i$ you have multiple Ci gets &beyon Radio6utton Ci gets in a Radio0roup'. $( Subscribe to updates at http://commonsware. you Cill nee a %ontainer. An roi . Most 8". also o$$ers a Qbo.0 License Edition . toolkits have some notion o$ layout management.es.com Special Creative Commons BY-SA 3.n this %hapter. . Ce Cill e. ..Q mo el.$ you Cant a $orm Cith labels on the le$t an $iel s on the right. an -able+ayout &the gri mo el'. a %ontainer esigne to assist Cith implementing s%rolling %ontainers.CHAPTER - Working 4ith Containers Containers pour a %olle%tion o$ Ci gets &an possibly %hil %ontainers' into spe%i$i% layouts you like.t %hapter.$ you Cant >F an Can%el buttons to be beneath the rest o$ the $orm. su%h as E"L an (le. Relative+ayout &a rule3base mo el'. you Cill nee a %ontainer Oust to have a root element to pla%e the Ci gets insi e..g. along Cith Scroll7iew.n +avaU#Cing. an $lush to right si e o$ the s%reen.ample. Ce Cill look at three %ommonly3use %ontainers* +inear+ayout &the bo. mo el'. 6ox'.n the ne. $iguring that any esire layout %an be a%hieve through the right %ombination o$ neste bo.

0 License Edition . Concepts nd Properties 5o %on$igure a +inear+ayout.R.t. su%h as alignment vis a vis other bo. the Ceight. you %an use +inear+ayout in mu%h the same Cay.t. +ust a the android!orientation property to your +inear+ayout element in your EML layout.CA+.rientation:.com Special Creative Commons BY-SA 3. Orientation >rientation in i%ates Chether the +inear+ayout represents a roC or a %olumn.es shoul have. 8etting the visual representation you Cant is mostly a matter o$ i enti$ying Chere bo. 5he orientation %an be mo i$ie at runtime by invoking set. on the +inear+ayout. supplying it either 3.es. $% Subscribe to updates at http://commonsware. the gravity. the $ill mo el. an E"L use the bo./-A+ or 7)R-.$ you Cant.es shoul nest an Chat properties those bo. +inear+ayout is a bo. et%. 5hese Ci gets have a QnaturalQ siKe base on their te. We then have the issue o$ Chat to o Cith the remaining spa%e. an the pa ing. su%h as a pair o$ ra io buttons. 5his Corks similar to Elow+ayout in +avaU#Cing. .a%tly mat%h the Ci th o$ the An roi evi%e7s s%reen N parti%ularly sin%e s%reens %ome in various siKes. Fill Model Let7s imagine a roC o$ Ci gets.Working 4ith Containers Thinking inearly As note above. setting the value to be $ori'ontal $or a roC or vertical $or a %olumn. vbox an $box in (le. (le. mo el N Ci gets or %hil %ontainers are line up in a %olumn or roC. one a$ter the ne. you have $ive main areas o$ %ontrol besi es the %ontainer7s %ontents* the orientation.K. 5heir %ombine siKes probably o not e. an E"L. es%heCing some o$ the other %ontainers. as their primary unit o$ layout.

the se%on Ci get Cill use up tCi%e the $ree spa%e that the $irst Ci get oes. alloCing An roi to a Oust your vieC to $it the available spa%e. in a ition to setting android!layout*widt$ &$or roCs' or android!layout*$ei%$t &$or %olumns' to fill*parent. $. 5o make this Cork..$ you set it to be ? $or one Ci get an H $or another Ci get.a%tly -2B pi. An so on. a$ter all other Ci gets are taken %are o$ • • 5he latter tCo $lavors are the most %ommon. the $ree spa%e Cill be split evenly betCeen them.$ you set android!layout*wei%$t to be the same value $or a pair o$ Ci gets &e. ?'.Working 4ith Containers All Ci gets insi e a +inear+ayout must supply android!layout*widt$ an android!layout*$ei%$t properties to help a ress this issue. Weight /ut. in Chi%h %ase An roi %an use Cor 3Crap as nee e to make it $it @ou %an provi e fill*parent. suppose Ce have tCo multi3line $iel s in a %olumn. . Subscribe to updates at http://commonsware. Chat happens i$ Ce have tCo Ci gets that shoul split the available $ree spa%eD (or e.g. . su%h as ?HLpx to in i%ate the Ci get shoul take up e.com Special Creative Commons BY-SA 3. Chi%h means the Ci get shoul $ill up all available spa%e in its en%losing %ontainer.els @ou %an provi e wrap*content. an Ce Cant them to take up the remaining spa%e in the %olumn a$ter all other Ci gets have been allo%ate their spa%e.0 License Edition . 5his property in i%ates Chat proportion o$ the $ree spa%e shoul go to that Ci get. 5hese properties7 values have three $lavors* • @ou %an provi e a spe%i$i% imension. unless that is too big.ample. as they are in epen ent o$ s%reen siKe. Chi%h means the Ci get shoul $ill up its natural spa%e. you must also set android!layout*wei%$t.

$ you Cant to in%rease the Chitespa%e betCeen Ci gets. everything is le$t3 an top3aligne . %ommon gravity values are left.ts are aligne on the baseline &the invisible line that letters seem to Qsit onQ'.--Q. #o. !a ing is analogous to the margins on a Cor pro%essing o%ument N the page siKe might be 8. an right3aligne Ci gets respe%tively. the roC Cill start $lush on the le$t si e o$ the s%reen. (or a %olumn o$ Ci gets.0 License Edition .1Q area. Padding /y e$ault. . you nee to spe%i$y a gravity.com Special Creative Commons BY-SA 3. the e$ault is $or them to be aligne so their te. you %an tell the Ci get an its %ontainer hoC to align it vis a vis the s%reen. .BQ. 5he pa ing spe%i$ies hoC mu%h spa%e there is betCeen the boun aries o$ the Ci get7s Q%ellQ an the a%tual Ci get %ontents.Working 4ith Containers Gravity /y e$ault. at runtime on the Ci get7s +ava obOe%t'. but -Q margins Coul leave the a%tual te.t to resi e Cithin a 4. center*$ori'ontal.BQ. at runtime on the Ci get7s +ava obOe%t'. "sing android!layout*%ravity on a Ci get &or %alling set0ravity:.t to ea%h other.$ that is not Chat you Cant. though you may Cish to spe%i$y a gravity o$ center*vertical to %enter the Ci gets along the roC7s verti%al mi point. %entere . an ri%$t $or le$t3aligne . i$ you %reate a roC o$ Ci gets via a horiKontal +inear+ayout. you Cill Cant to use the android!paddin% property &or by %alling set1addin%:. $$ Subscribe to updates at http://commonsware. Ci gets are tightly pa%ke ne. (or a roC o$ Ci gets.

su%h as Lpx $or B pi. )ere is the layout* $/ Subscribe to updates at http://commonsware. .0 License Edition . Cith the Ci get7s %ontents itsel$ %entere Cithin that pa e 3out area. use android!paddin%+eft.ample &+inear' that shoCs +inear+ayout properties set both in the EML layout $ile an at runtime.Working 4ith Containers !igure 9< The relationship bet4een a 4idget6 its cell6 and the padding values 5he android!paddin% property alloCs you to set the same pa ing on all $our si es o$ the Ci get.$ you Cant the pa ing to i$$er on i$$erent si es. 5he value o$ the pa pa ing.els7 Corth o$ E. an android!paddin%6ottom. ing is a imension.com Special Creative Commons BY-SA 3. mple Let7s look at an e. android!paddin%-op. android!paddin%Ri%$t.

@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. 5he Radio0roup has Lpx o$ pa ing on all si es. Ce have Lpx o$ pa ing on all si es an a QnaturalQ height &android!layout*$ei%$t " #wrap*content#'.ample emonstrates neste bo.0 License Edition . so our e. )oCever. 5he bottom Radio0roup is a %olumn &android!orientation " #vertical#' o$ three Radio6utton Ci gets.com Special Creative Commons BY-SA 3. Ce $0 Subscribe to updates at http://commonsware. 5he Ci th an height are both set to wrap*content.android.es as i$ they Cere all +inear+ayout %ontainers. so the ra io buttons Cill only take up the spa%e that they nee .com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <Radio0roup android!id"#9Bid/orientation# android!orientation"#$ori'ontal# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!paddin%"#Lpx#& <Radio6utton android!id"#9Bid/$ori'ontal# android!text"#$ori'ontal# /& <Radio6utton android!id"#9Bid/vertical# android!text"#vertical# /& </Radio0roup& <Radio0roup android!id"#9Bid/%ravity# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!paddin%"#Lpx#& <Radio6utton android!id"#9Bid/left# android!text"#left# /& <Radio6utton android!id"#9Bid/center# android!text"#center# /& <Radio6utton android!id"#9Bid/ri%$t# android!text"#ri%$t# /& </Radio0roup& </+inear+ayout& 0ote that Ce have a +inear+ayout Crapping tCo Radio0roup sets. Again.Working 4ith Containers <>xml version"#?. separating it $rom the other Radio0roup. Radio0roup is a sub%lass o$ +inear+ayout. 5he top Radio0roup sets up a roC &android!orientation " #$ori'ontal#' o$ Radio6utton Ci gets.

d""R.setOnCheckedChangeListener:t$is.ri%$t.d""R.Radio0roup5 android.3.d""R.wid%et.wid%et.5 %ravity. meaning the %olumn o$ ra io buttons Q%laimsQ the entire Ci th o$ the s%reen.onCreate:icicle.app.0 License Edition .K. 8 super.id.verride public void onCreate:6undle icicle.main. 5o a Oust these settings at runtime base on user input.id.os.5 < public void onCheckedChanged:Radio0roup %roupG int c$ecked.5 // ri%$t < < $3 Subscribe to updates at http://commonsware.Working 4ith Containers have set android!layout*widt$ to be fill*parent.R.Activity5 android.6undle5 android.5 < else 8 orientation. 8 %ravity.com Special Creative Commons BY-SA 3. Ce nee some +ava %o e* packa%e com.left.id.d""R.5 %ravity":Radio0roup.5 orientation.center. 8 if :%roup""orientation.setGra ity:@x@L.wid%et.setOnCheckedChangeListener:t$is.$ori'ontal. 8 if :c$ecked.commonsware.layout.%ravity.5 < < else if :%roup""%ravity.-extCatc$er5 android.orientation.id.5 orientation":Radio0roup..)dit-ext5 +inear+ayoutDemo extends Activity Radio0roup.findViewById:R.CA+.5 // left < else if :c$ecked. 8 %ravity.text.setGra ity:@x@?.d.7)R-.nC$eckedC$an%e+istener 8 orientation5 %ravity5 public class implements Radio0roup Radio0roup 9.5 setContentView:R. 8 %ravity.setGra ity:@x@I.findViewById:R.5 // center*$ori'ontal < else if :c$ecked.setOrientation:+inear+ayout. 8 orientation.android./-A+.id.setOrientation:+inear+ayout. 8 if :c$ecked.containers5 import import import import import import android.id.+inear+ayout5 android.

the top Radio0roup a Ousts to mat%h* $7 Subscribe to updates at http://commonsware. Ce look up our tCo Radio0roup %ontainers an register a listener on ea%h. #in%e the a%tivity implements .com Special Creative Commons BY-SA 3.< The inear ayout. . &the %allba%k $or the listener'. so Ce are noti$ie Chen the ra io buttons %hange state &set.$ it Cas the orientation group.$ it Cas the gravity group.Working 4ith Containers < < . . .n onCreate:.$ Ce toggle on the Qverti%alQ ra io button. )ere is the result Chen it is $irst laun%he insi e the emulator* !igure (.nC$eckedC$an%e+istener:t$is. Ce a Oust the gravity base on the user7s sele%tion.emo sample application6 as initially launched .0 License Edition . Ce a Oust the orientation base on the user7s sele%tion.. Ce see Chi%h Radio0roup ha a state %hange.'. the a%tivity itsel$ is the listener.n onC$eckedC$an%ed:.nC$eckedC$an%e+istener.

Working 4ith Containers !igure ((< The same application6 4ith the vertical radio button selected .$ Ce toggle the Q%enterQ or QrightQ ra io buttons.com Special Creative Commons BY-SA 3.0 License Edition . the bottom Radio0roup a Ousts to mat%h* !igure (%< The same application6 4ith the vertical and center radio buttons selected $9 Subscribe to updates at http://commonsware.

as the name suggests. @ou %an pla%e Wi get E beloC an to the le$t o$ Wi get @. 5his is reminis%ent o$ +ames Illiot7s RelativeLayout $or use Cith +avaU#Cing. an so on. lays out Ci gets base upon their relationship to other Ci gets in the %ontainer an the parent %ontainer.0 License Edition . Concepts nd Properties 5o make all this Cork. or have Wi get M7s bottom e ge align Cith the bottom o$ the %ontainer. Ce nee Cays to re$eren%e other Ci gets Cithin an EML layout $ile.< The same application6 4ith the vertical and right radio buttons selected )ll Things )re 2elative Relative+ayout.Working 4ith Containers !igure (. Subscribe to updates at http://commonsware. plus Cays to in i%ate the relative positions o$ those Ci gets.com Special Creative Commons BY-SA 3. /.

/( Subscribe to updates at http://commonsware..n1arent • • says the Ci get positione horiKontally at the %enter o$ the %ontainer shoul be • says the Ci get shoul be positione verti%ally at the %enter o$ the %ontainer says the Ci get shoul be positione both horiKontally an verti%ally at the %enter o$ the %ontainer • All o$ these properties take a simple boolean value &true or false'. o$ the $orm 9Bid/. 0ote that the pa ing o$ the Ci get is taken into a%%ount Chen per$orming these various alignments.0 License Edition .Working 4ith Containers Positions Relative to Container 5he easiest relations to set up are tying a Ci get7s position to that o$ its %ontainer* • android!layout*ali%n1arent-op says the Ci get7s top shoul align Cith the top o$ the %ontainer • says the Ci get7s bottom shoul align Cith the bottom o$ the %ontainer android!layout*ali%n1arent6ottom android!layout*ali%n1arent+eft • says the Ci get7s le$t si e shoul align Cith the le$t si e o$ the %ontainer says the Ci get7s right si e shoul align Cith the right si e o$ the %ontainer android!layout*ali%n1arentRi%$t android!layout*center3ori'ontal android!layout*center7ertical android!layout*center. Relative Notation in Properties 5he remaining properties o$ relevan%e to Relative+ayout take as a value the i entity o$ a Ci get in the %ontainer.. 5he alignments are base on the Ci get7s overall %ell &%ombination o$ its natural spa%e plus the pa ing'. !ut i enti$iers &android!id attributes' on all elements that you Cill nee to a ress. 5o o this* -.com Special Creative Commons BY-SA 3.

i$ Wi get A is i enti$ie as 9Bid/wid%et*a.ample.. Positions Relative to Other Widgets 5here are $our properties that %ontrol position o$ a Ci get vis a vis other Ci gets* • in i%ates that the Ci get shoul above the Ci get re$eren%e in the property android!layout*above android!layout*below be pla%e be pla%e • in i%ates that the Ci get shoul beloC the Ci get re$eren%e in the property android!layout*to+eft • in i%ates that the Ci get shoul be pla%e to the le$t o$ the Ci get re$eren%e in the property in i%ates that the Ci get shoul be pla%e to the right o$ the Ci get re$eren%e in the property android!layout*toRi%$t • /eyon those $our. Re$eren%e other Ci gets using the same i enti$ier value Cithout the plus sign &9id/.com Special Creative Commons BY-SA 3.' (or e. there are $ive a itional properties that %an %ontrol one Ci get7s alignment relative to another* • in i%ates that the Ci get7s top shoul aligne Cith the top o$ the Ci get re$eren%e in the property android!layout*ali%n-op android!layout*ali%n6ottom be • in i%ates that the Ci get7s bottom shoul be aligne Cith the bottom o$ the Ci get re$eren%e in the property android!layout*ali%n+eft • in i%ates that the Ci get7s le$t shoul be aligne Cith the le$t o$ the Ci get re$eren%e in the property in i%ates that the Ci get7s right shoul be aligne Cith the right o$ the Ci get re$eren%e in the property android!layout*ali%nRi%$t android!layout*ali%n6aseline • • in i%ates that the baselines o$ the tCo Ci gets shoul be aligne /% Subscribe to updates at http://commonsware. Wi get / %an re$er to Wi get A in one o$ its oCn properties via the i enti$ier 9id/wid%et*a..0 License Edition .Working 4ith Containers 2.

Working 4ith Containers 5he last one is use$ul $or aligning labels an $iel s so that the te. An roi makes a single pass through your EML layout an %omputes the siKe an position o$ ea%h Ci get in se<uen%e.t o$ the label to be higher on3s%reen than the te.0 License Edition . let7s e.@# encodin%"#utf(A#>& <Relative+ayout xmlns!android"#$ttp!//sc$emas. )ere is the EML layout. #o.android. plus a pair o$ buttons labele Q>FQ an QCan%elQ. a label. pulle $rom the Relative sample proOe%t* <>xml version"#?. android!layout*ali%n-op Coul align the top o$ the $iel 7s bo. Ce nee to in%lu e android!layout*toRi%$t " #9id/wid%et*a# &assuming 9id/wid%et*a is the i entity o$ Wi get A'. #in%e $iel s have a bo.com Special Creative Commons BY-SA 3.t appears QnaturalQ. Chi%h Cill %ause the te.amine a typi%al Q$ormQ Cith a $iel . 5his has a $eC rami$i%ations* • @ou %annot re$eren%e a Ci get that has not been e$ine in the $ile yet @ou %are$ul that any uses o$ fill*parent in android!layout*widt$ or android!layout*$ei%$t o not Qeat upQ all the spa%e be$ore subse<uent Ci gets have been e$ine must be • E.t entere into the $iel . in the EML element $or Wi get /. i$ Ce Cant Wi get / to be positione to the right o$ Wi get A. Order of Evaluation What makes this even more %ompli%ate is the or er o$ evaluation.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!paddin%"#Lpx#& <-ext7iew android!id"#9Bid/label# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#2R+!# /. mple With all that in min . aroun them an labels o not. Subscribe to updates at http://commonsware. Cith the top o$ the label.

an have a B3 pi.n this %ase.0 License Edition . Ce a in the $iel . Ce Coul $in that the top o$ the $iel is %lippe o$$. Chi%h is $airly basi%.el pa ing on the label. have their te. by e$ault. only as mu%h height as Ce nee &android!layout*$ei%$t " #wrap*content#'. A$ter that. 0e.M# /& <6utton android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!layout*to+eft"#9id/ok# android!layout*ali%n-op"#9id/ok# android!text"#Cancel# /& </Relative+ayout& (irst. More on that in a moment. an $or the $iel to take up the rest o$ this QroCQ in the layout.el pa ing &android!paddin% " #Lpx#'. Ce e$ine the label. Ce Cant to use the $ull Ci th o$ the s%reen &android!layout*widt$ " #fill*parent#'.el pa betCeen the boun aries o$ the %ontainer an its %ontents &android!paddin% " #Lpx#'.t. e. 5hat7s be%ause o$ the B3pi. 5he android!layout*ali%n6aseline " #9id/label# simply aligns the baselines o$ the label an $iel .com Special Creative Commons BY-SA 3. 5hose are han le by three properties* • • • android!layout*toRi%$t " #9id/label# android!layout*ali%n6aseline " #9id/label# android!layout*ali%n6aseline " #9id/label# . .%ept $or its oCn B3pi. We Cant the $iel to be to the right o$ the label.ts aligne along the baseline. Ce open up the Relative+ayout. 5he label. has its top /$ Subscribe to updates at http://commonsware.Working 4ith Containers android!paddin%-op"#Lpx#/& <)dit-ext android!id"#9Bid/entry# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!layout*toRi%$t"#9id/label# android!layout*ali%n6aseline"#9id/label#/& <6utton android!id"#9Bid/ok# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!layout*below"#9id/entry# android!layout*ali%nRi%$t"#9id/entry# android!text"#.$ Ce Cere to skip the B3pi.el pa ing on the %ontainer itsel$.

so the label oes not appear • 8oing ba%k to the e. . as the android!layout*widt$ " #fill*parent# Qeats upQ the Ci th o$ the QroCQ.. an the label7s position is alrea y e$ine &be%ause it appeare $irst in the EML'. but not both. 5he solution to this %onun rum. the >F button is set to be beloC the $iel &android!layout*below " #9id/entry#' an have its right si e align Cith the right si e o$ the $iel &android!layout*ali%nRi%$t " #9id/entry#'. With no %hanges to the auto3generate +ava %o e.com Special Creative Commons BY-SA 3. 5his pushes the label oCn $ar enough that the $iel Cill not get %lippe . /ut the label is shorter than the $iel be%ause o$ the $iel 7s bo. you either have the top aligne properly or the baselines aligne properly. @ou %annot e$ine the $iel $irst. be%ause you %annot have tCo properties that both attempt to set the verti%al position o$ the $iel . #o. @ou may $in yoursel$ running into these sorts o$ problems as you try to get your Relative+ayout to behave the Cay you Cant it to. %lippe o$$ by the %ontainer7s pa ing.n this %ase. )ere are some QsolutionsQ that o not Cork* • @ou %annot use android!layout*ali%n1arent-op on the $iel .els7 o$ pa ing on the top. android!layout*ali%n1arent-op %on$li%ts Cith the later android!layout*ali%n6aseline " #9id/label# property. 5he Can%el button is set to be to the le$t o$ the >F button &android!layout*to+eft " #9id/ok#' an have its top aligne Cith the >F button &android!layout*ali%n-op " #9id/ok#'.Working 4ith Containers aligne Cith the top o$ the parent.0 License Edition . leaving no room $or the label. use in the EML layout shoCn above. is to give the label B pi. #in%e the $iel is epen ent on the label7s position. the emulator gives us* // Subscribe to updates at http://commonsware. the $iel Cin s up being too high an has the top o$ its bo. then put the label to the le$t o$ the $iel . an the last one in Cins.ample.

you Cill like An roi 7s -able+ayout N it alloCs you to position your Ci gets in a gri to your spe%i$i%ations. Cith the Ci gets themselves poure into one or more -ableRow %ontainers. @ou %ontrol the number o$ roCs an %olumns. plus hoC to han le Ci gets that live outsi e o$ roCs. Chi%h %olumns might shrink or stret%h to a%%ommo ate their %ontents. Ce nee to $igure out hoC Ci gets Cork Cith roCs an %olumns. an the like.emo sample application Tabula 2asa .$ you like )5ML tables. -able+ayout Corks in %onOun%tion Cith -ableRow. -able+ayout %ontrols the overall behavior o$ the %ontainer.Working 4ith Containers !igure ($< The 2elative ayout. an so on. /0 Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. sprea sheet gri s. one per roC in the gri . Concepts nd Properties (or all this to Cork.0 License Edition .

0 License Edition .n the above EML layout $ragment. there Cill be at least $our %olumns. >r inarily. one Cith three Ci gets. the label Coul go in the $irst %olumn &%olumn @. 5his is akin to the colspan attribute one $in s in table %ells in )5ML* <-ableRow& <-ext7iew android!text"#2R+!# /& <)dit-ext android!id"#9Bid/entry# android!layout*span"#I#/& </-ableRow& .M# /& </-ableRow& /3 Subscribe to updates at http://commonsware.Working 4ith Containers Putting Cells in Rows RoCs are e%lare by you. . #o i$ you have three roCs. one Cith tCo Ci gets. an one Cith $our Ci gets. )oCever. Ci gets are put into the $irst available %olumn. in i%ating the number o$ %olumns the Ci get spans. as %olumns are %ounte starting $rom @'. by An roi P you %ontrol the (irst. spe%i$ying the @3 base %olumn the Ci get belongs to* <-ableRow& <6utton android!id"#9Bid/cancel# android!layout*column"#H# android!text"#Cancel# /& <6utton android!id"#9Bid/ok# android!text"#.n the above $ragment. by putting Ci gets as %hil ren o$ a -ableRow insi e the overall -able+ayout. an the $iel Coul go into a spanne set o$ three %olumns &%olumns ? through I'. )oCever. you %an put a Ci get into a i$$erent %olumn via the android!layout*column property.com Special Creative Commons BY-SA 3. the eveloper. @ou. there Cill be at least one %olumn per Ci get in your longest roC. there$ore. %ontrol ire%tly hoC many roCs appear in the table. a Ci get %an take up more than one %olumn by in%lu ing the android!layout*span property. 5he number o$ %olumns are etermine number o$ %olumns in an in ire%t $ashion. the $iel spans three %olumns.

-able+ayout %ontains only -ableRow elements as imme iate %hil ren. >ne pattern $or this is to use a plain 7iew as a pi. ivi er &e. Again. 5he %olumns liste in this property Cill try to Cor 3Crap their %ontents to re u%e the e$$e%tive Ci th o$ the %olumn N by e$ault. /7 Subscribe to updates at http://commonsware. 5his helps i$ your %ontent is narroCer than the available spa%e. 5he value shoul be a single %olumn number &again. Ci gets are not Cor 3Crappe . it is possible to put other Ci gets in betCeen roCs. this shoul be a single %olumn number or a %omma3 elimite list o$ %olumn numbers. #ometimes. ea%h %olumn Cill be siKe a%%or ing to the QnaturalQ siKe o$ the Ci est Ci get in that %olumn &taking spanne %olumns into a%%ount'. <7iew as a tCo3 android!layout*$ei%$t " #Hpx# android!back%round " #D@@@@EE# /& "tret#h$ "hrin%$ and Collapse /y e$ault.com Special Creative Commons BY-SA 3.t available %olumn. Conversely. an you nee more %ontrol over %olumn behavior. the Can%el button goes in the thir %olumn &%olumn H'. 5he Ci gets automati%ally have their Ci th set to fill*parent.g. (or those Ci gets. Chi%h is the $ourth %olumn. so they Cill $ill the same spa%e that the longest roC oes. @ou %an pla%e an android!stretc$Columns property on the -able+ayout. @3base ' or a %omma3 elimite list o$ %olumn numbers. 5hose %olumns Cill be stret%he to take up any available spa%e yet on the roC.Working 4ith Containers . 5his helps i$ you have %olumns Cith potentially Cor y %ontent that might %ause some %olumns to be pushe o$$ the right si e o$ the s%reen.. Non-Row Children of Ta le!ayout 0ormally.0 License Edition .el3high blue bar a%ross the Ci th o$ the table'. 5he >F button then goes into the ne. )oCever. you %an pla%e a android!s$rinkColumns property on the -able+ayout. though. -able+ayout behaves a bit like +inear+ayout Cith verti%al orientation.n the pre%e ing EML layout $ragment. that oes not Cork out very Cell.

. you %an %ollapse an un3%ollapse %olumns by %alling setColumnCollapsed:. @ou might use this to alloC users to %ontrol Chi%h %olumns are o$ importan%e to them an shoul be shoCn versus Chi%h ones are less important an %an be hi en.M# /& </-ableRow& </-able+ayout& /9 Subscribe to updates at http://commonsware. meaning they Cill be part o$ the table in$ormation but Cill be invisible.Working 4ith Containers @ou %an also leverage an android!collapseColumns property on the -able+ayout. %an at runtime via E.@# encodin%"#utf(A#>& <-able+ayout xmlns!android"#$ttp!//sc$emas. on the -able+ayout. @ou also %ontrol stret%hing an shrinking setColumnStretc$able:. mple 5he EML layout $ragments shoCn above.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!stretc$Columns"#?#& <-ableRow& <-ext7iew android!text"#2R+!# /& <)dit-ext android!id"#9Bid/entry# android!layout*span"#I#/& </-ableRow& <7iew android!layout*$ei%$t"#Hpx# android!back%round"#D@@@@EE# /& <-ableRow& <6utton android!id"#9Bid/cancel# android!layout*column"#H# android!text"#Cancel# /& <6utton android!id"#9Bid/ok# android!text"#. Chen %ombine . !rogrammati%ally. give us a -able+ayout ren ition o$ the Q$ormQ Ce %reate $or Relative+ayout. Cith the a ition o$ a ivi er line betCeen the labelU$iel an the tCo buttons &$oun in the -able emo'* <>xml version"#?.com Special Creative Commons BY-SA 3. 5hese %olumns Cill start out Q%ollapse Q.android.0 License Edition . again Cith a %olumn number or %omma3 elimite list o$ %olumn numbers. an setColumnS$rinkable:.

. the rest available via s%rolling. @ou %an take a layout that might be too big $or some s%reens. the rest available via s%rolling up or oCn.isting layout logi%.emo sample application Scroll4ork !hone s%reens ten to be small.0 License Edition . Ce get* !igure (/< The Table ayout. Subscribe to updates at http://commonsware. here is a Scroll7iew use in an EML layout $ile &$rom the Scroll emo'* 0.ample.Working 4ith Containers When %ompile against the generate +ava %o e an run on the emulator. an still use your e.t Oust so happens that the user %an only see part o$ your layout at one time. >ne tri%k $or oing this is to use s%rolling. Scroll7iew (or e. Crap it in a Scroll7iew. is a %ontainer that provi es s%rolling $or its %ontents.com Special Creative Commons BY-SA 3. Chi%h re<uires evelopers to use some tri%ks to present a lot o$ in$ormation in the limite available spa%e. so only part o$ the in$ormation is visible at one time.

com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content#& <-able+ayout android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!stretc$Columns"#@#& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#D@@@@@@#/& <-ext7iew android!text"#D@@@@@@# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#DNN@@@@# /& <-ext7iew android!text"#DNN@@@@# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#DAANN@@# /& <-ext7iew android!text"#DAANN@@# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#DaaAANN# /& <-ext7iew android!text"#DaaAANN# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#DffaaAA# /& <-ext7iew android!text"#DffaaAA# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#Dffffaa# /& <-ext7iew android!text"#Dffffaa# android!paddin%+eft"#Npx# 0( Subscribe to updates at http://commonsware.@# encodin%"#utf(A#>& <Scroll7iew xmlns!android"#$ttp!//sc$emas.android.com Special Creative Commons BY-SA 3.Working 4ith Containers <>xml version"#?.0 License Edition .

Working 4ith Containers android!layout*%ravity"#center*vertical# /& </-ableRow& <-ableRow& <7iew android!layout*$ei%$t"#A@px# android!back%round"#Dffffff# /& <-ext7iew android!text"#Dffffff# android!paddin%+eft"#Npx# android!layout*%ravity"#center*vertical# /& </-ableRow& </-able+ayout& </Scroll7iew& Without the Scroll7iew. 5here may be some evi%es Cith s%reens %apable o$ shoCing that mu%h in$ormation. but only present part o$ it at a time. you see* !igure (0< The ScrollGie4. >n the sto%k An roi emulator.emo sample application 0% Subscribe to updates at http://commonsware.els ea%h. 5he Scroll7iew lets us keep the table as3is. the table Coul take up at least B40 pi.com Special Creative Commons BY-SA 3.0 License Edition . base on the 7iew e%larations'. Chen the a%tivity is $irst vieCe . but many Cill be smaller.els &2 roCs at 80 pi.

0.com Special Creative Commons BY-SA 3. you %an s%roll up an oCn to see the remaining roCs. /y pressing the upU oCn buttons on the ire%tional pa .Working 4ith Containers 0oti%e hoC only $our roCs an part o$ the $i$th are visible. Subscribe to updates at http://commonsware.0 License Edition .

0 License Edition .com Special Creative Commons BY-SA 3.Subscribe to updates at http://commonsware.

a apters provi e a %ommon inter$a%e to the ata mo el behin a sele%tion3style Ci get. rop3 oCn lists.0 License Edition .s.g. in An roi 7s %ase.com Special Creative Commons BY-SA 3. Classi% ". 0/ Subscribe to updates at http://commonsware. su%h as the ra io buttons seen earlier. toolkits have listbo.es. plus others o$ parti%ular interest $or mobile evi%es &e. su%h as numeri%3only or phone3number3only.ible $rameCork $or etermining Chat %hoi%es are available in these Ci gets. you saC hoC $iel s %oul have %onstraints pla%e upon them to limit possible input.amining save photos'. An roi o$$ers a $le. More spe%i$i%ally. 5hese sorts o$ %onstraints help users Qget it rightQ Chen entering in$ormation. An roi o$$ers a $rameCork o$ ata a apters that provi e a %ommon inter$a%e to sele%tion lists ranging $rom stati% arrays to atabase %ontents..es. )dapting to the Circumstances . #ele%tion vieCs N Ci gets $or presenting lists o$ %hoi%es N are han e an a apter to supply the a%tual %hoi%es. su%h as a listbo. a apters provi e a %ommon inter$a%e to multiple isparate A!. %ombobo. An roi has many o$ the same sorts o$ Ci gets. Moreover.. the 0allery $or e. #pe%i$i%ally. the ultimate in %onstraine input is to sele%t a %hoi%e $rom a set o$ items.n the abstra%t. >$ %ourse. parti%ularly on a mobile evi%e Cith %rampe keyboar s.CHAPTER / >sing Selection Widgets /a%k in the %hapter on basi% Ci gets. an the like $or that very purpose.

in +avaU#Cing. on the obOe%ts in the list an Crap ea%h o$ those strings in the vieC esignate by the supplie resour%e. an you have a $ully3 $un%tioning a apter* Strin%OP items"8#t$is#G #is#G #a#G #really#G #silly#G #list#<5 new ArrayAdapter<Strin%&:t$isG android.g. Chi%h in turn %onverts strings $or the list into =C$eck6ox3plus3=+abel %omposite Ci gets. An roi 7s a apters are responsible $or provi ing the roster o$ ata $or a sele%tion Ci get plus %onverting in ivi ual elements o$ ata into spe%i$i% vieCs to be isplaye insi e the sele%tion Ci get. but in reality it is not that i$$erent $rom other 8".R. plus label. an +ava is $ar $rom the only environment o$$ering this sort o$ abstra%tion &e.0 License Edition . an %li%ks a Oust the state o$ the %he%kbo.layout.5 5he ArrayAdapter %onstru%tor takes three parameters* • • 5he Context to use &typi%ally this Cill be your a%tivity instan%e' 5he resour%e . to a%tually be a %he%klist &Chere in ivi ual roCs are a %he%kbo.simple*list*item*?G items. i$ you Cant a =+ist3ba%ke listbo. (or e. (le. android..nternet'. +avaU#Cing7s mo el a apters $or =-able'.A.com Special Creative Commons BY-SA 3.R. 5he latter $a%et o$ the a apter system may soun a little o .ample. to supply your oCn +istCellRenderer. +sin! Arr yAd pter 5he easiest a apter to use is ArrayAdapter N all you nee to o is Crap one o$ these aroun a +ava array or java.simple*list*item*? simply turns those strings 00 Subscribe to updates at http://commonsware.util. the ArrayAdapter Cill invoke toStrin%:. you inevitably Cin up %alling setCellRenderer:. as shoCn above' 5he a%tual array or list o$ items to shoC • /y e$ault.7s EML ata3bin ing $rameCork a%%epts EML inline as stati% ata or retrieve $rom the ..+ist instan%e.layout.A o$ a vieC to use &su%h as a built3in system resour%e .g.>sing Selection Widgets 5his use o$ +ava inter$a%es is $airly %ommon &e.'. toolkits7 Cays o$ overri ing e$ault isplay behavior.

Cill be shoCn the list or spinner or Chatever Ci get uses this ArrayAdapter. typi%ally $rom a %ontent provi er. you nee to instantiate your oCn' 5he Ci get that Cill %ontain this vieC.setText:!uildString"or:position.>sing Selection Widgets into -ext7iew obOe%ts. the a apter still returns a -ext7iew.t sample appli%ation emonstrates using a more %ompli%ate %ustom vieC $or a list a apter. ea%h o$ Chi%h Cill be %overe in greater etail later in this book* • CursorAdapter %onverts a Cursor. @ou %an sub%lass ArrayAdapter an vieCs* overri e %et7iew:. but uses a i$$erent behavior $or etermining the string that goes in the vieC.5 < convert7iew.iste .0 License Edition . 0ther 1ey Ad pters )ere are some other a apters in An roi that you Cill likely use.isting vieC to up ate Cith the ata $or this position &i$ one alrea y e. %et7iew:.ample shoCn above. su%h as $rom s%rolling N i$ null. i$ nee e $or instantiating the vieC • . 5hose -ext7iew Ci gets.5 )ere. re%eives three parameters* • • 5he in e. o$ the item in the array to shoC in the vieC An e.5 < return:convert7iew. 8 if :convert7iew""null. 5he 5our.n the e. into something that %an be isplaye in a sele%tion vieC SimpleAdapter %onverts • ata $oun in EML resour%es 03 Subscribe to updates at http://commonsware..com Special Creative Commons BY-SA 3. 8 convert7iew"new TextView:t$is. to Qroll your oCnQ public 7iew getView:int positionG 7iew convert7iewG 7iew0roup parent. in turn.

here is a layout pulle $rom the +ist sample proOe%t* <>xml version"#?. Ci get in An roi is knoCn as +ist7iew. With that.$ you o Cant to %ustomiKe the layout.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.n%lu e one o$ these in your layout. you might Cell %onsi er %reating your a%tivity as a sub%lass o$ +istActivity. 07 Subscribe to updates at http://commonsware. . an atta%h a listener via set..t is Oust a list Cith a label on top to shoC the %urrent sele%tion. )oCever. . invoke setAdapter:. to $in out Chen the sele%tion has %hange . i$ your a%tivity is ominate by a single list.n.>sing Selection Widgets • an Activity. you %an.$ your main vieC is Oust the list.com Special Creative Commons BY-SA 3. to supply your ata an %hil vieCs. you have a $ully3$un%tioning listbo.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content#/& <+ist7iew android!id"#9android!id/list# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!drawSelector. rather than the regular Activity base %lass. .temSelected+istener:.conAdapter provi e you Cith the names or i%ons o$ a%tivities that %an be invoke upon a parti%ular intent ActivityAdapter ists of 5aughty and 5ice 5he %lassi% listbo.ample.android.n-op"#false# /& </+inear+ayout& .0 License Edition . (or e. so long as you i enti$y your +ist7iew as 9android!id/list. so +istActivity knoCs Chi%h Ci get is the main list $or the a%tivity. you o not even nee to supply a layout N +istActivity Cill %onstru%t a $ull3s%reen list $or you.

simple*list*item*?G items. an take appropriate steps base on the supplie %hil vieC an position &in this %ase.R.5 setContentView:R.0 License Edition .onCreate:icicle.5 < public void onListItemClick:+ist7iew parentG 7iew vG int positionG lon% id.layout.t $or that position'.5 < < With +istActivity.findViewById:R.com Special Creative Commons BY-SA 3. 8 selection. 5o $in out Chen the list sele%tion %hanges.id. N in this %ase.. 5he resultsD 09 Subscribe to updates at http://commonsware. Q/ 9.layout. provi ing an ArrayAdapter Crapping an array o$ nonsense strings.5 setList#dapter:new ArrayAdapter<Strin%&:t$isG android. up ating the label Cith the te.selection.5 selection":-ext7iew.main. 8 super.setText:itemsOpositionP.verride public void onCreate:6undle icicle.>sing Selection Widgets 5he +ava %o e to %on$igure the list an %onne%t the list Cith the label is* public class +ist7iewDemo extends +istActivity 8 -ext7iew selection5 Strin%OP items"8#lorem#G #ipsum#G #dolor#G #sit#G #amet#G #consectetuer#G #adipiscin%#G #elit#G #morbi#G #vel#G #li%ula#G #vitae#G #arcu#G #aliJuet#G #mollis#G #etiam#G #vel#G #erat#G #placerat#G #ante#G #porttitor#G #sodales#G #pellentesJue#G #au%ue#G #purus#<5 /QQ Called wit$ t$e activity is first created.temClick:. you %an set the list a apter via set+istAdapter:. overri e on+ist.

by e$ault.pan e Spinner itsel$ provi es. an hook in a listener obOe%t $or sele%tions via set. the Spinner is the e<uivalent o$ the rop3 oCn sele%tor you might $in in other toolkits &e.$ you Cant to tailor the vieC use Chen isplaying the rop3 oCn perspe%tive. 3. !ressing the le$t an right buttons on the A3pa iterates over %hil ren.n. you provi e the a apter $or ata an %hil vieCs via setAdapter:. a small list &akin to a +ist7iew' appears to shoC a $eC items at a time. metho to supply the resour%e .0 License Edition .A o$ the vieC to use.>sing Selection Widgets !igure (3< The istGie4. Subscribe to updates at http://commonsware. instea o$ the one3item3at3a3time perspe%tive the une. not the Spinner Ci get. !ressing the %enter button on the A3pa isplays.com Special Creative Commons BY-SA 3.. . =Combo6ox in +avaU#Cing'. "se the setDropDown7iewResource:.n An roi ..g.temSelected+istener:. As Cith +ist7iew. you nee to %on$igure the a apter.emo sample application Spin Control .

id.simple*list*item*?G 3( Subscribe to updates at http://commonsware..com Special Creative Commons BY-SA 3.5 selection":-ext7iew.layout.n-op %ontrols Chether the arroCs are raCn on the sele%tor button on the right si e o$ the Spinner ". here is an EML layout $or a simple vieC Cith a Spinner* <>xml version"#?.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.5 ArrayAdapter<Strin%& aa"new ArrayAdapter<Strin%&:t$isG android.5 Spinner spin":Spinner.setOnItemSelectedListener:t$is.main. Ce nee some +ava %o e* public class SpinnerDemo extends Activity implements Adapter7iew.findViewById:R.layout.0 License Edition .verride public void onCreate:6undle icicle. Oust Cith a Spinner instea o$ a +ist7iew. 8 super.spinner.R. %ulle $rom the Spinner sample proOe%t.>sing Selection Widgets (or e.. 5o populate an use the Spinner.5 spin.selection.android.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <Spinner android!id"#9Bid/spinner# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!drawSelector. 5he Spinner property android!drawSelector.findViewById:R.n.onCreate:icicle.id.ample.5 setContentView:R.temSelected+istener 8 -ext7iew selection5 Strin%OP items"8#lorem#G #ipsum#G #dolor#G #sit#G #amet#G #consectetuer#G #adipiscin%#G #elit#G #morbi#G #vel#G #li%ula#G #vitae#G #arcu#G #aliJuet#G #mollis#G #etiam#G #vel#G #erat#G #placerat#G #ante#G #porttitor#G #sodales#G #pellentesJue#G #au%ue#G #purus#<5 9.n-op"#true# /& </+inear+ayout& 5his is the same vieC as shoCn in the previous se%tion.

Ce implement the %allba%ks re<uire by .layout.setDropDownView$esource: android.5 < public void onItemSelected:Adapter7iew parentG 7iew vG int positionG lon% id. We %on$igure the a apter not only Cith the list o$ $ake Cor s. (inally.n.simple*spinner*dropdown*item.'. Ce atta%h the a%tivity itsel$ as the sele%tion listener &spin.setText:##.R.com Special Creative Commons BY-SA 3.5 < public void on%othingSelected:Adapter7iew parent.'.0 License Edition . 5his Corks be%ause the a%tivity implements the .5 < < )ere.>sing Selection Widgets items.set#dapter:aa.5 aa. What Ce get is* 3% Subscribe to updates at http://commonsware.temSelected+istener:t$is. but also Cith a spe%i$i% resour%e to use $or the rop3 oCn vieC &via aa.setDropDown7iewResource:.set.n.n. 8 selection. 8 selection.temSelected+istener inter$a%e.temSelected+istener to a Oust the sele%tion label base on user input.setText:itemsOpositionP.5 spin.

>sing Selection Widgets !igure (7< The Spinner. Subscribe to updates at http://commonsware.emo sample application6 as initially launched !igure (9< The same application6 4ith the spinner drop"do4n list displayed 3.com Special Creative Commons BY-SA 3.0 License Edition .

3$ Subscribe to updates at http://commonsware. i$ you supply a value o$ auto*fit.els. 5here are a $eC properties Chi%h. the three %olumns Cill ea%h e.els Ci e ea%h %olumn shoul be.els Ci e. suppose the s%reen is ?20 pi.pan by ?3= pi. the tCo Chitespa%es Cill ea%h groC by B pi. $or gri s Cith auto*fit $or shoul happen $or any available spa%e not taken up by %olumns or spa%ing N this shoul be columnCidt$ to have the %olumns take up available spa%e or spacin%Cidt$ to have the Chitespa%e betCeen %olumns absorb e. An roi Cill %ompute the number o$ %olumns base on available spa%e an the properties liste beloC. With android!stretc$Mode set to spacin%Cidt$.els o$ Chitespa%e there shoul be betCeen items in the gri . android!numColumns android!verticalSpacin% android!$ori'ontalSpacin% android!columnCidt$ • an its %ounterpart in i%ate hoC many pi. 5hree %olumns Coul use ?-0 pi. or. Chat 0ote the properties android!verticalSpacin%.els.els'.els to %onsume the remaining -0 pi. • • i%ates. that android!stretc$Mode in android!numColumns.els. (or e.com Special Creative Commons BY-SA 3. @ou have mo erate %ontrol over the number an siKe o$ the %olumnsP the number o$ roCs is ynami%ally etermine base on the number o$ items the supplie a apter says are available $or vieCing.ample. at the time o$ this Criting. Chen %ombine .els &three %olumns o$ -00 pi. in i%ates hoC many pi. android!$ori'ontalSpacin%.>sing Selection Widgets 'rid -our ions #+r Something ike That<<<& As the name suggests. etermine the number o$ %olumns an their siKes* • spells out hoC many %olumns there are.els to use up the remaining -0 pi. an Ce have android!columnCidt$ set to ?@@ an android!$ori'ontalSpacin% set to L. With android!stretc$Mode set to columnCidt$. 0rid7iew gives you a tCo3 imensional gri o$ items to %hoose $rom.0 License Edition . not a imension.tra spa%e.els an tCo Chitespa%es o$ B pi. an android!columnCidt$ all take a simple number pi.

@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. here is a EML layout $rom the 0rid sample proOe%t. 5he number o$ %olumns is %ompute by An roi &android!numColumns " #auto*fit#' base on B3pi.temSelected+istener:. et%. to provi e the ata an %hil vieCs. (or e.%ept $or Chat our sele%tion label re<uires. shoCing a 0rid7iew %on$iguration* <>xml version"#?.el %olumns &android!columnCidt$ " #?@@#'.com Special Creative Commons BY-SA 3.>sing Selection Widgets >therCise.temSelected+istener 8 -ext7iew selection5 Strin%OP items"8#lorem#G #ipsum#G #dolor#G #sit#G #amet#G #consectetuer#G #adipiscin%#G #elit#G #morbi#G #vel#G 3/ Subscribe to updates at http://commonsware. the 0rid7iew Corks mu%h like any other sele%tion Ci get N use setAdapter:. Cith the %olumns absorbing any QslopQ Ci th le$t over &android!stretc$Mode " #columnCidt$#'. 5he +ava %o e to %on$igure the 0rid7iew is* public class 0ridDemo extends Activity implements Adapter7iew.n. -003pi. invoke set.ample.n. to register a sele%tion listener.el horiKontal spa%ing &android!$ori'ontalSpacin% " #L#'.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <0rid7iew android!id"#9Bid/%rid# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!verticalSpacin%"#IL# android!$ori'ontalSpacin%"#L# android!numColumns"#auto*fit# android!columnCidt$"#?@@# android!stretc$Mode"#columnCidt$# android!%ravity"#center# /& </+inear+ayout& (or this gri .0 License Edition . Ce take up the entire s%reen e.android..

findViewById:R.R.setOnItemSelectedListener:t$is..findViewById:R.convert7iew5 if :convert7iew""null. 8 super. 8 selection.com Special Creative Commons BY-SA 3. 8 selection.convert7iew5 < label.id.5 30 Subscribe to updates at http://commonsware.main.layout. 8 super:ctxtG resourceG items.%rid.setText:itemsOpositionP.onCreate:icicle. 8 -ext7iew label":-ext7iew.5 label":-ext7iew. 8 convert7iew"new TextView:ctxt.5 < public void onItemSelected:Adapter7iew parentG 7iew vG int positionG lon% id.5 selection":-ext7iew.5 0rid7iew %":0rid7iew.selection.verride public void onCreate:6undle icicle.id.set#dapter:new "unnyLooking#dapter:t$isG android.5 < public void on%othingSelected:Adapter7iew parent.5 < < < return:convert7iew.5 setContentView:R.5 %.5 %.simple*list*item*?G items.>sing Selection Widgets #li%ula#G #vitae#G #arcu#G #aliJuet#G #mollis#G #etiam#G #vel#G #erat#G #placerat#G #ante#G #porttitor#G #sodales#G #pellentesJue#G #au%ue#G #purus#<5 9.setText:##.0 License Edition .setText:itemsOpositionP.ctxt"ctxt5 public 7iew getView:int positionG 7iew convert7iewG 7iew0roup parent.5 < private class Eunny+ookin%Adapter extends ArrayAdapter 8 Context ctxt5 "unnyLooking#dapter:Context ctxtG int resourceG Strin%OP items.layout.5 < t$is.

Ce Crap the $unny3looking strings in our oCn -ext7iew Ci gets. With the ?B3pi.0 License Edition . the gri over$loCs the boun aries o$ the emulator7s s%reen* !igure %..>sing Selection Widgets (or the gri %ells.com Special Creative Commons BY-SA 3.n this %ase.tP otherCise.emo sample application6 as initially launched 33 Subscribe to updates at http://commonsware.< The 'rid. by sub%lassing ArrayAdapter an overri ing %et7iew:. Ce Oust reset its te. . . Ce %reate our oCn vieCs.el verti%al spa%ing $rom the EML layout &android!verticalSpacin% " #IL#'. Ce %reate a neC -ext7iew instan%e an populate it. re%eives a -ext7iew.$ %et7iew:. Oust to be i$$erent. rather than using auto3generate -ext7iew Ci gets as in the previous se%tions.

the te. Mat%hes are shoCn in a sele%tion list that. sub%lasses )dit7iew.n a ition. @ou %an give AutoComplete-ext7iew an a apter %ontaining the list o$ %an i ate values via setAdapter:. $ilter.. as the user types.t is treate as a pre$i. With auto3%ompletion. 5he user %an either type out an entry &e. %omparing the entere te. to in i%ate the minimum number o$ %hara%ters a user must enter be$ore the list $iltering begins. )oCever. sin%e the user %oul type 37 Subscribe to updates at http://commonsware.0 License Edition .t as a pre$i. something not in the list' or %hoose an entry $rom the list to be the value o$ the $iel . su%h as $ont $a%e an %olor. AutoComplete-ext7iew . against a list o$ %an i ates..>sing Selection Widgets !igure %(< The same application6 scrolled to the bottom of the grid !ieldsH 5o4 With . like Cith Spinner.g. so you %an %on$igure all the stan ar look3an 3$eel aspe%ts. AutoComplete-ext7iew has a android!completion-$res$old property.com Special Creative Commons BY-SA 3./I ess Typing! 5he AutoComplete-ext7iew is sort o$ a hybri betCeen the )dit7iew &$iel ' an the Spinner. $ol s oCn $rom the $iel .

5 selection":-ext7iew.findViewById:R.verride public void onCreate:6undle icicle.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. 8 super. to be noti$ie Chen the te.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <AutoComplete-ext7iew android!id"#9Bid/edit# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!completion-$res$old"#I#/& </+inear+ayout& 5he %orrespon ing +ava %o e is* public class AutoCompleteDemo extends Activity implements -extCatc$er 8 -ext7iew selection5 AutoComplete-ext7iew edit5 Strin%OP items"8#lorem#G #ipsum#G #dolor#G #sit#G #amet#G #consectetuer#G #adipiscin%#G #elit#G #morbi#G #vel#G #li%ula#G #vitae#G #arcu#G #aliJuet#G #mollis#G #etiam#G #vel#G #erat#G #placerat#G #ante#G #porttitor#G #sodales#G #pellentesJue#G #au%ue#G #purus#<5 9.5 edit. 5hese events Cill o%%ur either be%ause o$ manual typing or $rom a sele%tion $rom the rop3 oCn list. /eloC Ce have a $amiliar3looking EML layout. AutoComplete-ext7iew oes not support sele%tion listeners. like you %an Cith any )dit7iew. you %an register a -extCatc$er.set#dapter:new ArrayAdapter<Strin%&:t$isG 39 Subscribe to updates at http://commonsware.onCreate:icicle.id.id.edit.0 License Edition .t %hanges.selection.findViewById:R.>sing Selection Widgets something not in the list.5 edit.layout.android.addTextChangedListener:t$is. .5 edit":AutoComplete-ext7iew.com Special Creative Commons BY-SA 3. this time %ontaining an AutoComplete-ext7iew &pulle $rom the AutoComplete sample appli%ation'* <>xml version"#?.5 setContentView:R.nstea .main.

R. an before-extC$an%ed:.0 License Edition . )ere Ce have the results* !igure %%< The )utoComplete. Subscribe to updates at http://commonsware. Ce are only intereste in the $ormer.setText:edit. our a%tivity implements -extCatc$er.layout.simple*list*item*?G items.5 < public void !eforeTextChanged:C$arSeJuence sG int startG int countG int after.getText:.>sing Selection Widgets < android.n this %ase. Chi%h means our %allba%ks are on-extC$an%ed:. 8 selection.5 public void onTextChanged:C$arSeJuence sG int startG int beforeG int count. . an Ce up ate the sele%tion label to mat%h the AutoComplete-ext7iew7s %urrent %ontents.. 8 // needed for interfaceG but not used < < 5his time..emo sample application6 as initially launched 7.com Special Creative Commons BY-SA 3..

>sing Selection Widgets !igure %.0 License Edition .com Special Creative Commons BY-SA 3.< The same application6 after a fe4 matching letters 4ere entered6 sho4ing the auto"complete drop"do4n !igure %$< The same application6 after the auto"complete value 4as selected 7( Subscribe to updates at http://commonsware.

t a%ross the horiKontal plane.n your EML layout. the 0allery lets people previeC the pi%tures in the pro%ess o$ %hoosing one. otherCise users Cill not be able to rea the sele%tion 7% Subscribe to updates at http://commonsware. you have a $eC properties at your isposal* • android!spacin% %ontrols the number o$ pi.>sing Selection Widgets 'alleries6 'ive +r Take The )rt 5he 0allery Ci get is not one or inarily $oun in 8".com Special Creative Commons BY-SA 3. be sure that your sele%tor has su$$i%ient • transparen%y to shoC the %hil through the sele%tor. the 0allery Corks mu%h like a Spinner or 0rid7iew.. .n-op in i%ates i$ the sele%tion bar &or Drawable' shoul be raCn be$ore &false' or a$ter &true' raCing the sele%te %hil N i$ you %hoose true. >ne %hoi%e $olloCs the ne. 5he <uintessential e. one rotates through the options through the le$t an right A3pa buttons.ample use $or the 0allery is image previeC N given a %olle%tion o$ photos or i%ons. in e$$e%t.0 License Edition . >n an An roi evi%e. toolkits. Compare to the Spinner.t is. Compare to the +ist7iew.els betCeen entries in the list • android!spinnerSelector %ontrols Chat is use to in i%ate a sele%tion N this %an either be a re$eren%e to a Drawable &see the resour%es %hapter' or an R8/ value in DAARR0066 or similar notation android!drawSelector. the 0allery alCays shoCs more than one %hoi%e at a time. . Cith the %urrently3sele%te item highlighte . the 0allery takes up less s%reen spa%e Chile still shoCing multiple %hoi%es at one time &assuming they are short enough'. Co e3Cise. a horiKontally3lai 3out listbo.

appli%ations. but also are Ci ely use in buil ing 8".t minimiKes keystrokes an s%reen taps.CHAPTER 2 Employing !ancy Widgets and Containers 5he Ci gets an %ontainers %overe to ate are not only $oun in many 8". entering a letter somepla%e Chere only numbers are e. Chether Web3base .0 License Edition . -ime1ickerDialo%' $or helping users enter ates an times. or mobile. phone numbers. An roi also supports Ci gets &Date1icker. in the $orm o$ a year. toolkits &in one $orm or $ashion'. et%. esktop. As shoCn previously. @ou %an 7.com Special Creative Commons BY-SA 3. . plus re u%es the %han%e o$ making some sort o$ error &e. 5he Ci gets an %ontainers in this %hapter are a little less Ci ely use . an ay o$ month value. month.g. having Ci gets an ialogs that are aCare o$ the type o$ stu$$ somebo y is suppose to be entering is very help$ul.. -ime1icker' an ialogs &Date1ickerDialo%. 5he Date1icker an Date1ickerDialo% alloC you to set the starting ate $or the sele%tion. )dit7iew has %ontent3aCare $lavors $or entering in numbers. Pick and Choose With limite 3input evi%es like phones. 0ote that the month runs $rom @ $or +anuary through ?? $or Ae%ember. Subscribe to updates at http://commonsware. though you Cill likely $in many to be <uite use$ul.pe%te '.

Chi%h is supplie to you in the $orm o$ an hour an minute • • (or e. parti%ularly i$ you are using the ialog.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/dateAnd-ime# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <6utton android!id"#9Bid/date6tn# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!text"#Set t$e Date# /& <6utton android!id"#9Bid/time6tn# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!text"#Set t$e -ime# 7$ Subscribe to updates at http://commonsware.Employing !ancy Widgets and Containers also %hoose the ay on Chi%h a Ceek QbeginsQ N the tra itional "# %alen ar has Ceeks beginning on a #un ay &S2/DAF'.t is up to you to store that ate somepla%e. here7s a trivial layout %ontaining a label an tCo buttons N the buttons Cill pop up the ialog $lavors o$ the ate an time pi%kers* <>xml version"#?.n-imeSet+istener' to be noti$ie o$ Chen the user has %hosen a neC time.android. sin%e there is no other Cay $or you to get at the %hosen ate later on. in the $orm o$ an hour &@ through HI' an a minute &@ through LR' in i%ate i$ the sele%tion shoul be in -23hour mo e Cith an AMU!M toggle. -ime1icker an -ime1ickerDialo% let you* • set the initial time the user %an a Oust.ample.0 License Edition . Most importantly.nDateSet+istener' Chere you are in$orme o$ a neC ate sele%te by the user. . ea%h let you provi e a %allba%k obOe%t &. $rom the C$rono sample proOe%t.com Special Creative Commons BY-SA 3.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. or in 2=3hour mo e &Chat in the "# is thought o$ as Qmilitary timeQ an in the rest o$ the Corl is thought o$ as Qthe Cay times are suppose to beQ' provi e a %allba%k obOe%t &. #imilarly.

n-imeSet+istener t"new -ime1icker.id.5 Date1icker.findViewById:R.onCreate:icicle.set:Calendar.3. 8 public void onClick:7iew v. 8 public void timeSet:-ime1icker viewG int $our.5 dateAnd-ime.E*M.5 updateLa!el:.get:Calendar. 8 new Date&ickerDialog:C$ronoDemo.S2/DAF.fMont$.5 btn":6utton.verride public void onCreate:6undle icicle.t$isG tG #Set t$e time#G dateAnd-ime.G dateAnd-ime.E*M.OnTimeSetListener:. 8 dateAnd-ime.DAF*.getInstance:.5 btn.OnClickListener:.get:Calendar. 8 dateAnd-ime.OnClickListener:.t$isG dG dateAnd-ime. 8 public void dateSet:Date1icker viewG int yearG int mont$.5 dateAnd-ime.setOnClickListener:new 7iew.2RG $our. 8 new Time&ickerDialog:C$ronoDemo.M.M.get:Calendar.findViewById:R.fFearG int day.0 License Edition .set:Calendar.M.5 updateLa!el:..fDay.5 < <5 9.3.setOnClickListener:new 7iew. 8 public void onClick:7iew v. 8 super.show:.set:Calendar.get:Calendar.G dateAnd-ime.com Special Creative Commons BY-SA 3.id./-3./-3G mont$.fMont$.G Calendar./-3.set:Calendar...5 btn.5 < <./2-).5 dateAnd-ime.DAF*.5 setContentView:R./-3G day.M.F)AR.5 6utton btn":6utton.2R.5 < <5 -ime1icker.nDateSet+istener d"new Date1icker.get:Calendar.OnDateSetListener:.Employing !ancy Widgets and Containers /& </+inear+ayout& 5he more interesting stu$$ %omes in the +ava sour%e* public class C$ronoDemo extends Activity 8 DateEormat fmtDateAnd-ime"DateEormat.G dateAnd-ime.main.G 7/ Subscribe to updates at http://commonsware./2-)G minute.fDayG int minute.set:Calendar.time6tn.5 -ext7iew dateAnd-ime+abel5 Calendar dateAnd-ime"Calendar.getDateTimeInstance:.F)ARG year.fFear.date6tn.layout.

an put it in the -ext7iew. Ia%h button is given a .getTime:. getting the values out o$ the Calendar. . 8 dateAnd-ime+abel. With all this Cire together.0 License Edition .5 < <..5 < private void updateLa!el:. We also give the ialog the last3sele%te ate. Ce take the %urrent Calendar. When the button is %li%ke . month.. Ce give it a .5 dateAnd-ime+abel":-ext7iew. it gets a . metho .n the %ase o$ the -ime1ickerDialo%.Employing !ancy Widgets and Containers true.id.com Special Creative Commons BY-SA 3. either a Date1ickerDialo% or a -ime1ickerDialo% is shoCn. the resulting a%tivity looks like this* 70 Subscribe to updates at http://commonsware.nDateSet+istener %allba%k that up ates the Calendar Cith the neC ate &year. . an a true in i%ating Ce Cant 2=3hour mo e on the time sele%tor..5 < < 5he Qmo elQ $or this a%tivity is Oust a Calendar instan%e.dateAnd-ime.format:dateAnd-ime. . We pour it into the vieC via a DateEormat $ormatter.nClick+istener %allba%k obOe%t.setText:fmtDateAnd-ime . initially set to be the %urrent ate an time. ay o$ month'.findViewById:R.n the update+abel:.n-imeSet+istener %allba%k to up ate the time portion o$ the Calendar. $ormat it.n the %ase o$ the Date1ickerDialo%.show:.5 updateLa!el:. the last3sele%te time.

com Special Creative Commons BY-SA 3.Employing !ancy Widgets and Containers !igure %/< The Chrono.emo sample application6 as initially launched !igure %0< The same application6 sho4ing the date picker dialog 73 Subscribe to updates at http://commonsware.0 License Edition .

All you nee to o it put them in your layout an let them o their thing. here is an EML layout %ontaining both Di%italClock an Analo%Clock* <>xml version"#?.tremely easy to use. rather than have users enter the time. $rom the Clocks sample appli%ation. 5hese are e. you may Cish to use the Di%italClock or Analo%Clock Ci gets. (or e.android. as they automati%ally up ate Cith the passage o$ time.com Special Creative Commons BY-SA 3.ample.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <Analo%Clock android!id"#9Bid/analo%# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!layout*center3ori'ontal"#true# android!layout*ali%n1arent-op"#true# /& <Di%italClock android!id"#9Bid/di%ital# 77 Subscribe to updates at http://commonsware.@# encodin%"#utf(A#>& <Relative+ayout xmlns!android"#$ttp!//sc$emas.Employing !ancy Widgets and Containers !igure %3< The same application6 sho4ing the time picker dialog Time @eeps !lo4ing ike a 2iver .0 License Edition .$ you Cant to isplay the time.

Chi%h Cill be %overe in a later %hapter Feep them apprise o$ your progress.com Special Creative Commons BY-SA 3. lest they think your a%tivity has Can ere aCay an Cill never %ome ba%k 5he typi%al approa%h to keeping users in$orme o$ progress is some $orm o$ progress bar or QthrobberQ &think the animate graphi% toCar s the upper3 79 Subscribe to updates at http://commonsware. you oCe it to your users to o tCo things* • • "se a ba%kgroun threa .emo sample application *aking Progress . Ce %an buil this !igure %7< The Clocks.Employing !ancy Widgets and Containers android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!layout*center3ori'ontal"#true# android!layout*below"#9id/analo%# /& </Relative+ayout& Without any +ava %o e other than the generate proOe%t an get the $olloCing a%tivity* stub.$ you nee to be oing something $or a long perio o$ time.0 License Edition .

that %an be %ompli%ate to set up.. Cith 0 in i%ating no progress has been ma e. you pre$er your progress bar to be in eterminate.n An roi .ntent. then it perhaps belongs in another a%tivity ki%ke o$$ via an . use the android!indeterminate property. setting it to true. #in%e the 1ro%ress6ar is tie %losely to the use o$ threa s N a ba%kgroun threa oing Cork. you might use tabs to a%%omplish this en .$ Putting 8t +n *y Tab 5he general An roi philosophy is to keep a%tivities short an sCeet. @ou probably shoul also set the android!indeterminate6e$avior property to either repeat &to loop en lessly until stoppe in +ava %o e' or cycle to reverse %ourse an hea ba%k to @. . su%h as a =-abbed1ane in +avaU#Cing. . e$ine as an integer. you %an either positively set the amount o$ progress that has been ma e &via set1ro%ress:.imum en o$ the range N Chat value in i%ates progress is %omplete N via the android!max property. up ating the ". . Moreover. a 1ro%ress6ar starts Cith a progress o$ @. An roi supports this through the 1ro%ress6ar Ci get. though you %an start $rom some other position via the android!pro%ress property. /y e$ault.' or in%rement the progress $rom its %urrent amount &via increment1ro%ress6y:. A !rogress/ar keeps tra%k o$ progress. @ou %an e$ine the ma. albeit perhaps Cith s%rolling. Subscribe to updates at http://commonsware.0 License Edition . you noC have an option o$ using a 9. ..'.Employing !ancy Widgets and Containers right %orner o$ many Web broCsers'. as Cill be es%ribe later in this book. threa Cith neC progress in$ormation N Ce Cill hol o$$ emonstrating the use o$ 1ro%ress6ar to a later %hapter. )oCever. sometimes there legitimately is a lot o$ in$ormation that nee s to be %olle%te to be pro%esse as an atomi% operation. .n a tra itional ".n your +ava %o e.com Special Creative Commons BY-SA 3. @ou %an $in out hoC mu%h progress has been ma e via %et1ro%ress:.$ there is more in$ormation than %an reasonably $it on one s%reen.

Chi%h %ontain te. (or e. in or er to make these three Cork together* • @ou must give the -abCid%et an android!id o$ 9android!id/tabs 9( Subscribe to updates at http://commonsware. The Idiosyncr sies 5here are a $eC rules to $olloC.Employing !ancy Widgets and Containers %ontainer in mu%h the same Cay N a portion o$ your a%tivity7s s%reen is taken up Cith tabs Chi%h. -ab3ost #ome 8". The Pieces 5here are a $eC Ci gets an %ontainers you nee to use in or er to set up a tabbe portion o$ a vieC* • -ab3ost is the overar%hing %ontainer $or the tab buttons an %ontents -abCid%et tab • implements the roC o$ tab buttons. you might have an a%tivity Cith a tab $or entering a lo%ation an a se%on tab $or shoCing a map o$ that lo%ation. the tabs element %orrespon s to -abCid%et. the tabbox element %orrespon s to An roi 7s -ab3ost. sCap out part o$ the vieC an repla%e it Cith something else. #ome toolkits re$er to QtabsQ as being the %ombination o$ the %li%kable button3ish element an the %ontent that appears Chen that tab is %hosen.ample. .t labels an optionally %ontain i%ons is the %ontainer $or the tab %ontentsP ea%h tab %ontent is a %hil o$ the Erame+ayout Erame+ayout • 5his is similar to the approa%h that MoKilla7s E"L takes. so Ce Cill %all them Qtab buttonsQ an Qtab %ontentsQ in this se%tion. an tabpanels %orrespon s to the Erame+ayout. Chen %li%ke . toolkits re$er to QtabsQ as being Oust the things a user %li%ks on to toggle $rom one vieC to another.com Special Creative Commons BY-SA 3. at least in this milestone e ition o$ the An roi toolkit.n E"L7s %ase.0 License Edition . An roi treats the tab buttons an %ontents as is%rete entities.

@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. you nee to leave enough pa ing &via android!paddin%-op' in Erame+ayout to QshoveQ the a%tual tab %ontents oCn beneath the tab buttons. even i$ you o not supply i%ons. )en%e.els o$ pa ing. @ou o not ne%essarily have to use -abActivity N a plain a%tivity %an use tabs as Cell. @our tab %ontents obs%ure your tab buttons.Employing !ancy Widgets and Containers • @ou must set asi e some pa buttons &more on this beloC' ing in the Erame+ayout $or the tab • .n other Cor s. so this behavior may Cell %hange in $uture versions o$ the toolkit. With respe%t to the Erame+ayout pa ing issue.ample. .$ you Cish to use the -abActivity. you nee to supply at least 42 pi. (or e. you must give the -ab3ost an android!id o$ 9android!id/tab$ost -abActivity. no matter Chat you spe%i$y $or android!layout*$ei%$t $or the -abCid%et. 5his is likely a bug. the Erame+ayout ignores it an raCs at the top o$ the overall -ab3ost. $or Chatever reason.android. the -abCid%et oes not seem to allo%ate its oCn spa%e insi e the -ab3ost %ontainer. pattern &a%tivity ma e up entirely o$ tabs' into a pattern3aCare a%tivity sub%lass. Craps a %ommon ". perhaps more epen ing on the i%ons you supply.0 License Edition .n a ition. $or this version o$ the toolkit. )en%e. .com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#& <-ab3ost android!id"#9Bid/tab$ost# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#& <-abCid%et android!id"#9android!id/tabs# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <Erame+ayout android!id"#9android!id/tabcontent# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# 9% Subscribe to updates at http://commonsware. here is a layout e$inition $or a tabbe a%tivity.com Special Creative Commons BY-SA 3. the -abCid%et seems to alCays raC itsel$ Cith room $or i%ons. like +istActivity. $rom -ab* <>xml version"#?.

i$ you nee more %ontrol than a simple label an optional i%on. there are tCo tabs* a %lo%k an a button.ndicator:. 5he tCo key metho s on -abSpec are* • setContent:. $ill it out. ..Employing !ancy Widgets and Containers android!paddin%-op"#SHpx#& <Analo%Clock android!id"#9Bid/tab?# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!layout*center3ori'ontal"#true# /& <6utton android!id"#9Bid/tabH# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!text"#A semi(random button# /& </Erame+ayout& </-ab3ost& </+inear+ayout& 0ote that the -abCid%et an Erame+ayout are imme iate %hil ren o$ the -ab3ost.. 3irin! It To!ether 5he +ava %o e nee s to tell the -ab3ost Chat vieCs represent the tab %ontents an Chat the tab buttons shoul look like. @ou get a -abSpec instan%e $rom the host via new-abSpec:.. Subscribe to updates at http://commonsware. . an the Erame+ayout itsel$ has %hil ren representing the various tabs. 5his is all Crappe up in -abSpec obOe%ts. typi%ally the android!id o$ the vieC you Cant shoCn Chen this tab is sele%te set. • Chere you provi e the %aption $or the tab button an .n this %ase.0 License Edition . Chere you in i%ate Chat goes in the tab %ontent $or this tab. the tabs are probably some $orm o$ %ontainer &e.. then a it to the host in the proper se<uen%e. in some $lavors o$ this metho . supply a Drawable to represent the i%on $or the tab 0ote that tab Qin i%atorsQ %an a%tually be vieCs in their oCn right. +inear+ayout' Cith their oCn %ontents.com Special Creative Commons BY-SA 3.n a more %ompli%ate s%enario. 9.g.

com Special Creative Commons BY-SA 3. is not nee e i$ you are using the -abActivity base %lass $or your a%tivity.app. you %all setContent:.5 -ab3ost.newTa!Spec:#ta%H#. 8 super.os.ample.id. (inally. (or e.d:.5 -ab3ost tabs":-ab3ost.tab$ost..setContent:R. 5he %all to setup:. Ce get a -abSpec via new-abSpec:.5 < < tabs. o$ the tab.. metho . A$ter that.setIndicator:#Clock#.wid%et.5 spec. then have it setup:.main.5 spec.5 spec"tabs.setup:.addTa!:spec.layout.Activity5 import android.5 setContentView:R.newTa!Spec:#ta%?#.5 tabs.5 tabs.addTa!:spec.setContent:R.id. on the -ab3ost be$ore %on$iguring any o$ these -abSpec obOe%ts.android.5 spec.ndicator:.tab?.findViewById:R.-abSpec spec"tabs.5 We $in our -ab3ost via the $amiliar find7iew6y.6undle5 import android.onCreate:icicle.fancy5 import android.-ab3ost5 public class -abDemo extends Activity 8 9.ample* packa%e com.id.5 spec.setCurrentTa!:@. then %all add-ab:.verride public void onCreate:6undle icicle.0 License Edition .tabH. an set.5 tabs.setIndicator:#6utton#. you %an %hoose Chi%h tab is the one to shoC via setCurrent-ab:. 8iven the spe%..Employing !ancy Widgets and Containers Also note that you must %all setup:. ba%k on the -ab3ost to register the tab as available $or use. provi ing the @3base in e..commonsware. here is the +ava %o e to Cire together the tabs $rom the pre%e ing layout e. 5he resultD 9$ Subscribe to updates at http://commonsware. supplying a tag Chose purpose is unknoCn at this time.

0 License Edition .emo sample application6 sho4ing the first tab !igure ..< The same application6 sho4ing the second tab 9/ Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.Employing !ancy Widgets and Containers !igure %9< The Tab.

using Absolute+ayout %oul get <uite annoying. 5his provi es a simpli$ie tree representation.Employing !ancy Widgets and Containers +ther Containers of 5ote An roi o$$ers Absolute+ayout. sin%e the +istAdapter $amily oes not provi e any sort o$ group in$ormation $or the items in the list. #in%e An roi s%reens might run the gamut o$ siKes. @ou tell Absolute+ayout Chere to pla%e a %hil in pre%ise E. 5his re<uires a neC set o$ a apters. it means your vieCs Cill only look QrightQ on s%reens o$ a %ertain imension. plus have neC siKes %rop up perio i%ally. an An roi puts it there. 90 Subscribe to updates at http://commonsware. this gives you pre%ise positioning. >n the plus si e. >n the minus si e. An roi also has a neC $lavor o$ list. Chere the %ontents are lai out base on spe%i$i% %oor inate positions. 8roups %ontain %hil renP %hil ren are QleavesQ o$ the tree. the )xpandable+ist7iew.0 License Edition . 5his vieC $eels like it is a Cork3in3progress an so is not %overe here.com Special Creative Commons BY-SA 3. but shoul appear in a $uture e ition o$ this book. no <uestions aske . or it re<uires you to Crite a bun%h o$ %o e to a Oust the %oor inates base on s%reen siKe. supporting tCo levels o$ epth* groups an %hil ren.@ %oor inates.

An roi supports a%tivities Cith Qappli%ationQ menus.t menusQ. an the evi%e Cas esigne $or $inger3base tou%h input. you %oul push the -ext7iew Cith your $inger. toolkits. as Cith many 8".t menus typi%ally appear Chen the user Qtaps3an 3 hol sQ over a parti%ular Ci get. (or e. an that portion is manage by the An roi $rameCork itsel$. Also. 5he options menu is triggere by 93 Subscribe to updates at http://commonsware. %onte.0 License Edition .com Special Creative Commons BY-SA 3. Where An roi i$$ers $rom most other 8". su%h as !alm># an Win oCs Mobile. nor the timing o$ Chen the menu is built. you %an %reate Q%onte. >n mobile evi%es.t menu. >n a tra itional 8". !art o$ the menu is system3 e$ine . hol it $or a se%on or tCo.ample. this might be triggere by the right3mouse button.. While you %an a items to the menu. toolkits is in terms o$ menu %onstru%tion. you o not have $ull %ontrol over the menu7s %ontents. !lavors of *enu An roi %onsi ers the tCo types o$ menu es%ribe above as being the Qoptions menuQ an Q%onte. an a pop3up menu Cill appear $or the user to %hoose $rom.CHAPTER 14 )pplying *enus Like appli%ations $or the esktop an some mobile operating systems. #ome An roi phones Cill have a e i%ate menu key $or popping up the menuP others Cill o$$er alternate means $or triggering the menu to appear.t menuQ. i$ a -ext7iew ha a %onte.

5hen. 5his %allba%k re%eives an instan%e o$ Menu.th button Cill appear. Chi%h shoul be @ unless you are %reating a spe%i$i% groupe set o$ menu %hoi%es $or use Cith set0roupC$eckable:. 8iven that you have re%eive a Menu obOe%t via onCreate.n a ition. $iguring that the user probably Cants something loCer oCn on the menu. Oust hol onto the Menu instan%e you re%eive in onCreate. the i%on mo e Cill appear. labele QMoreQ N %li%king that option Cill bring up the e. so the An roi $rameCork %an a in any menu %hoi%es it $eels are ne%essary. so the user %an get to any o$ the menu %hoi%es. but rather the si.com Special Creative Commons BY-SA 3..'.pan e mo e.$ you Cill nee to a Oust the menu uring your a%tivity7s use &e. 5he $irst thing you shoul o is %hain upCar to the super%lass &super.ptionsMenu:.. sin%e they passe on the $irst $ive %hoi%es alrea y. 0otably.ptionsMenu:.g.0 License Edition .. 5he menu is s%rollable.pan e .)pplying *enus pressing the har Care QMenuQ button on the evi%e.t menu is raise by a tap3an 3hol on the Ci get sporting the menu.. but all re<uire the $olloCing parameters* • A group i enti$ier &int'.ptionsMenu:menu. *enus of +ptions Rather than buil ing your a%tivity7s options menu uring onCreate:.ptionsMenu:. . shoCing all available %hoi%es. 5here are many $lavors o$ this metho . . you a menu %hoi%es by %alling add:. . es%ribe beloC. $inger3 $rien ly buttons in a gri at the bottom o$ the s%reen.onCreate. the options menu operates in one o$ tCo mo es* i%on an e. &see beloC' 97 Subscribe to updates at http://commonsware. Chile the %onte. you instea nee to implement onCreate.$ the menu has more than $ive %hoi%es. isable a noC3invali menu %hoi%e'... the Cay you Cire up the rest o$ your ". a si.th. you %an go about a ing your oCn options.. the sele%tion bar Cill not be on the $irst menu %hoi%e. When the user $irst presses the QMenuQ button. shoCing up to the $irst $ive menu %hoi%es as large.

alongsi e the title.tem.temSelected:.com Special Creative Commons BY-SA 3. 5he add:..t o$ the menu %hoi%e &as a Strin% or by its resour%e .g. 5hese are set in ivi ually by %alling setAlp$abeticS$ortcut:. 5he menu is pla%e into alphabeti% short%ut mo e by %alling setTwertyMode:. 5he %hoi%e an group i enti$iers are keys use to unlo%k a $eatures. $or use in i enti$ying this %hoi%e in the on. so you o not %olli e Cith any An roi system menu %hoi%es put on the same menu.. Chere the %he%kbo.0 License Edition . so one out o$ the group %an be in the Q%he%ke Q state at any time • @ou %an also %all* 99 Subscribe to updates at http://commonsware.A' N these provi e the Q$a%eQ o$ the menu %hoi%e. %allba%k Chen a menu %hoi%e is %hosen @ou must also provi e an i%on &by its resour%e . Cith a %hoi%e i enti$ier.g.A' or the te.temC$eckable:. su%h as* • itional menu Calling set.&e. value gets toggle Chen the user %hooses that menu %hoi%e Calling set0roupC$eckable:.$ you provi e a Runnable. to %ontrol i$ the menu %hoi%e has a tCo3state %he%kbo. E. respe%tively. also alloC you to supply a Runnable to be %alle Chen the menu %hoi%e is %hosen.RS.RS-B?'. an set/umericS$ortcut:. >therCise.t o$ the menu %hoi%e'. #ome $lavors o$ add:. . on the menu Cith a true parameter.. Cith a group i enti$ier. An roi supports both an alphabeti% &or Q<CertyQ' set o$ short%uts an a numeri% set o$ short%uts. to turn a set o$ menu %hoi%es into ones Cith a mutual3e. @ou %an also set the short%uts $or the menu %hoi%e N single3%hara%ter mnemoni%s that %hoose that menu %hoi%e Chen the menu is visible. you shoul make your %hoi%e i enti$iers be an in%rement over E. the te.ptions.%lusion ra io button betCeen them. your %hoi%e i enti$ier &se%on parameter' %an be @. Chere you %an a Oust any o$ the menu item settings you have alrea y set &e. $amily o$ metho s all return an instan%e o$ Menu.)pplying *enus • A %hoi%e i enti$ier &also an int'.

temSelected:. your a%tivity Cill be noti$ie via the on.$ the user makes a menu %hoi%e.)pplying *enus • to a a separator line betCeen alrea y3 e$ine an up%oming menu %hoi%es addSeparator:. not Chen it is in Qi%onQ mo e.* #eparators an sub3menus only Cork Chen the options menu is in Qe. *enus in Context /y an large.0 License Edition .pan e Q mo e. 0ote that on. A typi%al pattern is to switc$:. an then only starting Cith the si.. then a menu %hoi%es to the sub3menu.A &item. an that %hoi%e %ame Cith a Runnable instan%e atta%he ..ptionsMenu:.. As Cith onCreate.ptions. e. >AT.temSelected:. o$$ering only the means to set a Qhea erQ or %aption $or the popup menu via set3eader:.th menu %hoi%e.%ept the Runnable %allba%k. %onte. you %an %reate $ly3out sub3menus by %alling addSubMenu:. your Runnable Cill be invoke . supplying the same parameters as addMenu:.ptions:. but a sub3menu %annot itsel$ have a sub3sub3menu.tem obOe%t %orrespon ing to the sele%te menu %hoi%e. Subscribe to updates at http://commonsware. >therCise. on the menu .t menus use the same guts as option menus N the %lass e. . is use regar less o$ Chether the %hosen menu item Cas in the base menu or in a submenu.d:.' an take appropriate behavior. add.%et. along Cith another Menu instan%e representing the sub3menu itsel$.ptions. • to populate the menu Cith menu %hoi%es %orrespon ing to the available a%tivities $or an intent &see the %hapter on laun%hing a%tivities' (inally. @ou shoul only use these $eatures i$ you have a really long menu. An roi Cill eventually %all onCreate1anelMenu:. @ou are given the Menu. ContextMenu (.com Special Creative Commons BY-SA 3..ten s the regular Menu %lass.. %allba%k that a menu %hoi%e Cas sele%te . passing it the %hoi%e i enti$ier o$ your sub3menu.ntent.. 5he tCo main i$$eren%es are hoC you populate the menu an hoC you are in$orme o$ menu %hoi%es. >ne limitation is that you %annot in e$initely nest sub3menus N a menu %an have a sub3menu. you shoul %hain upCar to the super%lass.

tra in$ormationQ Chen the menu is built. in %ase you Cant to %ustomiKe the %onte. so you %an tell them apart in this %allba%k.bject representing Qe.temSelected:. the 7iew the %onte.com Special Creative Commons BY-SA 3. An roi o$$ers a set.ptionsMenu:. as is es%ribe above. there is no %allba%k in the Activity to populate the %onte. this %allba%k behaves the same as on. Chi%h tells you Chi%h item in the list the user i the tap3an 3hol over.n1opulateContextMenu+istener %allba%k inter$a%e.( Subscribe to updates at http://commonsware. . 5o save you the total hea a%he o$ sub%lassing a bun%h o$ Ci gets Oust to set up your %onte. 5his takes an instan%e o$ the .t menu the Cay there is onCreate.t menus.t menu is $or a sele%tion Ci get that inherits $rom Adapter7iew.t menu. metho gets the ContextMenu itsel$. As a result. %onte. 5he on1opulateContextMenu:.t menu is asso%iate Cith.ptions.$ the %onte. 0ote that you only get this Qe. . an an opa<ue . 0ote that you only get the Menu. you %oul toggle a %he%kable menu %hoi%e base upon the %urrent state o$ the item. "nlike the options menu &Chi%h is only built on%e per a%tivity'. . implement on the a%tivity.n1opulateContextMenu+istener:.nfo. though.)pplying *enus #in%e %onte. to populate the options menu.tra in$ormationQ about the menu being built. (or e.tem instan%e that Cas %hosen in this %allba%k.ample. onContext. gets %alle $or ea%h time the %onte. not Chen a %hoi%e is ma e. you may Cant to ensure they have uni<ue menu item i enti$iers $or all their %hoi%es.temSelected:.0 License Edition . @our implementation o$ that inter$a%e N spe%i$i%ally. your implementation o$ on1opulateContextMenu:. ea%h Ci get itsel$ is tol Chen to populate the %onte. N is Chere you set up the %ontents o$ the %onte. )en%e.. >therCise. metho on all Ci gets.t is also important to note that on1opulateContextMenu:.t menu %hoi%e Cas %hosen. 5o $in out Chen a %onte.t menu base on that in$ormation. you o not Cant to hol onto the supplie ContextMenu obOe%tP Oust rely on getting the %han%e to rebuil the menu to suit your a%tivity7s nee s on an on3 eman basis base on user a%tions.t menus are per3Ci get. this obOe%t is suppose to be an instan%e o$ ContextMenu.t menus are is%ar e on%e they are use or ismisse .t menu is re<ueste . i$ your a%tivity has tCo or more %onte. rather than per3a%tivity.t menu. (.nstea .t menus.

E. 8 populate'enu:menu.D " Menu.R.D " Menu.U-))/*.5 setList#dapter:new ArrayAdapter<Strin%&:t$isG android.03-*.5 selection":-ext7iew.0 License Edition .*.RS-BI5 public static final int -C. the EML layout nee not %hange an is not reprinte here.On&opulateContext'enuListener:. 8 populate'enu:menu.selection.5 setContentView:R. you Cill $in an amen e version o$ the +ist7iew sample &+ist' Cith an asso%iate menu.5 < 9.n the sample proOe%t Menus. #in%e the menus are e$ine in +ava %o e.2R*.com Special Creative Commons BY-SA 3.5 getListView:.nfo.bject menu.D " Menu.5 (.)pplying *enus Taking a Peek .verride public void onCreate:6undle icicle.RS-BN5 9. 8 super.onCreate:icicle.layout.RS-BH5 public static final int -C)/-F*E.% Subscribe to updates at http://commonsware.id. .setText:itemsOpositionP.D " Menu. )oCever.E.E.set(eader:#Divider 3ei%$t#.verride public boolean onCreateOptions'enu:Menu menu.findViewById:R. 8 selection.5 < <.main.5 menu..E. 8 public void on&opulateContext'enu:ContextMenu menuG 7iew vG .layout.5 < public void onListItemClick:+ist7iew parentG 7iew vG int positionG lon% id. the +ava %o e has a $eC neC behaviors* public class MenuDemo extends +istActivity 8 -ext7iew selection5 Strin%OP items"8#lorem#G #ipsum#G #dolor#G #sit#G #amet#G #consectetuer#G #adipiscin%#G #elit#G #morbi#G #vel#G #li%ula#G #vitae#G #arcu#G #aliJuet#G #mollis#G #etiam#G #vel#G #erat#G #placerat#G #ante#G #porttitor#G #sodales#G #pellentesJue#G #au%ue#G #purus#<5 public static final int ).setOn&opulateContext'enuListener:new 7iew.simple*list*item*?G items.RS-B?5 public static final int S.

2R*.5 < .U-))/*. Chi%h Ce $ill in via our populateMenu:.add:@G ).5 < private void populate'enu:Menu menu.5 case -C. VV super.add:@G -C)/-F*E.U-))/*.setDi ider(eight:A. private metho .D! getListView:.add:@G -C.DG #?S 1ixels#.setDi ider(eight:?S.DG #A 1ixels#.5 menu..onCreateOptions'enu:menu.5 case S.DG #H 1ixels#.D! getListView:.verride public boolean onOptionsItemSelected:Menu.*.n onCreate:. Subscribe to updates at http://commonsware.03-*.DG #HN 1ixels#..n1opulateContextMenu+istener obOe%t Cith the list Ci get.5 return:apply'enuChoice:item. VV super.5 menu.5 < 9..D! getListView:. (. We also set the hea er o$ the menu &menu...5 return:true.set3eader:#Divider 3ei%$t#..'. 8 menu.tem item. Ce register a ..setDi ider(eight:H. 8 return:apply'enuChoice:item.)pplying *enus return:super. 8 switc$ :item.5 < private boolean apply'enuChoice:Menu.*..0 License Edition .5 < < return:false..5 return:true.tem item.D! getListView:. 8 case ).5 return:true.getId:.com Special Creative Commons BY-SA 3.tem item..onContextItemSelected:item.2R*.5 < 9.03-*.setDi ider(eight:HN.t menu..5 case -C)/-F*E.. 8 apply'enuChoice:item..onOptionsItemSelected:item.add:@G S.5 return:true. so it Cill get a %onte.verride public boolean onContextItemSelected:Menu.5 menu.

to $ill in the menu.com Special Creative Commons BY-SA 3. &$or options menu sele%tions' an onContext.n applyMenuC$oice:. i$ you press the Menu button. >n%e again..)pplying *enus We also implement the onCreate. . plus %haining upCar s to the super%lass i$ none o$ our menu %hoi%es Cas the one sele%te by the user. Ce elegate to populateMenu:.temSelected:.nitially.t menu sele%tions' both elegate to a private applyMenuC$oice:. the a%tivity looks the same in the emulator as it i $or +istDemo* !igure .ptionsMenu:. %allba%k. . in i%ating that our a%tivity also has an options menu. metho .(< The *enu. &$or %onte.ptions.0 License Edition .n populateMenu:.emo sample application6 as initially launched /ut. Ce see i$ any o$ our menu %hoi%es Cere %hosenP i$ so. . >ur implementations o$ on. Ce set the list7s ba%kgroun %olor to be the user3sele%te hue.temSelected:. /eing laKy. Ce a $our menu %hoi%es..$ Subscribe to updates at http://commonsware. Ce es%heC the i%ons. you Cill get our options menu* (. ea%h Cith a uni<ue i enti$ier.

-4 pi.els' then %hanges the ivi er height o$ the list to something garish* !igure .0 License Edition .com Special Creative Commons BY-SA 3.)pplying *enus !igure ..%< The same application6 sho4ing the options menu Choosing a height &say.< The same application6 made ugly (./ Subscribe to updates at http://commonsware.

0 License Edition .t menu by oing a tap3an 3hol on any item in the list* !igure .com Special Creative Commons BY-SA 3. (.0 Subscribe to updates at http://commonsware.)pplying *enus @ou %an trigger the %onte. %hoosing an option sets the ivi er height.$< The same application6 sho4ing a context menu >n%e again.

that it gets its oCn +ava pa%kage &android. ) Bro4ser6 Writ Small (or simple stu$$.Wi gets' to embe ing . +avaU#Cing. base upon your re<uirements.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <Ceb7iew android!id"#9Bid/webkit# (.CHAPTER 11 Embedding the Web@it Bro4ser >ther 8". An roi is mu%h the same. an you7re one. tell it Chat "RL to navigate to via +ava %o e. 5he An roi broCser is su$$i%iently %omple.plorer into .@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. here is a simple layout Cith a Ceb7iew* <>xml version"#?.. 5he An roi broCser is base on WebFit. (or e. the same engine that poCers Apple7s #a$ari Web broCser.com Special Creative Commons BY-SA 3.nternet I. $or isplaying )5ML or $ull3$le ge broCsing.ample &6rowser?'.g.0 License Edition .android. toolkits let you use )5ML $or presenting in$ormation.webkit'. $rom limite )5ML ren erers &e. in that you %an embe the built3in Web broCser as a Ci get in your oCn a%tivities.0I5 appli%ations. Ceb7iew is not signi$i%antly i$$erent than any other Ci get in An roi N pop it into a layout. though using the Ceb7iew Ci get itsel$ %an be simple or poCer$ul.3 Subscribe to updates at http://commonsware. C.

7 Subscribe to updates at http://commonsware.os.onCreate:icicle.webkit5 import android.layout.commonsware. you nee to tell it hoC it shoul $ill up the spa%e in the layout &in this %ase.webkit.Activity5 import android.main.android. 8 super.5 browser":Ceb7iew.6undle5 import android.5 < < 5he only bit unusual Cith this e ition o$ onCreate:.com#. 5he +ava %o e is e<ually simple* packa%e com. is that Ce invoke load2rl:. it $ills all remaining spa%e'.id.webkit. 5he resulting a%tivity looks like a Web broCser. the home page o$ some ran om $irm'.Ceb7iew5 public class 6rowserDemo? extends Activity 8 Ceb7iew browser5 9.Embedding the Web@it Bro4ser /& </+inear+ayout& android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# As Cith any other Ci get.0 License Edition .com Special Creative Commons BY-SA 3.load)rl:#$ttp!//commonsware. on the Ceb7iew Ci get.findViewById:R. to tell it to loa a Web page &in this %ase. Oust Cith hi en s%rollbars* (.5 browser.app.5 setContentView:R.verride public void onCreate:6undle icicle.

%ellular netCork. you supply the )5ML $or the broCser to vieC. oading 8t >p 5here are tCo main Cays to get %ontent into the Ceb7iew. shoCn above.Embedding the Web@it Bro4ser !igure . 5he alternative is to use loadData:.'..com Special Creative Commons BY-SA 3. >ne./< The Bro4ser( sample application As Cith the regular An roi broCser.nternet through Chatever means are available to that spe%i$i% evi%e at the present time &Wi(i. is to provi e the broCser Cith a "RL an have the broCser isplay that page via load2rl:. )ere.. 5he broCser Cill a%%ess the . Cell3traine tiny %arrier pigeons. Chile the ire%tional pa moves you aroun all the $o%usable elements on the page. /luetooth3tethere phone. su%h as a navigational toolbar.9 Subscribe to updates at http://commonsware.0 License Edition . What is missing is all the e. @ou might use this to* (. et%. you %an pan aroun the page by ragging it.tra a%%outerments that make up a Web broCser.

an the en%o ing. invo%ation in the previous e. instea o$ using the An roi Ci get set • • 5here are tCo $lavors o$ loadData:.0< The Bro4ser% sample application ((.ample Cith the $olloCing* browser. 5ypi%ally.loadData:#<$tml&<body&3elloG worldW</body&</$tml&#G #text/$tml#G #2-E(A#.MI type.5 @ou get* !igure . 5he simpler one alloCs you to provi e the %ontent. all as strings. (or e.ample. Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.MI type Cill be text/$tml an your en%o ing Cill be 2-E(A $or or inary )5ML..Embedding the Web@it Bro4ser • isplay a manual that Cas installe as a $ile Cith your appli%ation pa%kage isplay snippets o$ )5ML you retrieve as part o$ other pro%essing.0 License Edition . i$ you repla%e the load2rl:. your M. the M. su%h as the es%ription o$ an entry in an Atom $ee generate a Chole user inter$a%e using )5ML.

but you have to supply the ". • • to %lear the broCser resour%e %a%he an clear3istory:..rEorward:. 5hat being sai . 5avigating the Waters As Cas mentione above.Embedding the Web@it Bro4ser 5his is also available as a $ully3buil able sample. clearCac$e:. ((( Subscribe to updates at http://commonsware. to go ba%k one step in the broCser history. i$ you Cant to o$$er navigational %apabilities. there is no navigation toolbar Cith the Ceb7iew Ci get. @ou Cill Cant to make sure those links are han le properly. you Cill Cant to be able to get %ontrol at key times. parti%ularly Chen users %li%k on links. or by some other means &see the %hapter on laun%hing a%tivities'. you %an. to %o6ack. broCsing the Web'.' can0o6ack. Ceb7iew o$$ers Cays to per$orm gar • • en3variety broCser navigation. an etermine i$ there is any history to go $orCar to • to go ba%kCar s or $orCar s in the broCser history. by submitting an . as 6rowserH. Chere negative numbers represent a %ount o$ steps to go ba%kCar s.com Special Creative Commons BY-SA 3. an can0o6ack:. to go can0oEorward:. • $orCar one step in the broCser history. either by loa ing your oCn %ontent ba%k into the Ceb7iew. to %lear the broCsing history Entertaining the Client !arti%ularly i$ you are going to use the Ceb7iew as a lo%al user inter$a%e &vs. in%lu ing* Web page reload:. to etermine i$ there is any history to go ba%k to %oEorward:. 5his alloCs you to use it in pla%es Chere su%h a toolbar Coul be pointless an a Caste o$ s%reen real estate.ntent to An roi to open the "RL in a $ull broCser. an positive numbers represent hoC many steps to go $orCar s to see i$ the broCser %an go ba%kCar s or $orCar s the state number o$ steps &$olloCing the same positiveUnegative %onvention as %o6ack.0 License Edition .rEorward:.rEorward:. to re$resh the %urrently3vieCe %o6ack:.

util. .onCreate:icicle. et%. upon a %li%k. i$ you have inserte a Q$akeQ "RL into the )5ML.commonsware.app.ample. let7s amen the $irst broCser e.webkit5 import import import import import android.android. a%tually $et%h the Web page re$eren%e by the "RL'. you probably Cant to use an .verride public void onCreate:6undle icicle. Chere your %allba%k is passe a "RL &plus the Ceb7iew itsel$' an you return true i$ you Cill han le the re<uest or false i$ you Cant e$ault han ling &e.. here is the revise +ava* packa%e com. you %an up ate the Ceb7iew yoursel$. $or e.Ceb7iew5 android. representing a link to some a%tivity3 provi e %ontent.. so i$ the user %li%ks a "RL. su%h as* • • • on-ooManyRedirects:. A %ommon hook Cill be s$ould. /ut. nee to han le %ertain user3 or %ir%umstan%e3 initiate events.webkit. 5he supplie %allba%k obOe%t Cill be noti$ie o$ a Ci e range o$ a%tivities.ample to be a broCser3base e<uivalent o$ our original e.n the %ase o$ a $ee rea er appli%ation. ranging $rom Chen parts o$ a page have been retrieve &on1a%eStarted:.webkit.' to Chen you.. (rom 6rowserI.g.os.6undle5 android.0 License Edition ..verride2rl+oadin%:.5 ((% Subscribe to updates at http://commonsware.main.ample* an appli%ation that.5 setContentView:R.ample. as the host appli%ation. you Cill probably not have a $ull broCser Cith navigation built into your rea er. et%.Embedding the Web@it Bro4ser @our hook into Ceb7iew a%tivity is via setCeb7iewClient:.layout. onReceived3ttpAut$ReJuest:.Date5 public class 6rowserDemoI extends Activity 8 Ceb7iew browser5 9.com Special Creative Commons BY-SA 3.Activity5 android.ntent to ask An roi to loa that page in a $ull broCser.Ceb7iewClient5 java. shoCs the %urrent time. 8 super. (or e. Chi%h takes an instan%e o$ a Ceb7iewClient implementation as a parameter.

.0 License Edition ..5 browser. 8 Strin% pa%e"#<$tml&<body&<a $ref"4#/clock4#&# Bnew Date:. Ce loa a simple Web page into the broCser & load-ime:.set*e!ViewClient:new Call!ack:.toString:. Subscribe to updates at http://commonsware.id.5 private class Callback extends Ceb7iewClient 8 public boolean shouldO erride)rlLoading:Ceb7iew viewG Strin% url. 8 loadTime:.Embedding the Web@it Bro4ser browser":Ceb7iew.5 < void loadTime:. no matter Chat the "RL.findViewById:R. Ce Cant to Oust reloa the Ceb7iew via load-ime:.webkit..com Special Creative Commons BY-SA 3.verride2rl+oadin%:.5 loadTime:.loadData:pa%eG #text/$tml#G #2-E(A#. provi ing our implementation o$ s$ould.n this %ase.' that %onsists o$ the %urrent time.. Running this a%tivity gives us* ((.5 < < < )ere. ma e into a hyperlink to the /clock "RL. . We also atta%h an instan%e o$ a Ceb7iewClient sub%lass. B#</a&</body&</$tml&#5 < browser.5 return:true.

Settings6 Preferences6 and +ptions #+h6 *y!& With your $avorite esktop Web broCser. via the CebSettin%s instan%e returne $rom %alling the Ci get7s %etSettin%s:. 5here are lots o$ options on CebSettin%s to play Cith. Most appear $airly esoteri% &e. sample application #ele%ting the link an %li%king the A3pa %enter button Cill Q%li%kQ the link. )oCever. /etCeen that an the toolbar %ontrols. $rom pre$erre $onts to the behavior o$ +avas%ript. setEantasyEontEamily:. #imilarly.'.g. you %an tCeak an tCi le the behavior o$ your broCser. %ausing us to rebuil the page Cith the neC time.0 License Edition . metho .3< The Bro4ser. here are some that you may $in more use$ul* (($ Subscribe to updates at http://commonsware.. you have some sort o$ QsettingsQ or Qpre$eren%esQ or QoptionsQ Cin oC.Embedding the Web@it Bro4ser !igure . you %an a Oust the settings o$ your Ceb7iew Ci get as you see $it.com Special Creative Commons BY-SA 3.

0 License Edition . &to merely stop it $rom opening pop3up Cin oCs' Control Web site ren ering via set2seDesktop2serA%ent:.Embedding the Web@it Bro4ser • Control the $ont siKing via setDefaultEontSi'e:. Chile true results in a user3agent string that suggests it is a esktop broCser • • 5he settings you %hange are not persistent. &to isable it outright' an set=avaScriptCan.penCindowsAutomatically:. &to use a point siKe' or set-extSi'e:. &to use %onstants in i%ating relative siKes like +AR0)R an SMA++)S-' Control +avas%ript via set=avaScript)nabled:. so you shoul store them someChere &su%h as via the An roi pre$eren%es engine' i$ you are alloCing your users to etermine the settings. N false means the Ceb7iew gives the Web site a user3agent string that in i%ates it is a mobile broCser. ((/ Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. versus har 3Ciring the settings in your appli%ation.

Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition .

.n these an other %ases. 0ot every intera%tion Cith An roi users Cill be neat. 2aising Toasts A -oast is a transient message. you may nee to %ommuni%ate Cith the user outsi e the boun s o$ the tra itional user inter$a%e. is %overe in a later %hapter.pe%te . Moreover. an %ontainable in a%tivities %ompose o$ vieCs.. as su%h.n this %hapter. More subtle in i%ators also e. $rom task tray i%ons to boun%ing o%k i%ons to a vibrating %ell phone.ist. . /a%kgroun tasks may take Cay longer than e. Irror messages in the $orm o$ ialog bo. Irrors Cill %rop up. meaning that it isplays an isappears on its oCn Cithout user intera%tion. this is nothing neC. noti$i%ations. you Cill see tCo means o$ raising pop3up messages* toasts an alerts.com Special Creative Commons BY-SA 3.es have been aroun $or a very long time.CHAPTER 1& Sho4ing Pop">p *essages #ometimes. #omething asyn%hronous may o%%ur. it oes not take $o%us aCay $rom ((3 Subscribe to updates at http://commonsware. ti y. >$ %ourse. is tie heavily into intents an servi%es an . >ne. your a%tivity &or other pie%e o$ An roi %o e' Cill nee to speak up. An roi has <uite a $eC systems $or letting you alert your users outsi e the boun s o$ an Activity3base ". su%h as an in%oming message.0 License Edition .

an AlertDialo% pops up. an the message Cill be isplaye .$ you Coul pre$er your -oast be ma e out o$ some other 7iew. et%. su%h as in i%ating a long3running ba%kgroun task is %omplete . grabs the $o%us. or something else Chere you are sure that the user nee s to see the message an nee s to see it noC. the -oast is mostly $or a visory messages.t.com Special Creative Commons BY-SA 3.0 License Edition . Chat you Cant is an AlertDialo%. 6uilder o$$ers a series o$ metho s to ((7 Subscribe to updates at http://commonsware. @ou might use this $or a %riti%al error.. 5he uration is e. simply %reate a neC -oast instan%e via the %onstru%tor &Chi%h takes a Context'. nor oes the message sti%k aroun $or a long time to pester the user.$ you Coul pre$er something in the more %lassi% ialog bo.. )lert! )lert! . >n%e your -oast is %on$igure . metho . to set the uration.A' an returns a -oast instan%e.presse in the $orm o$ the +)/0-3*S3. @ou get no a%knoCle gment $rom them. on a relative basis. #in%e a -oast is transient.t 8reat Ameri%an !rogramming 8ui e.Sho4ing Pop">p *essages the %urrently3a%tive Activity. metho also nee s the Activity &or other Context' plus a uration. (olloCing in true buil er style./0 %onstants to in i%ate. they Cill not have keystrokes be QeatenQ by the message. you have no Cay o$ knoCing i$ the user even noti%es it. Making a -oast is $airly easy. hoC long the message shoul remain visible.R. )en%e. an stays there until %lose by the user. a vali ation message that %annot be e$$e%tively isplaye in the base a%tivity ". then %all set7iew:. the battery has roppe to a loC3but3not3too3loC level. . 5he simplest Cay to %onstru%t an AlertDialo% is to use the 6uilder %lass. so i$ the user is busy Criting the ne. 5he -oast %lass o$$ers a stati% make-ext:.or +)/0-3*+. rather that be a boring ol pie%e o$ te. 5he make-ext:. %all its s$ow:. that a%%epts a Strin% &or string resour%e . As Cith any other mo al ialog bo. to supply it Cith the vieC to use an setDuration:. style.

$rom either a supplie Strin% or a supplie string resour%e . Checking Them +ut 5o see hoC these Cork in pra%ti%e. to get the partially3built AlertDialo% instan%e. %all create:.. ea%h metho returning the 6uilder $or easy %haining.tual message. Cill appear an aCait user input.$ you nee to %on$igure the AlertDialo% beyon Chat the buil er alloCs. the ialog bo.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <6utton android!id"#9Bid/alert# android!text"#Raise an alert# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content#/& ((9 Subscribe to updates at http://commonsware. >n%e s$ow:.android. is %alle .con:..A setMessa%e:. . to set. on the AlertDialo% itsel$. set/eutral6utton:. %ontaining the $olloCing layout. an Chat logi% shoul be invoke Chen the button is %li%ke &besi es ismissing the ialog'. %enter. • in i%ate Chi%h button&s' shoul appear a%ross the bottom o$ the ialog. an set/e%ative6utton:. take a peek at Messa%e.com Special Creative Commons BY-SA 3. %on$igure it the rest o$ the Cay. Chat their %aptions shoul be.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. set1ositive6utton:... instea o$ %alling s$ow:.Sho4ing Pop">p *essages %on$igure an AlertDialo%. or right.0 License Edition . then %all one o$ the $lavors o$ s$ow:. Chere they shoul be positione &le$t.. At the en . set-itle:...* <>xml version"#?. respe%tively'. an • to %on$igure the te.t an Uor i%on to appear in the title bar o$ the ialog bo. Commonly3use %on$iguration metho s on 6uilder in%lu e* • i$ you Cant the Qbo yQ o$ the ialog to be a simple te. on the buil er to isplay the ialog bo.. you %all s$ow:.

'. 8 new AlertDialo%.set%eutralButton:#Close#G new Dialo%. .toast.show:.5 setContentView:R.5 alert":6utton.setOnClickListener:t$is. 8 if :view""alert. 8 public void onClick:Dialo%.makeText:t$isG #<clinkG clink&#G -oast.OnClickListener:..5 < < < 5he layout is unremarkable N Oust a pair o$ buttons to trigger the alert an the toast.onCreate:icicle.id. 8 // do not$in% X it will close on its own < <.alert.5 < public void onClick:7iew view.5 toast":6utton.0 License Edition .findViewById:R. .findViewById:R.5 < else 8 -oast .+)/0-3*S3.. Subscribe to updates at http://commonsware.' to set the title &set-itle:#Messa%eDemo#.5 alert.nClick+istener 8 6utton alert5 6utton toast5 9.verride public void onCreate:6undle icicle.an +ava %o e* public class Messa%eDemo extends Activity implements 7iew.set'essage:#eekW#.main.R-.setTitle:#Messa%eDemo#..nterface. 8 super.Builder:t$is.Sho4ing Pop">p *essages <6utton android!id"#9Bid/toast# android!text"#Make a toast# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content#/& </+inear+ayout& . .setOnClickListener:t$is.show:. . .com Special Creative Commons BY-SA 3.5 toast.layout. an (%. When you %li%k the alert button.'.nterface dl%G int sumt$in.id. Ce use a buil er &new 6uilder:t$is. message &setMessa%e:#eekW#.

Sho4ing Pop">p *essages Qneutral buttonQ &set/eutral6utton:#Close#G new . you %oul up ate in$ormation in your a%tivity base upon the user a%tion. the . the -oast %lass makes us a te. When the button is %li%ke . parti%ularly i$ you have multiple buttons $or the user to %hoose $rom.0 License Edition .* !igure . non3interrupting message* (%( Subscribe to updates at http://commonsware.R-. 5he result is a short3live .7< The *essage.' be$ore shoCing the ialog.nClick+istener:. Chi%h Ce then s$ow:..t3base toast &make-ext:t$isG #<clinkG clink&#G +)/0-3*S3.. . )oCever. 5he result is a typi%al ialog bo.nClick+istener %allba%k oes nothing N the mere $a%t the button Cas presse %auses the ialog to be ismisse .'.emo sample application6 after clicking the =2aise an alert= button When you %li%k the toast button..com Special Creative Commons BY-SA 3.

0 License Edition .com Special Creative Commons BY-SA 3.Sho4ing Pop">p *essages !igure .9< The same application6 after clicking the =*ake a toast= button (%% Subscribe to updates at http://commonsware.

com Special Creative Commons BY-SA 3. on the ".g. your a%tivity might have real Cork to o.-$read2tilities. Subscribe to updates at http://commonsware.pensive Cork in a ba%kgroun threa An roi provi es a veritable %ornu%opia o$ means to set up ba%kgroun threa s yet alloC them to sa$ely intera%t Cith the ". eally. an you o not nee to manually register it or anything N (%. 200ms' is a $ine goal. Ao e. threa . an using 2. At minimum.pensive operations in a ba%kgroun servi%e. lest the ActivityMana%er e%i e to play the role o$ the 8rim Reaper an kill o$$ your a%tivity as being non3responsive. Chi%h takes non3 negligible amounts o$ time..ible means o$ making an An roi 3$rien ly ba%kgroun threa is to %reate an instan%e o$ a 3andler sub%lass. Ao e. Respon ing to user input <ui%kly &e. relying on noti$i%ations to prompt users to go ba%k to your a%tivity 2.CHAPTER 1' .0 License Edition . 'etting Through the Dandlers 5he most $le.ealing 4ith Threads . so your users on7t $eel that your appli%ation is sluggish. @ou only nee one 3andler obOe%t per a%tivity. though. >$ %ourse. 5hese in%lu e 3andler obOe%ts. posting Runnable obOe%ts to the 7iew. you nee to make sure you respon Cithin B se%on s. you Cant your a%tivities to be oCnright snappy. 5here are tCo Cays o$ ealing Cith this* -.

iately puts the message on the <ueue imme iately. 5o these messages. 5he more %ompli%ate your 3andler pro%essing nee s to be... $amily o$ metho s* • • sendMessa%e:.presse in millise%on s sendMessa%eDelayed:.com Special Creative Commons BY-SA 3. @our ba%kgroun threa %an %ommuni%ate Cith the 3andler.. su%h as up ating Ci gets. to get the Messa%e obOe%t out o$ the pool. $irst invoke obtainMessa%e:.ealing 4ith Threads merely %reating the instan%e is su$$i%ient to register it Cith the An roi threa ing subsystem. 5hen. e.. e.:. %ess !es 5o sen a Messa%e to a 3andler. alloCing you to Oust %reate empty Messa%e obOe%ts. as is the e$ault'.presse in the $orm o$ millise%on s base on system uptime &SystemClock. your 3andler nee s to implement $andleMessa%e:. as ". Chi%h Cill o all o$ its Cork on the a%tivity ". threa .' sendMessa%eAt-ime:. or ones populate Cith message i enti$iers an arguments.fTueue:. @ou have tCo options $or %ommuni%ating Cith the 3andler* messages an Runnable obOe%ts.uptimeMillis:.0 License Edition . 5here are a $eC $lavors o$ obtainMessa%e:. using one o$ the sendMessa%e. so your message takes priority over all others puts the message on the <ueue at the state time. shoul only o%%ur on the a%tivity ". an moreover puts it at the $ront o$ the message <ueue &versus the ba%k. you sen the Messa%e to the 3andler via its message <ueue. • • puts the message on the <ueue a$ter a elay. %hanges. Chi%h Cill be %alle Cith ea%h message that appears on the pro%ess (%$ Subscribe to updates at http://commonsware. 5his is important. puts the message on the <ueue imme sendMessa%eAtEront. threa .. the more likely it is you Cill nee to put ata into the Messa%e to help the 3andler istinguish i$$erent events.

android. )oCever.Activity5 android.os. also employs tCo other properties o$ note* • Chi%h Cill be %overe in greater etail in some $uture e ition o$ this book. in a ition to setting the Ci th an height as normal. it shoul still o that Cork <ui%kly.commonsware. the han ler %an up ate the ".e.os..com Special Creative Commons BY-SA 3. (or noC.1ro%ress6ar5 public class 3andlerDemo extends Activity 8 1ro%ress6ar bar5 (%/ Subscribe to updates at http://commonsware.imum value $or the 1ro%ress6ar &i.Messa%e5 android. as other ".android.os.0 License Edition . 5here. su$$i%e it to say that it in i%ates this 1ro%ress6ar shoul be raCn as the tra itional horiKontal bar shoCing the amount o$ Cork that has been %omplete .ealing 4ith Threads message <ueue.app. as nee e .6undle5 android. A value o$ ?@@ means the 1ro%ress6ar Corks on a simple per%entage system. (or e. android!max.wid%et. at Chat value is the Cork Q oneQ an the progress bar %omplete '. Cork is suspen e until the 3andler is one.t$reads5 import import import import import android.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <1ro%ress6ar android!id"#9Bid/pro%ress# style"#>android!attr/pro%ress6arStyle3ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!max"#?@@# /& </+inear+ayout& 5he 1ro%ress6ar.ample. An here is the +ava* packa%e com. let7s %reate a 1ro%ress6ar an up ate it via a 3andler. )ere is the layout $rom 3andler* <>xml version"#?.. • Chi%h in i%ates the ma.3andler5 android. style.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.

8 // just end t$e back%round t$read < < <. 8 super.5 isRunnin%"true5 back%round. (%0 Subscribe to updates at http://commonsware. post a Messa%e to the 3andler. then e.verride public void onCreate:6undle icicle. /asi%ally.5 $andler. $or any message re%eive .it the message han ler.onStart:.5 isRunnin%"false5 < < As part o$ %onstru%ting the Activity.main... Ce Oust sleep one se%on . . 8 bar. Ce up ate the 1ro%ress6ar by L points.. Ce %reate an instan%e o$ 3andler. Cith our implementation o$ $andleMessa%e:.5 bar.5 < <5 boolean isRunnin%"false5 9.set&rogress:@. 8 -$read.0 License Edition .onCreate:icicle.id..5 setContentView:R.onStop:.5 < public void onStop:. 8 super.5 -$read back%round"new Thread:new $unna!le:.verride public void handle'essage:Messa%e ms%.5 < < catc$ :-$rowable t. .n onStart:. 8 9. 8 try 8 for :int i"@5i<H@ YY isRunnin%5iBB.5 < public void onStart:.5 bar":1ro%ress6ar. 8 super. 8 public void run:.layout. an repeat $or a total o$ H@ passes.start:.ealing 4ith Threads 3andler $andler"new (andler:.send'essage:$andler. Ce set up a ba%kgroun threa .n a real system.com Special Creative Commons BY-SA 3.increment&rogressBy:L. )ere. this threa Coul o something meaning$ul.pro%ress.o!tain'essage:.sleep:?@@@.findViewById:R.

5he onStart:. 3andler o$$ers a set o$ post.com Special Creative Commons BY-SA 3. you %an also pass Runnable obOe%ts to the 3andler. an postDelayed:.:. 5his lightly (%3 Subscribe to updates at http://commonsware. threa . so it %an up ate Ci gets an su%h. an also so An roi oes not think our a%tivity is stu%k. both to let the 3andler get its Cork one. Chi%h Cill run those Runnable obOe%ts on the a%tivity "..ealing 4ith Threads 0ote that Ce then leave onStart:.. to a Runnable obOe%ts to the event <ueue. that means Ce nee to get out o$ onStart:..0 License Edition .. )oCever. 5his is %ru%ial. 2unning 8n Place +ust as 3andler supports post:.emo sample application Runn 5les . you %an use those same metho s on 7iew. metho s $or passing Runnable obOe%ts in $or eventual pro%essing. metho is invoke on the a%tivity ". threa .. 5he resulting a%tivity is simply a horiKontal progress bar* !igure $.< The Dandler.$ you Coul rather not $uss Cith Messa%e obOe%ts.

Dialo%.e%ute on the ". #u%h Qappropriate a%tionQ might be to use run. you must supply an Activity.ealing 4ith Threads simpli$ies your %o e. threa o$ the supplie 7iew.-$read2tilities helper %lass.onAt *ean Water Works& @et another option is to use the 2. you %an invoke is2. in that it <ueues up a Runnable to run on the ".n2.n the 3andler sample shoCn above. 5here$ore. threa . this metho Coul be super$luous N you pretty mu%h %an alCays tell by QeyeballingQ the %o e Chether it Cill be e.e%uting on the ".$ the Cork that the (%7 Subscribe to updates at http://commonsware.. /a%kgroun threa s not only a %omple.0 License Edition . >tilities #)nd 8 ..com Special Creative Commons BY-SA 3. an battery li$e.$ you alrea y are on the ". . threa . it invokes the Runnable imme iately. Chile the ba%kgroun threa is %hugging along. Chi%h o$$ers a set o$ stati% metho s to assist in Corking Cith the ". Chile eminently possible using the An roi 3andler system. Chi%h Cill tell you i$ you are presently e. $or sa$ety. i$ you pa%kage some o$ your %o e in a +AR $or others to reuse. )nd 5o46 The Caveats /a%kgroun threa s. in%lu ing* • 5he possibility that users Cill intera%t Cith your a%tivity7s ". it o$$ers is2. (irst. 5his Corks similar to the post:.-$read:. in that you %an then skip the 3andler obOe%t. are not all happiness an Carm puppies. . 5o that en . but they have real3Corl %osts in terms o$ available memory.ity. threa . )oCever.i$ you are not on the ".ibility. threa . C!". there are a Ci e range o$ s%enarios you nee to a%%ount $or Cith your ba%kgroun threa . /ut..e%uting on the ".. .-$read:. threa right noC. or 7iew. you lose a bit o$ $le.. metho s on 3andler an 7iew. threa or $rom a ba%kgroun threa . you might not knoC Chether your %o e is being e. an the 3andler has been aroun longer in the An roi toolkit an may be more teste .-$read:. threa . to $in out an take appropriate a%tion i$ you are not on the ". 5o i enti$y the proper ". threa or not.

.ealing 4ith Threads

ba%kgroun threa is oing is altere or invali ate by the user input, you Cill nee to %ommuni%ate this to the ba%kgroun threa . An roi in%lu es many %lasses in the java.util.concurrent pa%kage that Cill help you %ommuni%ate sa$ely Cith your ba%kgroun threa .

5he possibility that the a%tivity Cill be kille o$$ Chile ba%kgroun Cork is going on. (or e;ample, a$ter starting your a%tivity, the user might have a %all %ome in, $olloCe by a te;t message, $olloCe by a nee to look up a %onta%t...all o$ Chi%h might be su$$i%ient to ki%k your a%tivity out o$ memory. 5he ne;t %hapter Cill %over the various events An roi Cill take your a%tivity throughP hook the proper ones an be sure to shut oCn your ba%kgroun threa %leanly Chen you have the %han%e. 5he possibility that your user Cill get irritate i$ you %heC up a lot o$ C!" time an battery li$e Cithout giving any payba%k. 5a%ti%ally, this means using 1ro%ress6ar or other means o$ letting the user knoC that something is happening. #trategi%ally, this means you still nee to be e$$i%ient at Chat you o N ba%kgroun threa s are no pana%ea $or sluggish or pointless %o e. 5he possibility that you Cill en%ounter an error uring ba%kgroun pro%essing. (or e;ample, i$ you are gathering in$ormation o$$ the .nternet, the evi%e might lose %onne%tivity. Alerting the user o$ the problem via a 0oti$i%ation an shutting oCn the ba%kgroun threa may be your best option.

(%9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

CHAPTER 1(

Dandling )ctivity ifecycle Events

While this may soun like a broken re%or ...please remember that An roi evi%es, by an large, are phones. As su%h, some a%tivities are more important that others N taking a %all is probably more important to users than is playing #u oku. An , sin%e it is a phone, it probably has less RAM than oes your %urrent esktop or notebook. As a result, your a%tivity may $in itsel$ being kille o$$ be%ause other a%tivities are going on an the system nee s your a%tivity7s memory. 5hink o$ it as the An roi e<uivalent o$ the Q%ir%le o$ li$eQ N your a%tivity ies so others may live, an so on. @ou %annot assume that your a%tivity Cill run until you think it is %omplete, or even until the user thinks it is %omplete. 5his is one e;ample N perhaps the most important e;ample N o$ hoC an a%tivity7s li$e%y%le Cill a$$e%t your oCn appli%ation logi%. 5his %hapter %overs the various states an %allba%ks that make up an a%tivity7s li$e%y%le an hoC you %an hook into them appropriately.

SchroedingerAs )ctivity
An a%tivity, generally speaking, is in one o$ $our states at any point in time*

(,(
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Dandling )ctivity ifecycle Events

Active* the a%tivity Cas starte by the user, is running, an is in the $oregroun . 5his is Chat you7re use to thinking o$ in terms o$ your a%tivity7s operation. Paused* the a%tivity Cas starte by the user, is running, an is visible, but a noti$i%ation or something is overlaying part o$ the s%reen. Auring this time, the user %an see your a%tivity but may not be able to intera%t Cith it. (or e;ample, i$ a %all %omes in, the user Cill get the opportunity to take the %all or ignore it. #topped* the a%tivity Cas starte by the user, is running, but it is hi en by other a%tivities that have been laun%he or sCit%he to. @our appli%ation Cill not be able to present anything meaning$ul to the user ire%tly, only by Cay o$ a 0oti$i%ation. Dead* either the a%tivity Cas never starte &e.g., Oust a$ter a phone reset' or the a%tivity Cas terminate , perhaps ue to la%k o$ available memory.

ife6 .eath6 and -our )ctivity
An roi Cill %all into your a%tivity as the a%tivity transitions betCeen the $our states liste above. #ome transitions may result in multiple %alls to your a%tivity, an sometimes An roi Cill kill your appli%ation Cithout %alling it. 5his Chole area is rather murky an probably subOe%t to %hange, so pay %lose attention to the o$$i%ial An roi o%umentation as Cell as this se%tion Chen e%i ing Chi%h events to pay attention to an Chi%h you %an sa$ely ignore. 0ote that $or all o$ these, you shoul %hain upCar an invoke the super%lass7 e ition o$ the metho , or An roi may raise an e;%eption.

onCre te67 nd onCompleteTh #67
We have been implementing onCreate:; in all o$ our Activity sub%lasses in all the e;amples. 5his Cill get %alle in tCo situations* -. When the a%tivity is $irst starte &e.g., sin%e a system restart', onCreate:; Cill be invoke Cith a null parameter.
(,%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Dandling )ctivity ifecycle Events

2. .$ the a%tivity ha been running, ha onEree'e:; invoke , then sometime later Cas kille o$$, onCreate:; Cill be invoke Cith the 6undle $rom onEree'e:; as a parameter. Aealing Cith $reeKing an restoring state is %overe later in this %hapter. )ere is Chere you initialiKe your user inter$a%e an set up anything that nee s to be one on%e, regar less o$ hoC the a%tivity gets use . .$ the a%tivity is being restore $rom a $roKen state &se%on s%enario above', then onComplete-$aw:; is also %alle , an is passe the same 6undle as Cas the pre%e ing onCreate:;. .$ you Cant, you %an isolate your un3$reeKing logi% here.

onSt rt678 onRest rt678 nd onResume67
5hese are invoke as your a%tivity is brought to the $oregroun an ma e available to the user. 5he An roi o%umentation is %ontra i%tory as to un er Chat %ir%umstan%es an in Chat or er these are %alle . .t is $airly sa$e to say that*

Cill be %alle more %ommonly than the others, an shoul be %alle i$ the a%tivity Cas pause &on1ause:;' an then brought ba%k to the $oregroun relatively <ui%kly. .n $a%t, onResume:; shoul be %alle Oust be$ore the a%tivity is brought to the $oregroun in all %ir%umstan%es.
onResume:;

may be %alle i$ the a%tivity Cas stoppe &onStop:;' then starte up again Cithout the pro%ess being terminate
onStart:;

8enerally speaking, in these metho s you Cill Cish to o things that only make sense Chen a user is looking at your a%tivity, parti%ularly things that might have %hange sin%e the last time your a%tivity Cas looke at. (or e;ample, i$ you are polling a servi%e $or %hanges to some in$ormation &e.g., neC entries $or a $ee ', onResume:; is a $ine time to both re$resh the %urrent vieC an , i$ appli%able, ki%k o$$ a ba%kgroun threa to up ate the vieC &e.g., via a 3andler'.

(,,
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Dandling )ctivity ifecycle Events

onP use678 on9ree:e678 onStop678 nd onDestroy67
5he onEree'e:; event is triggere i$ An roi thinks that it may have to kill o$$ your a%tivity in the not3too3 istant $uture. @ou are passe a 6undle obOe%t, Chi%h Corks similar to a Map, Chere you %an persist the %urrent state o$ your ". &e.g., $iel values, %he%kbo; states'. 5hat 6undle Cill be re3supplie to you in onCreate:; an onComplete-$aw:; i$, in ee , your a%tivity Cas kille o$$. )oCever, it is possible that onEree'e:; Cill be %alle several times Cithout your a%tivity a%tually being kille o$$, so o not assume that Oust be%ause your onEree'e:; han ler is %alle that Qthe en is nearQ. Anything that steals your user aCay $rom your a%tivity N mostly, the a%tivation o$ another a%tivity N Cill result in your on1ause:; being %alle . )ere, you shoul un o anything you i in onResume:;, su%h as stopping ba%kgroun threa s, releasing any e;%lusive3a%%ess resour%es you may have a%<uire &e.g., %amera', an the like. >n%e on1ause:; is %alle , An roi reserves the right to kill o$$ your a%tivity7s pro%ess at any point. )en%e, you shoul not be relying upon re%eiving any $urther events. 5he onStop:; event is the %ounterpart to onRestart:;. )oCever, sin%e it might not get %alle , it is un%lear Chat spe%i$i%ally you might Cant to o in this metho . #imilarly, onDestroy:; may or may not be %alle be$ore your pro%ess en s. )oCever, there is no <uestion that, a$ter onDestroy:;, your pro%ess is en ing, an so the ne;t line o$ %o e o$ yours that Cill be invoke $or this a%tivity Cill be onCreate:;.

(,$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

PART III – Data Stores, Network Services, and APIs

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

s to %hoose $rom* -. you have tCo A!. you %an store in the pre$eren%es Chatever you like. to a%%ess a%tivity3 spe%i$i% pre$eren%es %et1references:. 5he simplest to use is the pre$eren%es system. pre$eren%es might be shareable a%ross appli%ations. su%h as the last $ee the user looke at in your $ee rea er. or Chatever. Strin%. the primary purpose is $or you to store user3spe%i$ie %on$iguration etails. Iventually. $rom Cithin your Activity. As the name suggests. $rom Cithin your Activity &or other appli%ation Context'. that Cill hang aroun betCeen invo%ations o$ an a%tivity. or Chat sort or er to use by e$ault on a list.' !re$eren%es %an either be $or a single a%tivity or share among all a%tivities in an appli%ation.3 Subscribe to updates at http://commonsware. 'etting What -ou Want 5o get a%%ess to the pre$eren%es.com Special Creative Commons BY-SA 3. but that is not supporte as o$ the time o$ this Criting.CHAPTER 1) >sing Preferences An roi has many i$$erent Cays $or you to store ata $or long3term use by your a%tivity. 2.0 License Edition . in the $orm o$ keyUvalue pairs &akin to a Map'. to a%%ess appli%ation3level pre$eren%es (. An roi alloCs a%tivities an appli%ations to keep pre$eren%es. et%. so long as it is keye by a Strin% an has a primitive value &boolean. >$ %ourse. %etS$ared1references:.

pass in @.g. i$ one part o$ your appli%ation &say. Ce nee an a%tivity that gives the user something to input &so Ce %an persist it as a pre$eren%e'.t also has* • • • remove:.7 Subscribe to updates at http://commonsware. to get ri clear:. (. . Chi%h is returne i$ there is no pre$eren%e set un er the spe%i$ie key. Chi%h o$$ers a series o$ getters to a%%ess name pre$eren%es. the %hanges. 5he getters also take a e$ault value.. sin%e the pre$eren%es obOe%t supports live %hanges. to persist your %hanges ma 5he last one is important N i$ you mo i$y pre$eren%es via the e itor an $ail to commit:. Cith the a%tivity7s %lass name as the pre$eren%e set name.an that Ce knoC Cill go through a likely a%tivity li$e%y%le event $or us to persist the %hange. metho also takes a name o$ a set o$ pre$eren%es N %et1references:. Stating -our Preference 8iven the appropriate S$ared1references obOe%t. ) Preference !or )ction 5o emonstrate pre$eren%es. %et6oolean:.com Special Creative Commons BY-SA 3. those %hanges Cill evaporate on%e the e itor goes out o$ s%ope. e$$e%tively %alls %etS$ared1references:. to return a boolean pre$eren%e'. to get ri o$ a single name pre$eren%e o$ all pre$eren%es e via the e itor commit:. returning a suitably3type result &e. you %an use edit:. a servi%e' Cill have a%%ess to the %hange value imme iately.0 License Edition . Conversely. another part o$ your appli%ation &say. an a%tivity' mo i$ies share pre$eren%es. /oth o$ those metho s return an instan%e o$ S$ared1references.>sing Preferences /oth take a se%urity mo e parameter N $or noC.. 5he %etS$ared1references:. to get an Qe itorQ $or the pre$eren%es. 5his obOe%t has a set o$ setters that mirror the getters on the parent S$ared1references obOe%t..

6utton5 android.5 6utton btn":6utton.id.c$eck. 5he +ava is a bit more involve * packa%e com.0 License Edition .>sing Preferences 5he $irst %riterion is easy* Oust use a %he%kbo. Ce have a roC o$ tCo Ci gets* our %he%kbo..content.verride public void onCreate:6undle icicle..findViewById:R. 8 finish:.9 Subscribe to updates at http://commonsware. .layout.Activity5 android.main.5 cb":C$eck6ox.prefs5 import import import import import import import android.C$eck6ox5 android.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#& <C$eck6ox android!id"#9Bid/c$eck# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#-$is c$eckbox is! unc$ecked# /& <6utton android!id"#9Bid/close# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#Close# /& </+inear+ayout& )ere.ample &1refs' is base o$$ o$ our earlier %he%kbo.wid%et.close. emo* <>xml version"#?.app. 8 super.6undle5 android.android..setOnCheckedChangeListener:t$is.5 < (.android.commonsware.setOnClickListener:new 6utton.onCreate:icicle. 8 public void onClick:7iew v.S$ared1references5 android.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.view.findViewById:R.5 btn.wid%et.Compound6utton5 public class 1refsDemo extends Activity implements Compound6utton.os.wid%et.5 cb.5 setContentView:R.com Special Creative Commons BY-SA 3. this e.id. an a button labele QCloseQ.n $a%t.7iew5 android.nC$eckedC$an%e+istener 8 C$eck6ox cb5 9.OnClickListener:.

ample. Ce get the a%tivity7s pre$eren%es. Ce o the same setup as be$ore. to that value.setText:#-$is c$eckbox is! c$ecked#. tying our a%tivity in as the ..setText:#-$is c$eckbox is! unc$ecked#..isChecked:. 8 super. Ce get a likely spot to persist the pre$eren%es. onStop:.edit:.5 < public void onCheckedChanged:Compound6utton button7iewG boolean isC$ecked. it Cill be set to $alse. an on1ause:.)ditor editor"settin%s. /y e$ault. .com Special Creative Commons BY-SA 3. Ce %an be sure that.5 public void on&ause:.5 S$ared1references settin%s"get&references:@.0 License Edition .n onResume:. an onDestroy:.. ($.getBoolean:#cb*c$ecked#G false..>sing Preferences <. 8 cb.putBoolean:#cb*c$ecked#G cb.nC$eckedC$an%e+istener $or the %he%kbo. Ce also hook into onResume:. %ausing An roi to go through the $ull %hain o$ on1ause:.5 S$ared1references.on&ause:.n onCreate:. $or our test. i$ the pre$eren%e is not $oun . 8 if :isC$ecked. 5his Cay. "nlike in the original e. an %ommit the %hange.5 < else 8 cb. We also tie an anonymous .. 5his proa%tively %loses the a%tivity. Ce a%%ess the a%tivity7s pre$eren%es an retrieve a cb*c$ecked boolean pre$eren%e.5 < < public void on$esume:.5 < cb. in on1ause:.5 editor... 8 super.setChecked:settin%s.7s %urrent state. as it %loses out the a%tivity.. on the a%tivity.commit:. Subscribe to updates at http://commonsware. Conversely. store the cb*c$ecked pre$eren%e as the %he%kbo.5 < < . Chi%h %alls finis$:.nClick+istener to the button.on$esume:. an set the %he%kbo.5 S$ared1references settin%s"get&references:@..5 editor.

then %li%k the Close button. is un%he%ke * !igure $(< The Prefs. alrea y %he%ke * ($( Subscribe to updates at http://commonsware.0 License Edition .. you Cill see that it opens Cith the %he%kbo.$ you %he%k the %he%kbo. the %he%kbo.emo sample application6 as initially launched . then re3open the a%tivity.com Special Creative Commons BY-SA 3.>sing Preferences When Ce $irst laun%h the a%tivity.

is %he%ke .com Special Creative Commons BY-SA 3. implementation is being %alle .0 License Edition . 5his means that our onC$eckedC$an%ed:. ($% Subscribe to updates at http://commonsware.>sing Preferences !igure $%< The same application6 after checking the checkbox 0oti%e that the label $or the %he%kbo. state via setC$ecked:. in that it says the %he%kbo. is also %orre%t.. even though Ce are manually setting the %he%kbo.

you nee to get yoursel$ a Resources obOe%t. so it gets put in the An roi appli%ation .CHAPTER 1* )ccessing !iles While An roi o$$ers stru%ture storage. sin%e it is un%hanging until the user installs an up ate version o$ your appli%ation pa%kage. e. #in%e you %an only get an .apk $ile as part o$ the pa%kaging pro%ess.d:. )en%e.nputStream on the $ile you spe%i$y. that is as simple as %alling %etResources:. A Resources obOe%t o$$ers openRawResource:.com Special Creative Commons BY-SA 3. to get an .words. An roi o$$ers tCo mo els $or a%%essing $iles* one $or $iles pre3pa%kage Cith your appli%ation. it is really only use$ul $or stati% re$eren%e ata. Rather than a path. the i enti$ier is a%%essible in +ava as R.0 License Edition ..nputStream.pe%ts an integer i enti$ier $or the $ile as pa%kage . sometimes a simple $ile Cill su$$i%e. 5he easiest Cay to eploy that is to put the $ile in the res/raw ire%tory. -ou )nd The Dorse -ou 2ode 8n +n Let7s suppose you have some stati% ata you Cant to ship Cith the appli%ation. ($. 5his Corks Oust like a%%essing Ci gets via find7iew6y. openRawResource:. 5o a%%ess this $ile.raw.xml in res/raw. Moreover. via pre$eren%es an atabases. you have no means o$ mo i$ying this $ile. N i$ you put a $ile name words. (rom an a%tivity. an one $or $iles %reate on3 evi%e by your appli%ation. either the re$eren%e ata has to be vali $or the $oreseeable $uture. su%h as a list o$ Cor s $or a spell3%he%ker. Subscribe to updates at http://commonsware.

n-op"#false# /& </+inear+ayout& .g.n the Static sample proOe%t. this time using a stati% EML $ile instea o$ a har Cire array in +ava.)ccessing !iles or you Cill nee to provi e some means o$ up ating the ata. 5he layout is the same* <>xml version"#?. An alternative is to keep the re$eren%e ata as3is but keep mo i$i%ations in a $ile or atabase.android. a atabase'.ample.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.0 License Edition . i$ your appli%ation ships a $ile o$ "RLs. 5he simplest Cay to han le that is to use the re$eren%e ata to bootstrap some other mo i$iable $orm o$ storage &e.com Special Creative Commons BY-SA 3. you %oul have a se%on $ile that tra%ks "RLs a e by the user or re$eren%e "RLs that Cere elete by the user.n a ition to that EML $ile. (or e. you also nee an EML $ile Cith the Cor s to shoC in the list* <words& <word <word <word <word <word <word <word <word <word <word <word value"#lorem# /& value"#ipsum# /& value"#dolor# /& value"#sit# /& value"#amet# /& value"#consectetuer# /& value"#adipiscin%# /& value"#elit# /& value"#morbi# /& value"#vel# /& value"#li%ula# /& ($$ Subscribe to updates at http://commonsware. . e. you Cill $in a reCorking o$ the listbo.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <+ist7iew android!id"#9android!id/list# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!drawSelector.ample $rom earlier.. but this makes $or tCo %opies o$ the ata in storage. an merge them together Chen you nee a %omplete pi%ture o$ the in$ormation.

G #Cancel#G true. an put them somepla%e $or the list to pi%k up* public class StaticEileDemo extends +istActivity 8 -ext7iew selection5 Array+ist items"new #rrayList:.open$aw$esource:R..com Special Creative Commons BY-SA 3.id.0 License Edition .5iBB.5 9. 8 items.get#ttri!ute:#value#.a%tly a mo el o$ spa%e e$$i%ien%y. it Cill su$$i%e $or a emo.5 selection":-ext7iew.item:i. .5 for :int i"@5i<words.main.getLength:..5 < catc$ :-$rowable t.)ccessing !iles <word value"#vitae# /& <word value"#arcu# /& <word value"#aliJuet# /& <word value"#mollis# /& <word value"#etiam# /& <word value"#vel# /& <word value"#erat# /& <word value"#placerat# /& <word value"#ante# /& <word value"#porttitor# /& <word value"#sodales# /& <word value"#pellentesJue# /& <word value"#au%ue# /& <word value"#purus# /& </words& While this EML stru%ture is not e. 5he +ava %o e noC must rea in that EML $ile.words.5 < setList#dapter:new ArrayAdapter<Strin%&:t$isG ($/ Subscribe to updates at http://commonsware.verride public void onCreate:6undle icicle.selection.add:::)lement.onCreate:icicle.5 /ode+ist words"doc.parse:inG null.close:.5 < in.newInstance:.newDocumentBuilder:.raw.5 Document6uilder builder"Document6uilderEactory . parse out the Cor s.5 Document doc"builder..5 setContentView:R. 8 show#lert:#)xceptionW#G @G t.get+lementsByTag%ame:#word#.5 try 8 .toString:..nputStream in"get$esources:. 8 super.words.findViewById:R.layout.

5hat is %overe in the ne. 8 selection.0 License Edition .setText:items.. the $ile %oul Oust as easily ($0 Subscribe to updates at http://commonsware. sin%e the list o$ Cor s is the same..raw.'.t %hapter.5 < 5he i$$eren%es mostly lie Cithin onCreate:...emo sample application >$ %ourse. there are even easier Cays to have EML $iles available to you as pre3pa%kage $iles N using an EML resour%e.words.ample use EML.)ccessing !iles < android. then pour the value attributes into an Array+ist $or use by the ArrayAdapter. Chile this e.5 < public void onListItemClick:+ist7iew parentG 7iew vG int positionG lon% id.get:position.< The Static!ile. )oCever.nputStream $or the EML $ile &%etResources:.layout.R.openRawResource:R. 5he resulting a%tivity looks the same as be$ore. then use the built3 in EML parsing logi% to parse the $ile into a A>M Document.simple*list*item*?G items.. Oust relo%ate * !igure $. We get an .toString:.com Special Creative Commons BY-SA 3. pi%k out the Cor elements.

t3base .nput:. to release the stream Chen one • • Relative paths &i. pulle $rom the ReadCrite sample appli%ation* <>xml version"#?. you probably Cant to %reate a %ontent provi er.android. .t e itor.utputStream. respe%tively.utput:.U> logi%* • Wrap those streams as nee e .nput:. . appli%ation3spe%i$i% ata $iles is nearly i enti%al to Chat you might o in a esktop +ava appli%ation.txt $ile via openEile. an openEile.nputStream an .$ tCo appli%ations both try rea ing a notes. (rom that point $orCar . 2eadinA An WritinA Rea ing an Criting your oCn. it is not mu%h i$$erent than regular +ava . on your Activity or other Context to get an . those Cithout lea ing slashes' are lo%al to the appli%ation.0 License Edition . su%h as using an ..)ccessing !iles have been a simple one3Cor 3per3line list.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!orientation"#vertical#& <6utton android!id"#9Bid/close# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#Close# /& <)dit-ext android!id"#9Bid/editor# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!sin%le+ine"#false# /& </+inear+ayout& ($3 Subscribe to updates at http://commonsware.utputStreamCriter $or te. /eloC you Cill see the layout $or the Corl 7s most trivial te. as Cill be es%ribe an up%oming %hapter. they Cill ea%h a%%ess their oCn e ition o$ the $ile. or in some other $ormat not han le natively by the An roi resour%e system.e.$ you nee to have one $ile a%%essible $rom many pla%es..com Special Creative Commons BY-SA 3.nputStreamReader or .@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. 5he key is to use openEile.U> Rea or Crite the ata "se close:.

nputStream5 java.view.main.nputStream5 java.nputStreamReader5 java.5 < in..6utton5 android.5 if :inW"null.commonsware. 8 super..5 6utton btn":6utton.6undle5 android.)dit-ext5 java.utputStreamCriter5 public class ReadCriteEileDemo extends Activity 8 )dit-ext editor5 9..findViewById:R..id.findViewById:R. 8 public void onClick:7iew v.OnClickListener:.io.append:strB#4n#.5 try 8 .wid%et. 8 super.io.layout.7iew5 android. Cith a QCloseQ button above it.5 < public void on$esume:.6ufferedReader5 java.os..io.id.5 btn.txt#.nputStream in"open"ileInput:#notes.5 Strin% str5 Strin%6uffer buf"new StringBuffer:.5 < <.files5 import import import import import import import import import import import android.wid%et.setOnClickListener:new 6utton. 8 buf. W" null.com Special Creative Commons BY-SA 3.Activity5 android. 8 6ufferedReader reader"new Buffered$eader:new InputStream$eader:in..io.close.close:. 5he +ava is only slightly more %ompli%ate * packa%e com.app.utputStream5 java.0 License Edition .5 ($7 Subscribe to updates at http://commonsware.android.io.readLine:.editor.on$esume:.io.5 setContentView:R.)ccessing !iles All Ce have here is a large te.onCreate:icicle. 8 finish:.t3e iting Ci get.5 w$ile ::str " reader.verride public void onCreate:6undle icicle.5 editor":)dit-ext..

8 show#lert:#)xceptionW#G @G t.write:editor.utputStreamCriter out"new OutputStream*riter:open"ileOutput:#notes. or similar situations.toString:.G #Cancel#G true.com Special Creative Commons BY-SA 3. Ce hook into on1ause:. Ce Cire up the button to %lose out our a%tivity Chen %li%ke by using set.. 8 super..5 try 8 .t e itor. to open notes. into Chi%h Ce pour the %ontents o$ the te. 8 show#lert:#)xceptionW#G @G t.toString:. . Ce use openEile.. su%h as via our QCloseQ button. )ere.$ the $ile is not $oun .5 < < < catc$ :-$rowable t.nClick+istener:. $rom a $resh laun%h or a$ter having been $roKen. Ce assume this is the $irst time the a%tivity Cas run &or the $ile Cas elete by other means'. so Ce get %ontrol Chen our e itor is %oming ba%k to li$e. to rea in notes. We use openEile.txt an pour the %ontents into the te.5 < < public void on&ause:.0 License Edition .setText:buf. it oesn7t look like mu%h* ($9 Subscribe to updates at http://commonsware.t.MG we probably $avenZt created it yet < catc$ :-$rowable t. 0e.utput:. an Ce Oust leave the e itor empty.getText:.txt..G #Cancel#G true.txt#G out.)ccessing !iles editor. >$ %ourse. Ce hook into onResume:...nput:. to invoke finis$:.5 < (irst. on the a%tivity. the phone being turne o$$. so Ce get %ontrol as our a%tivity gets hi en by other user a%tivity or is %lose . surviving our a%tivity being %lose . (inally.5 < catc$ :java.io.Eile/otEound)xception e.close:.toString:.5 < @.on&ause:.t e itor. 8 // t$atZs .5 out.toString:. 5he net result is that Ce have a persistent notepa * Chatever is type in Cill remain until elete .

com Special Creative Commons BY-SA 3. Subscribe to updates at http://commonsware.)ccessing !iles !igure $$< The 2eadWrite!ile.emo sample application6 as initially launched !igure $/< The same application6 after entering some text (/.0 License Edition .

amples in this book.ample.com Special Creative Commons BY-SA 3. all the other types o$ resour%es are parse $or you.%eption o$ raC resour%es &res/raw/'. su%h as an animation suggesting the turning o$ a page Chen a button is %li%ke . $or e. in%lu ing* • Animations &res/anim/'. that you %an take a vantage o$ in your An roi appli%ations.CHAPTER 1- Working 4ith 2esources Resour%es are stati% bits o$ in$ormation hel outsi e the +ava sour%e %o e. su%h as images an strings. there are several other types o$ resour%e available to you. esigne $or short %lips as part o$ a user inter$a%e. Chen you lay out an a%tivity7s ". you o not have to parse the layout EML yoursel$ N An roi han les that $or you. via a layout resour%e &res/layout/'. .0 License Edition . 5here are many other types o$ resour%e. either by the An roi pa%kaging system or by the An roi system on the evi%e or emulator. With the e. $or putting stati% i%ons or other pi%tures in a user inter$a%e • (/( Subscribe to updates at http://commonsware. The 2esource ineup Resour%es are store as $iles un er the res/ ire%tory in your An roi proOe%t layout.mages &res/drawable'.n a ition to layout resour%es &$irst seen in an earlier %hapter' an raC resour%es &intro u%e in another earlier %hapter'. @ou have seen one type o$ resour%e N the layout N $re<uently in the e. #o.

so you %an make your Cor s be bol or itali% intermingle Cith normal te.t $ormatting.ternaliKe strings.g.t outsi e the main sour%e %o e o$ your appli%ation is generally %onsi ere to be a very goo i ea.xml'. to both give these sorts o$ %onstants symboli% names an to keep them separate $rom the rest o$ the %o e &e. An roi supports simple te. it is easier to make %orre%tions i$ all the strings are in one spot instea o$ s%attere throughout your sour%e %o e.Working 4ith 2esources • #trings.n those %ases. An roi supports regular e.. Pl in Strin!s 8enerally speaking. $or internationaliKation an lo%aliKation' EML &res/xml/'.</strin%& </resources& 5he only tri%ky part is i$ the string value %ontains a <uote &#' or an apostrophe &Z'.n parti%ular. Cith a resources root element.</strin%& <strin% name"#lau%$s#&3e w$o lau%$s last. . Chi%h is the uni<ue name $or this string.. all you nee to o is have an EML $ile in the res/values ire%tory &typi%ally name res/values/strin%s. an one %hil strin% element $or ea%h string you Cish to en%o e as a resour%e.. %overe later in this %hapter.t o$ the string* <resources& <strin% name"#Juick#&-$e Juick brown fox. it helps Cith internationaliKation &. an a single te. 5he strin% element takes a name attribute.com Special Creative Commons BY-SA 3.0 License Edition .tQ.-80' an lo%aliKation &L-00'. %olors. you Cill Cant to es%ape those values.t element %ontaining the te. Chere the string has pla%ehol ers $or ynami%ally3inserte in$ormation. %alle Qstyle te. an imensions &res/values/'. by (/% Subscribe to updates at http://commonsware. arrays.t... >n top o$ that. . $or stati% EML $iles %ontaining your oCn ata an stru%ture • String Theory Feeping your labels an other bits o$ te. along Cith Qstring $ormatsQ. Iven i$ you are not going to translate your strings to other languages.

9strin%/lau%$s'. My name is [?\s'.5 Strin% strResult"Strin%.Juick.g. $or light )5ML $ormatting.5 Styled Te.anot$er*label. >r. )ere.5 ::-ext7iew.M supports string $ormats.strin%. you shoul have raC resour%es %ontaining )5ML..layout.strin%.layout. an <u&.findViewById:R.g. you %oul en%lose the value in <uotes &e. Strin! 9orm ts As Cith other implementations o$ the +ava language.%eption that the result o$ the %etStrin%:.t ..lau%$s.strin%.my*name.g. %etStrin%:R.e Cith R.Working 4ith 2esources pre%e ing them Cith a ba%kslash &e. . then pour those into a WebFit Ci get.. %all is really a Spanned* ::-ext7iew. that being the uni<ue name pre$i. Cith the e.com Special Creative Commons BY-SA 3..some*label. you %an Oust use a string resour%e* <resources& <strin% name"#b#&-$is $as <b&bold</b& in it. -$ese are t$e times t$at try men4Zs souls'.'.. the string %ontains pla%ehol ers representing ata to be repla%e at runtime by variable in$ormation &e.findViewById:R. i$ it is Oust an apostrophe.A o$ the string resour%e.g. <i&.$ you Cant really ri%h te. !lain strings store as resour%es %an be use as string $ormats* Strin% strEormat"getString:R.. @ou %an then re$eren%e this string $rom a layout $ile &as 9strin%/.0 License Edition . An roi 7s Aalvik . Chere the ellipsis is the uni<ue name N e. )oCever. &e..t.. Subscribe to updates at http://commonsware.setText:getString:R.</strin%& <strin% name"#i#&C$ereas t$is $as <i&italics</i&W</strin%& </resources& @ou %an a%%ess these the same as Cith plain strings..strin%.setText:strResult.format:strEormatG #-im#. #-$ese are t$e times t$at try menZs souls. ... Cith the resour%e .g. >r you %an get the string $rom your +ava %o e by %alling %etStrin%:.5 (/.#'. using <b&.

)ere is the layout $ile* <>xml version"#?.format:getString:R.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.5 =.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <+inear+ayout xmlns!android"#$ttp!//sc$emas. not Spanned obOe%ts Cith $ormatting instru%tions. Corks on Strin% obOe%ts. )5ML into a Spanned obOe%t via some-ext7iew.. .5 5o see this in a%tion.funky*format..com/apk/res/android# android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# & <6utton android!id"#9Bid/format# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#9strin%/btn*name# /& <)dit-ext android!id"#9Bid/name# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& </+inear+ayout& <-ext7iew android!id"#9Bid/result# (/$ Subscribe to updates at http://commonsware. being sure to es%ape any string values you substitute in.android.t gets tri%ky is Cith style string $ormats. in %ase they %ontain angle bra%kets or ampersan s Strin%. let7s look at the Strin%s emo.G -ext2tils. Intity3es%ape the angle bra%kets in the string resour%e &e.Working 4ith 2esources Styled 9orm ts Where style te.com Special Creative Commons BY-SA 3. %etStrin%:R.g. here is the Corkaroun * -.strin%.from3tml:.html+ncode:str/ame. 8enerate the $ormat results. t$is is Ylt5bY%t5[?\sYlt5/bY%t5' 2.g..format:.android. though it Cill not be style at this point &e. as Strin%. Convert the entity3es%ape 3tml.$ you really Cant to have style string $ormats. Retrieve the string resour%e as normal.strin%.funky*format.setText:3tml .from(tml:resultEromStrin%Eormat.' ?.0 License Edition ..

commonsware.-ext2tils5 android. 8 super.android.os. Chile our style string $ormat is in funky*format.5 (// Subscribe to updates at http://commonsware. 5he btn*name string is the %aption o$ the 6utton. 5he 6utton in the layout $ile re$eren%es a string resour%e &9strin%/btn*name'.7iew5 android. 5he intent is $or somebo y to enter their name in the $iel . then %li%k the button to %ause the label to be up ate Cith a $ormatte message %ontaining their name. an a label.view.com Special Creative Commons BY-SA 3.-ext7iew5 public class Strin%sDemo extends Activity 8 )dit-ext name5 -ext7iew result5 9.id.5 setContentView:R. so Ce nee a string resour%e $ile &res/values/strin%s.3tml5 android.xml'* <>xml version"#?.)dit-ext5 android.verride public void onCreate:6undle icicle.wid%et. (inally.name. a $iel . it is Oust a button.6undle5 android.0 License Edition .wid%et.onCreate:icicle.Working 4ith 2esources android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& </+inear+ayout& As you %an see.app.5 name":)dit-ext.findViewById:R.text.wid%et.layout.text.resources5 import import import import import import import import android. Ce nee a pin%h o$ +ava* packa%e com.Activity5 android.main.6utton5 android. to hook all this together.@# encodin%"#utf(A#>& <resources& <strin% name"#app*name#&Strin%sDemo</strin%& <strin% name"#btn*name#&/ame!</strin%& <strin% name"#funky*format#&My name is Ylt5bY%t5[?\sYlt5/bY%t5</strin%& </resources& 5he app*name resour%e is automati%ally %reate by the activityCreator s%ript.

getting a Strin% ba%k.funky*format.5 < <.OnClickListener:.strin%. N something Ce %oul have one at onCreate:. (irst.findViewById:R..from3tml:.t obOe%t via 3tml.5 < private void apply"ormat:. Chi%h is %alle Chen the button is %li%ke .5 btn. Ce %onvert the simple )5ML into a style te.$tml)ncode:. 0ote the use o$ -ext2tils.result.5 < < 5he string resour%e manipulation %an be $oun in applyEormat:..toString:. 8 Strin% format"getString:R.5 result.Working 4ith 2esources result":-ext7iew. sin%e the string resour%e is in entity3en%o e )5ML. Ce $ormat the value in the $iel using this $ormat.t.5 Strin% simpleResult"Strin%.from(tml:simpleResult. an up ate our label..format. 0e.id.html+ncode:name.com Special Creative Commons BY-SA 3. When the a%tivity is $irst laun%he . (inally.. 8 apply"ormat:. Ce have an empty label* (/0 Subscribe to updates at http://commonsware. to entity3en%o e the entere name.setOnClickListener:new 6utton.id.5 6utton btn":6utton.format:formatG -ext2tils.findViewById:R..0 License Edition .getText:. time $or e$$i%ien%y. Ce get our $ormat via %etStrin%:.setText:3tml. 8 public void onClick:7iew v. in %ase somebo y e%i es to use an ampersan or something.

com Special Creative Commons BY-SA 3.emo sample application6 as initially launched but i$ Ce $ill in a name an %li%k the button. Ce get* !igure $3< The same application6 after filling in some heroic figureAs name (/3 Subscribe to updates at http://commonsware.Working 4ith 2esources !igure $0< The Strings.0 License Edition .

foo' android.ma%es. to istinguish them $rom appli%ation3spe%i$i% resour%es &e. images are re$eren%e as 9drawable/. plus the base name &e..g.xml an .mages %an be use anyChere that re<uires a Drawable.ample to use an i%on $or the button instea o$ the string resour%e...app/raw/.. Chere you nee an image resour%e . Chere com. Chere the ellipsis is the base name o$ the $ile &e.tual name o$ the raC resour%e &e. an 8. is the numeri% resour%e .example. using an ..0 License Edition .android.picture*frame'.pn%..drawable. 8..example.ma%e6utton an re$eren%ing a raCable name 9drawable/icon* <>xml version"#?. $or res/drawable/foo. #o.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.R.A.A $or the resour%e in <uestion &e.g. Within layout $iles. su%h as the image an ba%kgroun o$ an .app is the name o$ the +ava pa%kage use by your appli%ation in AndroidManifest.com Special Creative Commons BY-SA 3.Working 4ith 2esources 'ot the Picture: An roi supports images in the !08. android.pn%' 0ote that An roi ships Cith some image resour%es built in.example.drawable.. "sing images is simply a matter o$ putting your image $iles in res/drawable/ an then re$eren%ing them as a resour%e.g. the resour%e name is 9drawable/foo'.drawable pre$i. 2. let7s up ate the previous e.resource!//com.app is the name o$ the +ava pa%kage use by your appli%ation in AndroidManifest. R. you %an use one o$ tCo i$$erent string $ormats $or the path* -.example.. 5his %an be $oun as .( is o$$i%ially is%ourage . .app/..com/apk/res/android# (/7 Subscribe to updates at http://commonsware.g. android... . (irst. foo $or res/drawable/foo. Chere com. .g.xml an . Ce slightly a Oust the layout $ile. 5hose are a resse in +ava Cith an android.foo'.( $ormats. hoCeverP !08 is the overall pre$erre $ormat.R.resource!//com.. +!I8.$ you nee a 2ri to an image resour%e..n +ava. use R.drawable.ma%e7iew.drawable. is the te... the value o$ R..

android.commonsware.Working 4ith 2esources android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <+inear+ayout xmlns!android"#$ttp!//sc$emas.verride public void onCreate:6undle icicle.os.id.Activity5 android.main.5 result":-ext7iew. 8 super.ma%esDemo extends Activity 8 )dit-ext name5 -ext7iew result5 9.5 name":)dit-ext.text.text.7iew5 android.layout..wid%et.app.-ext7iew5 public class . repla%ing our 6utton Cith an .n this %ase. Ce tCi le the +ava sour%e.-ext2tils5 android.com Special Creative Commons BY-SA 3.6undle5 android.view.onCreate:icicle.findViewById:R.?2 !08 $ile $rom the 0uvola i%on set.wid%et.ma%e6utton android!id"#9Bid/format# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!src"#9drawable/icon# /& <)dit-ext android!id"#9Bid/name# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& </+inear+ayout& <-ext7iew android!id"#9Bid/result# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& </+inear+ayout& 0e.wid%et.0 License Edition . .t.ma%e6utton5 android.wid%et.6utton5 android.5 (/9 Subscribe to updates at http://commonsware.result. (inally.com/apk/res/android# android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# & <.)dit-ext5 android.android.name.findViewById:R. Ce nee to put an image $ile in res/drawable Cith a base name o$ i%on.id.3tml5 android. Ce use a ?2.5 setContentView:R.ma%e6utton* packa%e com.resources5 import import import import import import import import import android.

8 Strin% format"getString:R.5 result. (0.id.. 8 public void onClick:7iew v. 8 apply"ormat:.format.5 Strin% simpleResult"Strin%.n a previous %hapter.5 < private void apply"ormat:. 5here is another Cay o$ pa%kaging stati% EML Cith your appli%ation* the EML resour%e.html+ncode:name... Subscribe to updates at http://commonsware.ma%e6utton btn":.findViewById:R.ma%e6utton.format:formatG -ext2tils.from(tml:simpleResult.toString:.setOnClickListener:new 6utton.OnClickListener:.strin%.Working 4ith 2esources .5 < <. our button has the esire i%on* !igure $7< The 8mages..setText:3tml.com Special Creative Commons BY-SA 3.funky*format.emo sample application ?* H The 2esource Way .5 < 0oC.0 License Edition .getText:. Ce shoCe hoC you %an pa%kage EML $iles as raC resour%es an get a%%ess to them $or parsing an usage.5 btn.

)/D*-A0.xmlpull.v?.android.xmlpull.+istActivity5 android. but in res/xml/. you %an a%%ess the tag7s name an attributesP a single -)Uevent represents the %on%atenation o$ all te.Activity5 android.layout. 8 super.xmlpull.words. 5he layout stays the same.commonsware.Array+ist5 or%.xml.app.ArrayAdapter5 android. Chi%h %oul be S-AR-*-A0.resources5 import import import import import import import import import import import import android.Uml1ull1arser)xception5 public class UM+ResourceDemo extends +istActivity 8 -ext7iew selection5 Array+ist items"new #rrayList:. let7s reCrite the +ava %o e $or the Static sample proOe%t to use an EML resour%e. testing.C2M)/-. an invoking per3element logi%. 5his returns an instan%e o$ the presently3un o%umente Uml1ull1arser.wid%et.view. $oun in the or%. Cith an EML $ile o$ words.6undle5 android.5 9.v?. An EML pull parser is event3 riven* you keep %alling next:.0 License Edition .%etUml:R. an you %an a%%ess it by %etUml:.main.A o$ R.os. you %oul %all %etResources:.v? +ava namespa%e.7iew5 android. Ao%umentation $or this library %an be $oun at at the parser7s site as o$ this Criting. on a Resources obOe%t..wid%et.nputStream5 java. so all that nee s repla%ing is the +ava sour%e* packa%e com.app.xml..io. #o. /y looping. 5his neC proOe%t. on the parser to get the ne.Working 4ith 2esources #imply put the EML $ile in res/xml/. re<uires that you pla%e the words.Adapter7iew5 android. )/D*D.. 5o see this in a%tion. supplying it a resour%e . UM+.5 (0( Subscribe to updates at http://commonsware.wid%et.+ist7iew5 android.wid%et.util.xml.xml $ile $rom Static not in res/raw/.-ext7iew5 java.t event.onCreate:icicle.Uml1ull1arser5 or%. you parse the $ile. >n a S-AR-*-A0 event.t no es that are ire%t %hil ren o$ this element.com Special Creative Commons BY-SA 3. et%. plus the base name o$ your EML $ile.5 setContentView:R. in an a%tivity.verride public void onCreate:6undle icicle.

selection.e-uals:#word#.eJuals:#word#.get.C2M)/-. it is sa$e enough to assume there is e..findViewById:R. attribute is Chat you think it is.. then Ce get the one3 an 3only attribute an pop that into our list o$ items $or the sele%tion Ci get.catc$ blo%k.0 License Edition . albeit Cith a i$$erent name in the title bar* (0% Subscribe to updates at http://commonsware.get#ttri!uteValue:@. 8 show#lert:#)xceptionW#G @G t. you might %onsi er %he%king the attribute %ount &%etAttributeCount:.words.get:position.get+ entType:.com Special Creative Commons BY-SA 3.""Uml1ull1arser. . Ce get our Uml1ull1arser an loop until the en o$ the o%ument.' an the name o$ the attribute &%etAttribute/ame:. 8 if :xpp.'. /ut..%et/ame:.5 try 8 Uml1ull1arser xpp"get$esources:.5 < < xpp.S-AR-*-A0..5 < < < public void onListItemClick:+ist7iew parentG 7iew vG int positionG lon% id.get+ entType:. i$ you Cere not as %om$ortable that the EML is properly e$ine ..id.get%ame:..layout.. 8 selection.a%tly one attribute.Working 4ith 2esources selection":-ext7iew.next:.5 w$ile :xpp...G #Cancel#G true.5 < setList#dapter:new ArrayAdapter<Strin%&:t$isG android.5 < catc$ :-$rowable t. 8 if :xpp. insi e our try.toString:.)/D*D.W"Uml1ull1arser.5 < 0oC.setText:items.' be$ore blin ly assuming the @3in e..simple*list*item*?G items. 8 items.$ the %urrent event is S-AR-*-A0 an the name o$ the element is word &xpp. #in%e Ce7re in %omplete %ontrol over the EML $ile.toString:.add:xpp. 5he result looks the same as be$ore.ml:R.xml.R.

?@px $or ten pi.emo sample application *iscellaneous Galues .. you %an pla%e one &or more' EML $iles es%ribing simple resour%es* imensions.n the res/values/ ire%tory.Working 4ith 2esources !igure $9< The ?* 2esource.g. #?@px#' as parameters to %alls.els'. @ou %an.amples. not in layout EML $iles. Chere they Cere passe as simple strings &e. you %an re$eren%e them $rom both +ava an layouts. We have alrea y seen uses o$ imensions an %olors in previous e.. there are several i$$erent units o$ measurement available to you* (0. Subscribe to updates at http://commonsware. o$ %ourse.els &e.. %olors..com Special Creative Commons BY-SA 3. /y putting these values in resour%e EML $iles. Resour%e EML $iles have a root element o$ resourcesP everything else is a %hil o$ that root.but this only Corks insi e +ava sour%e. plus have them %entrally lo%ate $or easy e iting. set these up as +ava stati% $inal obOe%ts an use their symboli% names. While this book usually uses pi.g. an arrays. Dimensions Aimensions are use in several pla%es in An roi to es%ribe istan%es. su%h a Ci get7s pa ing.0 License Edition .

Chere the ellipsis is a pla%ehol er $or your uni<ue name $or the resour%e &e..e Cith R. an a single %hil te. a a dimen element. values.dimen..el ensity &s%ale3 in epen ent pi. you re$eren%e imension resour%es by the uni<ue name pre$i. .Working 4ith 2esources • an mm $or in%hes an a%tual siKe o$ the s%reen in pt dp millimeters. you %an re$eren%e imensions as 9dimen/. &e.t$in.0 License Edition .a e%imal R8/ values. Cith a name attribute $or your uni<ue name $or this resour%e. base on the • $or points. leaving you Cith $our styles* • • • • DR06 DAR06 DRR0066 DAARR0066 5hese Cork similarly to their %ounterparts in Cas%a ing #tyle #heets &C##'. Chi%h in publishing terms is -U22n o$ an in%h &again. @ou have your %hoi%e o$ single3%hara%ter he.els an s%ale3in epen ent pi. base on the a%tual physi%al siKe o$ the s%reen' an sp $or evi%e3in epen ent pi.el e<uals one p $or a -40 pi resolution s%reen.els also take into a%%ount the user7s pre$erre $ont siKe' • 5o en%o e a imension as a resour%e.. Resources.com Special Creative Commons BY-SA 3.g.dimen.g.n a layout. respe%tively. (0$ Subscribe to updates at http://commonsware.n +ava.. t$in an fat $rom the sample above'.'. values or ouble3%hara%ter he. Colors Colors in An roi are he.t element representing the value* <resources& <dimen name"#t$in#&?@px</dimen& <dimen name"#fat#&?in</dimen& </resources& .. Cith the ratio s%aling base on the a%tual s%reen pi.els N one pi.%etDimen:R. also optionally spe%i$ying an alpha %hannel.

com Special Creative Commons BY-SA 3.t element Cith the value $or that entry in the array* <resources& <array name"#$onorifics#& <item&Dr.. o$ %ourse. you %an re$eren%e %olors as 9color/.$ you Cish to turn them into resour%es. a one or more %hil item elements.g.'. to get a o$ the items in the list. put these R8/ values as string literals in +ava sour%e or layout resour%es...n +ava.</item& <item&Mr.</item& <item&Ms. you nee one array element per array.e Cith R. 5he parameter to %etStrin%Array:.</item& </array& </resources& (rom your +ava %o e. Cith a name attribute $or the uni<ue name you are giving the array. &e.. ea%h o$ Chi%h having a single te.</item& <item&Mrs..%etStrin%Array:.'. Mrs.n the resour%e $ile. .dimen.. . Resources. .n a layout.'.forest*%reen. you re$eren%e %olor resour%es by the uni<ue name pre$i. Ms.%etStrin%Array:R. is your uni<ue name $or the array..g. burnt*umber'. an a single te.t element %ontaining the R8/ value itsel$* <resources& <color name"#yellow*oran%e#&DEEDLLL</color& <color name"#forest*%reen#&D@@LL@@</color& <color name"#burnt*umber#&DAAIIHN</color& </resources& .0 License Edition . su%h as a list o$ honori$i%s &Mr.. repla%ing the ellipsis Cith your uni<ue name $or the %olor &e.array. Strin%OP (0/ Subscribe to updates at http://commonsware. pre$i. you %an then use Resources. et%.e Cith R..g. 5hen.. though. Resources. Arr ys Array resour%es are esigne to hol lists o$ simple strings. Cith a name attribute $or your uni<ue name $or this %olor.color.Working 4ith 2esources @ou %an.$onorifics. &e.%etColor:R. Ar. all you nee to o is a color elements to the resour%es $ile.array.

g. though.com Special Creative Commons BY-SA 3. Chere the value a$ter the hyphen is the . 0ormally. like a ire%tional pa or %li%k3CheelD • • • • 5he Cay An roi presently han les this is by having multiple resour%e ire%tories. oes not really have an orientationD #creen siBe* hoC many pi.. there$ore.xml an the #panish ones in res/values(es/strin%s. you Coul put your strings in a $ile name res/values/strin%s. #uppose.tCo3letter %o e $or the language you Cant. >ne obvious area %omes Cith string resour%es an ealing Cith internationaliKation &. is the tou%hs%reen set up to be use Cith a stylus or a $ingerD 7ey6oard* Chat keyboar oes the user have &HWIR5@. 5o support both Inglish an #panish. $or e.ifferent !olks >ne set o$ resour%es may not $it all situations Chere your appli%ation may be use . you Coul %reate tCo $ol ers. so you %an siKe your resour%es a%%or ingly &e. large versus small i%ons'D Touchscreen* oes the evi%e have a tou%hs%reenD .xml.-80' an lo%aliKation &L-00'.0 License Edition .ample.els oes the s%reen have. !utting strings all in one language Corks $ine N probably at least $or the eveloper N but only %overs one language. )ere are others* • #creen orientation* is the s%reen in a portrait orientationD Lan s%apeD . An roi Cill %hoose the proper $ile base on the user7s evi%e settings.Working 4ith 2esources . numeri%. either noC or as an optionD Ather input* oes the evi%e have some other $orm o$ input. res/values(en an res/values(es. 5hat is not the only s%enario Chere resour%es might nee to i$$er. neither'. (00 Subscribe to updates at http://commonsware.s the s%reen s<uare an . @our Inglish3language strings Coul go in res/values( en/strin%s. you Cant to support strings in both Inglish an #panish. $or a single3language setup. Cith the %riteria $or ea%h embe e in their names.#> 4?13.ifferent Strokes for .$ so.xml.

Working 4ith 2esources #eems easy. (or the purposes o$ this e. >ptions are %ase sensitive • • #o. (en' have a parti%ular or er o$ pre%e en%e. as you might Cant one layout $or portrait an small s%reens. 5his Cill alloC you to make the best use o$ the available s%reen Qreal estateQ. stylus'.. @ou %annot. su%h as* • 5he %on$iguration options &e. >n%e you get into these sorts o$ situations.. $or the s%enario es%ribe above. though.com Special Creative Commons BY-SA 3. $or e.0 License Edition . an they must appear in the ire%tory name in that or er.ample. Chi%h must pre%e e s%reen siKe. 5here %an only be one value o$ ea%h %on$iguration option %ategory per ire%tory. one layout $or larger s%reens in lan s%ape mo e. $ol er. 5his may %ome most $re<uently Cith layouts.g. in theory. Cithout any %o ing %hanges to your a%tivity using the layout. %onsi er portrait an s<uare s%reens to be the same N ea%h Cill re<uire its oCn name res/layout. rightD Where things start to get %ompli%ate is Chen you nee to use multiple isparate %riteria $or your resour%es.ample. s%reen orientation must pre%e e tou%hs%reen type.. all sorts o$ rules %ome into play. Ce Coul nee the $olloCing ire%tories* • • • • • • • • res/layout(port(fin%er res/layout(sJuare(fin%er res/layout(landscape(fin%er(SN@xNA@ res/layout(port(notouc$ res/layout(sJuare(notouc$ res/layout(landscape(notouc$(SN@xNA@ res/layout(port(stylus res/layout(sJuare(stylus (03 Subscribe to updates at http://commonsware. 5he An roi o%umentation outlines the spe%i$i% or er in Chi%h these options %an appear. an variations o$ ea%h $or $inger3input versus other types o$ input &keyboar .

(irst up. an the layout Cill be %hosen base on Chether the evi%e supports $inger input or not. ?. (or e. $or e. #o Ce %oul skate by Cith only the $olloCing %on$igurations* • • • • res/layout(landscape(fin%er(SN@xNA@ res/layout(landscape(SN@xNA@ res/layout(fin%er res/layout . (07 Subscribe to updates at http://commonsware. Also note that there is nothing preventing you $rom also having a ire%tory Cith the una orne base name &res/layout'. by e%o ing the rules An roi uses $or etermining Chi%h.ample.2=0. 0oC. An roi tosses out ones that are spe%i$i%ally invali . in %ase $uture e itions o$ the An roi runtime intro u%e other %on$iguration options you i not %onsi er N having a e$ault layout might make the i$$eren%e betCeen your appli%ation Corking or $ailing on that neC evi%e. i$ the s%reen siKe o$ the evi%e is ?20. sin%e they spe%i$i%ally %all $or some other siKe. Ce %an Q%heatQ a bit. is the QrightQ resour%e ire%tory to use* -. Ce only %are about $inger layouts being i$$erent than the other tCo. (inally.t. this is probably a goo i ea. #o. among a set o$ %an i ates.Working 4ith 2esources • res/layout(landscape(stylus(SN@xNA@ 0ote that $or some o$ these. Ce Coul theoreti%ally have to have separate ire%tories Cith i enti%al %ontents $or notouc$ an stylus.=80 s%reen siKe. it goes $rom le$t to right in the ire%tory name.ample. An roi %ounts the number o$ mat%hes $or ea%h $ol er. 2. the SN@xNA@ ire%tories Coul be roppe as %an i ates. .0 License Edition . 0e. the $irst tCo %an i ates Cill be skippe . an only pays attention to those Cith the most mat%hes.$ the evi%e is in portrait or s<uare mo e.com Special Creative Commons BY-SA 3. or oes not have a 4=0.n $a%t. An roi goes in the or er o$ pre%e en%e o$ the options N in other Cor s. the a%tual layout $iles Cill be i enti%al. but sin%e Ce %annot %ombine those tCo.

Cith the $inal etermination being on Chether the evi%e supports $inger input or not.0 License Edition .com Special Creative Commons BY-SA 3. one o$ the tCo lan s%ape 4=0. (09 Subscribe to updates at http://commonsware.=80 layouts Cill be %hosen. as they Coul be a QstrongerQ mat%h than the others.Working 4ith 2esources >therCise.

Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition .

. it is publi% omain. 8oogle. Moreover. this %hapter oes not have a $ull e.perien%e in other #HL3 base atabases. )oCever. #ymbian' an open sour%e proOe%ts &MoKilla. an +A/C might be too mu%h overhea $or a memory3limite evi%e like a phone. A%tivities Cill typi%ally a%%ess a atabase via a %ontent provi er or servi%e.ample. as it %ombines a %lean #HL inter$a%e Cith a very small memory $ootprint an e%ent spee .CHAPTER 1/ *anaging and )ccessing ocal .ample (3( Subscribe to updates at http://commonsware. it is $airly straight$orCar to use $or people Cith e. anyCay. (or An roi . #in%e #HLite uses a #HL inter$a%e. !)!. Lots o$ $irms &A obe.t o$ Corking on An roi . @ou Cill $in a $ull e. . so everyone %an use it. 5his %hapter Cill %over the basi%s o$ #HLite use in the %onte. !ython' all ship pro u%ts Cith #HLite.$ you Cant to learn more about #HLite an hoC to use it in other environment than An roi . so every An roi appli%ation %an %reate #HLite atabases. Apple. #HLite is Qbake intoQ the An roi runtime. As su%h. is not +A/C.0 License Edition . )en%e.com Special Creative Commons BY-SA 3. #un. a $ine book is 5he Ae$initive 8ui e to #HLite by Mi%hael >Cens.atabases #HLite is a very popular embe e atabase. An roi programmers have a i$$erent A!. its native A!.t by no means is a thorough %overage o$ #HLite as a Chole. to learn N the goo neCs being is that it is not that i$$i%ult.

) Fuick SF ite Primer #HLite./ an E2++ . %omplete Cith triggers. !ut a string in an . as the name suggests.. neste transa%tions.'. like S)+)C-. al. . #HLite has a $eC pla%es Chere it eviates $rom the #HL312 stan ar . an ata e$inition &CR)A-) -A6+)./S)R-. notably E. #to%k #HL statements.'. al. though. 5he biggest i$$eren%e $rom other #HL atabases you Cill en%ounter is probably the ata typing. transa%tions./-)0)R %olumnD #ure: 0o problem: .R). you get a $ull #HL system.n a ition../.0 License Edition .03. that is as $ar as it goes.i%e versaD Works too: #HLite re$ers to this as Qmani$est typingQ. While you %an spe%i$y the ata types $or %olumns in a CR)A-) -A6+) statement. like >ra%le.*anaging and )ccessing ocal . the datatype is a property of the value itself. 5he goo neCs is that #HLite is so spa%e3e$$i%ient that the An roi runtime %an in%lu e all o$ #HLite. not of the column in which the value is stored. S Lite thus allows the user to store any value of any datatype into any column regardless of the declared type of that column.com Special Creative Commons BY-SA 3. as es%ribe in the o%umentation* In manifest typing.2-)R =. et. an some $lavors o$ A+-)R -A6+). not some arbitrary subset to trim it oCn to siKe.$ you are use to Corking Cith a maOor atabase.atabases o$ a %ontent provi er that a%%esses a atabase in the /uil ing a Content !rovi er %hapter. no i$$erent than most #HL atabases. R.pe%t. Cork pretty mu%h as you might e.0/ M)F %onstraints. @ou %an put Chatever ata you Cant in Chatever %olumn you Cant. /eyon that. there are a han $ul o$ stan ar #HL $eatures not supporte in #HLite. an the like. ata manipulation &. .. you may look upon #HLite as being a QtoyQ atabase. !lease bear in min that >ra%le an (3% Subscribe to updates at http://commonsware.2-)R =. et. an Chile #HLite Cill use those as a hint. uses a iale%t o$ #HL $or <ueries &S)+)C-'.

When somebo y upgra es your appli%ation to a neC version.es. use @ An optional instan%e o$ a CursorEactory sub%lass that shoul be use in %onOun%tion Cith this atabase. Start at the Beginning 0o atabases are automati%ally supplie to you by An roi . 5o %reate a atabase. es%ribe later in this %hapter. Subscribe to updates at http://commonsware. then populate it Cith your oCn tables. Chi%h you %an use $or %reating tables an the like. @ou also get a ST+iteDatabase instan%e Chen you %all openDatabase:. you %an %ompare the version you Cant to use Cith the version o$ the atabase that is alrea y installe . an that you Cill not be seeing a $ull %opy o$ >ra%le on a phone any time real soon. Content1rovider. to a%%ess a atabase you alrea y %reate . or other Context sub%lass %an %all createDatabase:. %all is an instan%e o$ ST+iteDatabase..0 License Edition . 5hat Cill help your appli%ation $igure out Chat nee s to be %hange in the table stru%tures. in all likelihoo .com Special Creative Commons BY-SA 3. in e. .*anaging and )ccessing ocal . optionally. (3. %overe in greater etail in the se%tion on <uerying the atabase. an ata. 5his is %overe in greater etail in the %hapter on %reating a %ontent provi er. later in this %hapter • • • 5he version number is $or your oCn bookkeeping. your Activity. i$ your neC version uses a i$$erent atabase s%hema. 5he result o$ the createDatabase:. provi ing $our parameters* • 5he name o$ the atabase N any %lass in your appli%ation %an a%%ess this atabase un er this name &though nothing outsi e your appli%ation %an a%%ess it' An integer version number $or the atabase &see beloC' 5he se%urity mo e $or a%%essing this atabase N $or noC.$ you Cant to use #HLite. the CursorEactory use Chen <uerying the atabase. you have to %reate your oCn atabase.atabases #HLite are meant to solve i$$erent problems. 5his takes the name o$ the atabase an .

Oust use execST+:. Most likely. on the table.$ you Cish to get ri o$ the atabase entirely. Cith the atabase7s name. you might never rop your tables or in e. by name.*anaging and )ccessing ocal ./-)0)R. you Cill nee to %all execST+:. but i$ you o.5 db.0 License Edition . or other Context sub%lass %an %all deleteDatabase:.#. on your provi ing the AAL statement you Cish to apply against the atabase.g. .atabases When you are one Cith the atabase &e..$ you o not %hange your table s%hemas..es. $or you on your primary key %olumn.D .es Chen you $irst %reate the atabase. on the #HLiteAatabase to release your %onne%tion.execS. #o.e.1 . so the se%on statement a s another in e./-)0)R 1R./D)U wid%ets6y/ame./ wid%ets :name. or possibly Chen the atabase nee s upgra ing to a%%ommo ate a neC release o$ your appli%ation.D that is an auto3in%remente integer &i.1 -A6+) statements as nee e . (3$ Subscribe to updates at http://commonsware. plus tCo ata %olumns* name &te. #HLite Cill assign the value $or you Chen you insert roCs'. simply %all close:. #HLite Cill automati%ally %reate an in e.execS.. Content1rovider. Setting the Table ST+iteDatabase. you %an* db. .#.es.L:#CR)A-) . your Activity. *akinA . name Ci gets.MARF M)F A2-. you probably Cant to put some ata in them an su%h. to invoke DR. $or e.ample.t' an inventory &integer'. your a%tivity is being %lose '.ata 8iven that you have a atabase an one or more tables.L:#CR)A-) -A6+) wid%ets #B #:. /arring a atabase error. @ou have tCo maOor approa%hes $or oing this. this metho returns nothing. Cith a primary key %olumn name .com Special Creative Commons BY-SA 3./D)U an DR. you Cill %reate tables an in e. (or %reating your tables an in e.dx #B #./CR)M)/-G #B #name -)U-G inventory .5 5his Cill %reate a table.

an a Content7alues Cith the initial values you Cant put into this roC./S)R. 5hese are Qbuil erQ sorts o$ metho s. metho Corks $or any #HL that oes not return results. in that the break oCn the #HL statements into is%rete %hunks. you have %etAs.. 5he update:. $or e. to a%%omplish some en s.0 License Edition .execS..5 @our alternative is to use the insert:./-. (or e.. an an optional list o$ parameters to $ill into the C3)R) %lause. 5he insert:. an optional C3)R) %lause. D)+)-). update:. 5hese metho s make use o$ Content7alues obOe%ts.nte%er:. albeit one that has a itional metho s $or Corking Cith #HLite types. et%. 5he C3)R) %lause an parameter list Corks akin to the positional #HL parameters you may be use to $rom other #HL A!. metho takes the name o$ the table.L:#. metho s on the ST+iteDatabase obOe%t. to retrieve a value by its key. so it %an han le . Oust $ine. an delete:.. then take those %hunks as parameters./S)R-..ample* // replacements is a Content7alues instance Strin%OP parms"new Strin%OP 8#snicklefrit'#<5 db. Oust like you i $or %reating the tables. a Content7alues representing the %olumns an repla%ement values to use./S)R.update:#wid%ets#G replacementsG #name">#G parms.ample. 5he execST+:. 5he Qnull %olumn ha%kQ is $or the %ase Chere the Content7alues instan%e is empty N the %olumn name as the Qnull %olumn ha%kQ Cill be e.atabases @ou %an alCays use execST+:..5 (3/ Subscribe to updates at http://commonsware. only repla%es %olumns Cith $i. you may nee to use execST+:. versus ones %ompute base on other in$ormation.e values. (or e. %etAsStrin%:. an so $orth. Chi%h implement a Map3 es<ue inter$a%e. metho takes the name o$ the table.com Special Creative Commons BY-SA 3.pli%itly assigne the value /2++ in the #HL . #in%e update:. to repla%e any embe e <uestion marks &>'.ample* db. in a ition to %et:.#.s. the name o$ one %olumn as the Qnull %olumn ha%kQ.#B #7A+2)S :ZSprocketZG L.. 21DA-).statement generate by insert:.*anaging and )ccessing ocal . wid%ets :nameG inventory. #o.

uery:#S)+)C. 5he S)+)C.atabases 5he delete:. #o.0 License Edition . to invoke a S)+)C. to buil up a <uery $rom its %omponent parts Con$oun ing matters $urther is the ST+iteTuery6uilder %lass an the issue o$ %ursors an %ursor $a%tories. What 'oes )round6 Comes )round As Cith . taking the name o$ the table.. (or e. this is a very straight$orCar Cay to use them. an D)+)-). it gets %ompli%ate i$ parts o$ the <uery are ynami%. an the %orrespon ing parameters to $ill into the C3)R) %lause. at least in terms o$ the A!... i$ the set o$ %olumns you nee to retrieve is not knoCn at %ompile time. %omes in. the optional C3)R) %lause. 21DA-). (30 Subscribe to updates at http://commonsware. Ce Cin up Cith* Strin%OP parms"8#snicklefrit'#<5 Cursor result" db.ample.. @ou %an use rawTuery:. #imply %all it Cith your #HL S)+)C. )oCever. or 2. Let7s take all o$ this one pie%e at a time..com Special Creative Commons BY-SA 3.*anaging and )ccessing ocal .5 ./S)R-.$ your <ueries are pretty mu%h Qbake intoQ your appli%ation. R # .M wid%ets C3)R) name">#G parms. is rawTuery:. metho Corks akin to update:.raw.ueries 5he simplest solution. puttering aroun %on%atenating %olumn names into a %omma3 elimite list %an be annoying.Chi%h is Chere Juery:.. you have tCo main options $or retrieving ata $rom a #HLite atabase using S)+)C-* -.statement ire%tly. beyon Chat positional parameters %an really han le..statement.statement %an in%lu e positional parametersP the array o$ these $orms your se%on parameter to rawTuery:. @ou %an use Juery:.DGinventory ER.

our previous snippet %onverts into* Strin%OP columns"8#. (or e.-uery:#wid%ets#G columnsG #name">#G parmsG nullG nullG null.0 License Edition . implementation is to %reate a ST+iteTuery6uilder. metho takes the is%rete pie%es o$ a #ILIC5 statement an buil s the <uery $rom them. the ST+iteTuery6uilder inter$a%e ovetails ni%ely Cith the Content1rovider inter$a%e $or e..ample.RD)R 6F %lause. here is a snippet o$ %o e $rom a %ontent provi er using ST+iteTuery6uilder* (33 Subscribe to updates at http://commonsware. More importantly. are* • • • • • • 5he name o$ the table to <uery against 5he list o$ %olumns to retrieve 5he C3)R) %lause.e%ute' the $ull <uery %ombining the e$aults Cith Chat is provi e to the %ontent provi er on the <uery re<uest. optionally in%lu ing positional parameters 5he list o$ values to substitute in $or those positional parameters 5he 0R.D#G #inventory#<5 Strin%OP parms"8#snicklefrit'#<5 Cursor result"db. 5he pie%es.com Special Creative Commons BY-SA 3.21 6F %lause. o$ %ourse'.atabases Re!ul r . then alloC it to buil up &an optionally e. parti%ularly $or nasty <ueries involving things like the union o$ multiple sub3<uery results.*anaging and )ccessing ocal . $ill in some e$aults. in or er that they appear as parameters to Juery:. i$ any 5he . )en%e.e%uting <ueries.5 Buildin! #ith Builders @et another option is to use ST+iteTuery6uilder. Chi%h o$$ers mu%h ri%her <uery3buil ing options. #o. a %ommon pattern $or your %ontent provi er7s Juery:.ueries 5he Juery:. i$ any 5hese %an be null Chen they are not nee e &e.%ept the table name.

setTa!les:getTa!le%ame:.get&athSegments:.Juery:dbG projectionG selectionG selectionAr%sG nullG nullG order6y. %all &appendC$ere:.e%ute the <uery ire%tly.e%ute ourselves.' (inally..B#"# B url.set&ro/ection'ap:getDefault&ro/ection:.is+mpty:sort.0 License Edition .-uery:dbG projectionG selectionG selectionAr%sG nullG nullG order6y. to have it generate an return the #HL S)+)Cstatement Ce nee e .*anaging and )ccessing ocal . 8 order6y"getDefaultSortOrder:. &Jb.ueryBuilder:. Ce see* • • • A ST+iteTuery6uilder is %onstru%te .'..get:?.com Special Creative Commons BY-SA 3. so some o$ this you Cill have to take on $aith until then..set%otification)ri:getContext:. Chi%h Ce %oul then e.5 < else 8 Jb.plaine in greater etail later in the book.5 Content provi ers are e.5 if :isCollection)ri:url. or is given a pie%e o$ a C3)R) %lause to i enti$y a parti%ular roC in the table by an i enti$ier e..G url.' .tra%te $rom the 2ri supplie to the Juery:.5 < Strin% order6y5 if :-ext2tils. Ce %oul have %alle buildTuery:...append*here:getIdColumn%ame:.5 c..nstea o$ having the ST+iteTuery6uilder e.5 Jb.t is tol the table to use $or the <uery &set-ables:%et-able/ame:.. )ere.t is either tol the e$ault set o$ %olumns to return &set1rojectionMap:.5 < else 8 order6y"sort5 < Cursor c"Jb. (37 Subscribe to updates at http://commonsware.atabases ST+iteTuery6uilder Jb"new S.e%ute the <uery. it is tol to e.Lite.' • . 8 Jb. blen ing the pre3set values Cith those supplie on the %all to Juery:.getContent$esol er:.

e%ute the <uery that %reate the %ursor via reJuery:.terate over the roCs via first:. • • (or e. an get values $or the %urrent roC $or a given %olumn via metho s like %etStrin%:. %onvert those into %olumn numbers via %etColumn. you get a Cursor ba%k. @ou o this by* (39 Subscribe to updates at http://commonsware. %et.5 Strin% name"result.0 License Edition .getInt:@.'.*anaging and )ccessing ocal .uery:#S)+)C.next:. Re3e. 8 int id"result..DG nameG inventory ER. 5his means not only %an you rea ata using the %ursor. an isAfter+ast:..is#fterLast:..raw.getString:?.5 int inventory"result. Release the %ursor7s resour%es via close:.. an in some other situations. With the %ursor.5 w$ile :Wresult. ..5 // do somet$in% useful wit$ t$ese result. (in out the names o$ the %olumns via %etColumn/ames:.or the S $e o.e%ute the <uery. a %on%ept use in many atabase systems.5 Ch n!e .atabases +sin! Cursors 0o matter hoC you e. you %an* • • • (in out hoC many roCs are in the result set via count:. the %ursor Cill support up ates &support2pdates:. 5his is the An roi U#HLite e ition o$ the atabase %ursor...5 < result.getInt:H.M wid%ets#. Ch n!e (or a simple S)+)C-. next:.com Special Creative Commons BY-SA 3.ndex:. et%.ample. but you %an mo i$y the ata an %ommit those %hanges ba%k to the atabase.close:..nt:. here Ce iterate over the Ci gets table entries $rom the previous snippets* Cursor result" db.

$ you are use to eveloping $or other atabases. provi ing it the path to your atabase $ile. .n those %ases. @our atabase $ile %an be $oun at* /data/data/your.. to re$resh the %ursor base on the results o$ your %hanges. (in ing an implementing a vali use $or this $a%ility is le$t as an e.er%ise $or the rea er. Committing those %hanges ba%k to the atabase via commit2pdates:. an updateStrin%:.packa%e/databases/your(db(name. . you shoul close:. #u$$i%e it to say that you shoul not nee to %reate your oCn %ursor %lasses mu%h. the %ursor Chen one. you have tCo main options $or this. that take a CursorEactory instan%e as a parameter.e%ute sJliteI.*anaging and )ccessing ocal .nt:. i$ you Cant to %ontinue using the %ursor • • An .db (7. i$ at all. you %an use $lavors o$ Juery:.com Special Creative Commons BY-SA 3.pe%t. >n%e you are in the emulator7s shell. Subscribe to updates at http://commonsware. an rawTuery:.nvoking reJuery:.app.. in or inary An roi evelopment. % $in! <our 0#n Cursors 5here may be %ir%umstan%es in Chi%h you Cant to use your oCn Cursor sub%lass. Oust e. is responsible $or %reating neC %ursors via its newCursor:. 5he $a%tory. rather than the sto%k implementation provi e by An roi . or eleting the %urrent roC via deleteRow:. you are also probably use to having tools to inspe%t an manipulate the %ontents o$ the atabase. . beyon merely the atabase7s A!. With An roi 7s emulator. o$ %ourse.ata6 Every4here . implementation. the emulator bun les in the sJliteI %onsole program an makes it available $rom the adb s$ell %omman .0 License Edition . as one might e. (irst.ata6 .atabases • "p ating values $or parti%ular %olumns in the %urrent roC via metho s like update.

as it Corks a%ross all plat$orms. you are Cel%ome to use it. 5o get the atabase o$$ the evi%e. then use a #HLite3aCare %lient program to putter aroun .*anaging and )ccessing ocal . 5he sJliteI program Corks. com. Chi%h takes the lo%al path to the atabase an the on3 evi%e estination as parameters. you %an alCays %opy the #HLite atabase o$$ the evi%e onto your evelopment ma%hine.com Special Creative Commons BY-SA 3.$ you pre$er something a little bit $rien lier. you Cill nee to trans$er the atabase ba%k over.AI'. >ne o$ the most3a%%essible #HLite %lients is the #HLite Manager e..0 License Edition .commonsware.atabases )ere your. 0ote. though.g. as supplie to createDatabase:.app. Chi%h takes the path to the on3 evi%e atabase an the lo%al estination as parameters. that you are Corking o$$ a %opy o$ the atabaseP i$ you Cant your %hanges to go ba%k to the evi%e. you %an use the adb pull %omman &or the e<uivalent in your .< the SF ite *anager !irefox extension (7( Subscribe to updates at http://commonsware. use adb pus$.packa%e is the +ava pa%kage $or your appli%ation &e.android' an your(db(name is the name o$ your atabase.tension $or (ire$o. an i$ you are use to poking aroun your tables using a %onsole inter$a%e. !igure /. .. 5o store a mo i$ie atabase on the evi%e..

com Special Creative Commons BY-SA 3.*anaging and )ccessing ocal .atabases @ou %an $in oKens o$ others on the #HLite Web site. (7% Subscribe to updates at http://commonsware.0 License Edition .

5here are a number o$ $a%tors to %onsi er. . )ere. i$ not more.com Special Creative Commons BY-SA 3. 5hat being sai . Cill Cork Cell Cith An roi . thir 3party libraries than any other mo ern programming language. in%lu ing* • .0 License Edition .M at its heart is not pre%isely +ava. 5his %hapter e. $or the ones you %an get Corking Cith An roi 7s $lavor o$ +ava.isten%e o$ +ava A!.CHAPTER 12 everaging Cava ibraries +ava has as many. Qthir 3party librariesQ re$er to the innumerable +ARs that you %an in%lu e in a server or esktop +ava appli%ation N the things that the +ava #AFs themselves o not provi e.n the %ase o$ An roi .xpected Platform AP%s* Aoes the %o e assume a neCer +.plains Chat it Cill take $or you to leverage su%h libraries an the limitations on An roi 7s support $or arbitrary thir 3party %o e. o$ %ourse. oes the %o e assume the e. an Chat it provi es in its #AF is not pre%isely the same as any tra itional +ava #AF. many +ava thir 3party libraries still provi e %apabilities that An roi la%ks natively an there$ore may be o$ use to you in your proOe%t.M than the one An roi is base onD >r.s that ship Cith +2#I but not Cith An roi . su%h as #CingD (7. The +uter imits 0ot all available +ava %o e. the Aalvik . Subscribe to updates at http://commonsware.

$ you %hoose to use their sour%e %o e. that you %an Crap your oCn inter$a%e aroun D • • >ne tri%k $or a ressing some o$ these %on%erns is to use open sour%e +ava %o e.isting +AR. all you nee to o is %opy it into your oCn sour%e tree &un er src/ in your proOe%t'. i$ you7re only using -0J o$ the thir 3party library. or at least removing the unne%essary %lasses $rom the +AR. on the other han . parti%ularly Chen pre3pa%kage as +ARs. . an a%tually Cork Cith the %o e to make it more An roi 3$rien ly.xml Ant s%ript.AI an are relying upon the build. you Cill nee to make some %hanges. that7s a matter o$ telling it to re$eren%e the +AR. or use pre3pa%kage +ARs. An roi . . so it %an sit alongsi e your e.ample.isting +ava %o e esigne $or use on esktops or servers nee not Corry too mu%h about on3 isk siKe. is short on both. . then let the %ompiler per$orm its magi%. maybe it7s CorthChile to re%ompile the subset o$ the proOe%t to be only Chat you nee . "sing thir 3party +ava %o e. )ere7s a pattern that Corks* (7$ Subscribe to updates at http://commonsware. in that you get %ompiler help to make sure you7re not is%ar ing some essential pie%e o$ %o e.0 License Edition .$ you are using an . or. may balloon the siKe o$ your appli%ation.AI. you are not using an .com Special Creative Commons BY-SA 3. %nterface* Aoes the +ava %o e assume a %onsole inter$a%eD >r is it a pure A!. though it may be more te ious to o.tent. . (or e.$. perhaps one $or Chi%h you o not have the sour%e %o e.everaging Cava ibraries • #iBe* I.$ you %hoose to use an e. o$ %ourse. to some e. even in3 RAM siKe. Performance* Aoes the +ava %o e e$$e%tively assume a mu%h more poCer$ul C!" than Chat you may $in on many An roi evi%esD +ust be%ause a esktop %an run it Cithout issue oesn7t mean your average mobile phone Cill han le it Cell. 5he $ormer approa%h is sa$er. you Cill nee to tea%h your buil %hain hoC to use the +AR. )nts and Cars @ou have tCo %hoi%es $or integrating thir 3party %o e into your proOe%t* use sour%e %o e.isting %o e.

so any +avaMail re$eren%es in the Mail/uKK %o e %an be %orre%tly resolve . pointing it to your neC lib/ ire%tory ?.everaging Cava ibraries -.jar#/& </exec& </tar%et& Mail/uKK.xml s%ript.dex files.java files into .N. ((& <tar%et name"#dex# depends"#compile#& <exec executable"#\8dx<# failonerror"#true#& <ar% value"#(=UmxIANM# /& <ar% value"#((dex# /& <ar% value"#((output"\8basedir</\8intermediate(dex<# /& <ar% value"#((locals"full# /& <ar% value"#((positions"lines# /& <ar% pat$"#\8basedir</\8outdir(classes<# /& <ar% pat$"#\8basedir</lib/activation(?.?. pointing it to the spe%i$i% +ARs to translate to Aalvik instru%tions an pa%kage (or e.jar#/& <ar% pat$"#\8basedir</lib/mail(?.s an nee s tCo +avaMail +ARs* mail(?. et%. 5o a%%omplish that en . 5hen.?. to your 2.0 License Edition .jar an activation(?.# destdir"#\8outdir(classes<# bootclasspat$"#\8android(jar<#& <classpat$& <fileset dir"#lib#& <include name"#QQ/Q. eals Cith email. those +ARs (7/ Subscribe to updates at http://commonsware. A a classpat$ element to the javac task in the compile target o$ your build.L# debu%"#true# extdirs"## srcdir"#. as a peer o$ src/.jar.xml $or Mail6u''. ((& <tar%et name"#compile# depends"#dirsG resource(srcG aidl#& <javac encodin%"#ascii# tar%et"#?. as the name suggests. Copy the thir 3party +AR&s' into a lib/ ire%tory you a proOe%t. Mail/uKK leverages the +avaMail A!.amine in greater etail in the %hapters on servi%es* <W(( Compile t$is projectZs . A neC ar% elements to your exec task in the dex target o$ the build. a proOe%t Ce Cill e.class files into .com Special Creative Commons BY-SA 3.jar#/& </fileset& </classpat$& </javac& </tar%et& <W(( Convert t$is projectZs . the classpat$ tells javac to link against those +ARs.xml s%ript.N.class files. With both o$ those in the lib/ ire%tory.ample. here are the tCo a$orementione Ant tasks $rom the build. bin/.

As note above. 5his Coul n7t ne%essarily be is%overe at %ompile time.M simply oesn7t o$$er.%eption. using +ARs %an make your proOe%t portly N Mail/uKK is about 2B0F/ thanks to the +avaMail %lasses.com Special Creative Commons BY-SA 3. along Cith the Mail/uKK %ompile %lasses. Without this step. it Con7t $in the +avaMail %lasses at runtime an Cill $ail Cith an e. it is entirely possible that +avaMail Coul re<uire $eatures in +ava that the Aalvik . so your testing Cill nee to ensure that you e.M instru%tions. in the task that invokes the dex tool to %onvert the +ava %o e into Aalvik .. even though your %o e may %ompile. (70 Subscribe to updates at http://commonsware. though.0 License Edition . >$ %ourse.er%ise all relevant uses o$ the thir 3party A!.everaging Cava ibraries are liste . so you knoC that it Cill run Cithout in%i ent.

su%h as the integrate WebFit broCser %omponent Ce saC in an earlier %hapter.nternet a%%ess. QRI#53 (73 Subscribe to updates at http://commonsware. . @ou %an either layer a #>A!UEML3R!C layer atop this library.nternet $rom their An roi phone. most people N or at least those Cith a ata plan or Wi(i a%%ess N Cill be able to get to the .CHAPTER &4 Communicating via the 8nternet 5he e. ?8. or possibly something else entirely. it oes have the Apa%he +akarta Commons )ttpClient library bake in. %ellular ata servi%es &IA8I. i$ not all. in betCeen. Regar less. as busy %o ers shoul be trying to reuse e.com Special Creative Commons BY-SA 3. An roi evi%es Cill have built3in .nternet3a%%ess A!.0 License Edition . 5he emphasis o$ this book is on the higher3level $orms o$ a%%ess* the WebFit %omponent an .'. you %an leverage A!. )oCever. the An roi plat$orm gives evelopers a Ci e range o$ Cays to make use o$ this . you %an rop all the Cay oCn to using raC so%kets. 5hat %oul be Wi(i. 2EST and 2elaxation An roi oes not have built3in #>A! or EML3R!C %lient A!. EM!!. >r.s. et%.s. #ome o$$er high3level a%%ess.s N both on3 evi%e an $rom ?r 3party +ARs N that give you a%%ess to spe%i$i% proto%ols* )55!. an so on.isting %omponents versus rolling one7s oCn on3the3Cire proto%ol Cherever possible.pe%tation is that most. (or the purposes o$ this book.nternet a%%ess. or use it QstraightQ $or a%%essing RI#53style Web servi%es.$ you Cant. 0ot surprisingly. #M5!.

5hose re<uests are bun le up into 3ttpMet$od instan%es. et%. 0etMet$od $or )55! 0). 5he %lient obOe%t han les all )55! re<uests upon your behal$.' as responsesQ.g. to rop the )55! %onne%tion.via 1ostMet$od'. $orm values i$ you are oing an )55! 1. %lose the . +#>0. HTTP 0per tions vi Ap che Commons 5he $irst step to using )ttpClient is.pansive tutorials. a Strin%. . you Cill also be given the bo y o$ the response.* this probably only Corks in the "#'. to %reate an 3ttpClient obOe%t..0 License Edition . give you an )55! response %o e &e. or an .er%ise $or the rea er. then invoke releaseConnection:.. let7s take a look at the Ceat$er sample proOe%t. not surprisingly. Chi%h you %an obtain as a byte array. @ou %reate an 3ttpMet$od sub%lass instan%e. Set(Cookie'.nputStream &i$ that7s hoC you got the response bo y'. Cith i$$erent 3ttpMet$od sub%lasses $or ea%h i$$erent )55! verb &e. When you are one Cith the re<uest. 5he re<uest Cill.. Chi%h is poure into a CebMit Ci get $or isplay.n many %ases.g. Ce7ll %over the basi%s. Also. (AHs. 5hat ata is %onverte into an )5ML page. H@@ $or >F' an various )55! hea ers &e.g.re<uests'. (or e. sin%e this sample is relatively long.nputStream $or later pro%essing. 5his implements an a%tivity that retrieves Ceather ata $or your %urrent lo%ation $rom the 0ational Weather #ervi%e &>AT. Chile %he%king the Ceather. then pass the metho to the %lient to a%tually make the )55! re<uest.Communicating via the 8nternet style Web servi%esQ is e$ine as Qsimple )55! re<uests $or or inary "RLs over the $ull range o$ )55! verbs.com Special Creative Commons BY-SA 3. on the metho obOe%t.. Ce Cill only shoC (77 Subscribe to updates at http://commonsware. at minimum. More e. an )>W5>s %an be $oun at the )ttpClient Web site. $ill in the "RL to retrieve an other %on$iguration ata &e.g.S. )ere.ample. Rebuil ing this emo using a +ist7iew is le$t as an e. Cith $ormatte payloa s &EML.

(or noC. 8 super. 8 -oast .releaseConnection:.G H@@@.getLongitude:. .5 < < catc$ :-$rowable t.Communicating via the 8nternet relevant pie%es o$ the +ava %o e here in this %hapter. Chi%h uses An roi 7s built3in lo%ation servi%es N more on this in a later %hapter. though you %an alCays oCnloa the $ull sour%e $rom the CommonsWare Web site.5 browser.5 < < (irst.show:. metho s that return the latitu e an longitu e o$ the evi%e7s position. 8 -oast .G #text/$tml#G #2-E(A#.5 Strin% url"Strin%. respe%tively.5 < finally 8 met$od.G loc.makeText:t$isG #ReJuest failed! #Bmet$od.execute'ethod:met$od. an pour in the latitu e an longitu e at runtime.format:formatG loc.getStatusLine:..makeText:t$isG #ReJuest failed! #Bt.get$esponseBody#sStream:. We retrieve the 0ational Weather #ervi%e ata every time the a%tivity pops ba%k to the $oregroun by implementing onResume:.5 < else 8 !uild"orecasts:met$od.5 0etMet$od met$od"new Get'ethod:url.G H@@@.com Special Creative Commons BY-SA 3.verride public void on$esume:.getLatitude:.5 if :statusCodeW"3ttpStatus. all you nee to knoC is that +ocation sports %et+atitude:.SC*. metho .5 try 8 int statusCode"client. .toString:. an %et+on%itude:.. in the a%tivity* 9. Ce retrieve our lo%ation using a private %et+ocation:.show:. 8iven our 3ttpClient (79 Subscribe to updates at http://commonsware.5 +ocation loc"getLocation:.loadData:generate&age:.0 License Edition .on$esume:. We hol the "RL to the 0ational Weather #ervi%e EML in a string resour%e.M.

a #AE parser &or%. .nputStream in.e%ute that metho . +#>0. P rsin! Responses 5he response you get Cill be $ormatte using some system N )5ML.Communicating via the 8nternet instan%e %reate in onCreate:.tra%t the $ore%ast time. Ce buil the $ore%ast )5ML page &see beloC' an pour that into the CebMit Ci get. to han le other $ormats. Ce populate a 0etMet$od Cith that %ustomiKe "RL.5 Eorecast forecast"new "orecast:..json' • @ou are also Cel%ome to use thir 3party +ava %o e.0 License Edition .5 Document doc"builder. an i%on &in i%ating sky %on itions an pre%ipitation' an generate an )5ML page $rom it. or i$ the 3ttpClient bloCs up Cith an e.n the %ase o$ the Ceat$erDemo. Chatever. . Subscribe to updates at http://commonsware. .get+lementsByTag%ame:#start(valid(time#. .$ Ce get H@@ as the result %o e.item:i. Ce nee to e.xml. t$rows )xception 8 Document6uilder builder"Document6uilderEactory . 5he use o$ thir 3party +ava %o e is is%usse in a separate %hapter.times. then e. su%h as a e i%ate R##UAtom parser $or a $ee rea er. metho * void !uild"orecasts:. Ce use the W?C A>M parser in our buildEorecasts:.dom'.parse:inG null.getLength:. EML.newInstance:. an the EML pull parser is%usse in the %hapter on resour%es A +#>0 parser &or%.5 /ode+ist times"doc. be$ore eventually releasing our )55! %onne%tion $or this re<uest.%eption. (or Ceat$erDemo. An roi in%lu es* • 5hree EML parsers* the tra itional W?C A>M &or%.$ Ce get some other response ba%k. . Chere possible. to pi%k out Chat in$ormation you nee an o something use$ul Cith it.sax'.newDocumentBuilder:. 8 )lement time":)lement.5 (9.t is up to you. o$ %ourse.5 for :int i"@5i<times. temperature.com Special Creative Commons BY-SA 3. Ce provi e that error as a -oast.5iBB.wIc.

.5 5he 0ational Weather #ervi%e EML $ormat is.add:forecast.temps. value $or the temperature.5 Eorecast forecast"forecasts. an icon(link $or the i%on "RL' are all uni<ue Cithin the o%ument.5 (9( Subscribe to updates at http://commonsware.Communicating via the 8nternet < forecasts..close:.setIcon:icon. 8 Strin%6uffer bufResult"new StringBuffer:#<$tml&<body&<table&#.5 < /ode+ist icons"doc.get+lementsByTag%ame:#icon(link#.icons.get"irstChild:. 8 )lement temp":)lement.setTime:time.get%odeValue:. Ce s%an $or the start(valid(time elements an populate a set o$ Eorecast mo els using those start times. the %enerate1a%e:..5iBB..com Special Creative Commons BY-SA 3.5iBB. relying heavily on se<uential position in lists versus the more obOe%t3oriente style you $in in $ormats like R## or Atom.nputStream an is $e into the A>M parser.5 forecast.n turn..get:i.5 bufResult..item:i.get+lementsByTag%ame:#value#.get%odeValue:..getLength:.5 in.0 License Edition .5 Eorecast forecast"forecasts. 5hat being sai . 5he )5ML %omes in as an .5 forecast. 5hen.getLength:... taking a vantage o$ the $a%t that the elements Ce Cant &start(valid(time $or the $ore%ast time. metho %reates a ru imentary )5ML table Cith the $ore%asts* Strin% generate&age:.get"irstChild:.%uriously stru%ture .5 < < forecast. Ce $in the temperature value elements an icon(link "RLs an $ill those in to the Eorecast obOe%ts.get"irstChild:.get:i.5 for :int i"@5i<icons.get%odeValue:.item:i. 8 )lement icon":)lement.append:#<tr&<t$ widt$"4#L@[4#&-ime</t$&#B #<t$&-emperature</t$&<t$&Eorecast</t$&</tr&#.5 for :int i"@5i<temps. Ce %an take a $eC liberties an simpli$y the parsing someChat.. (rom there.5 /ode+ist temps"doc.setTemp:new Integer:temp.

emo sample application Stu.getIcon:.append:forecast.5 bufResult.getTemp:.append:forecast.5 5he result looks like this* !igure /(< The Weather. Mostly. this is be%ause you nee to e%i e hoC to han le ##L %erti$i%ate presentation N o you blin ly a%%ept all %erti$i%ates.5 bufResult.append:forecast. bear in min that the e$ault )ttpClient setup oes not in%lu e ##L support. To Consider .append:#<tr&<td ali%n"4#center4#&#.append:#</td&<td&<im% src"4##.append:#4#&</td&</tr&#.5 bufResult.append:#</table&</body&</$tml&#.com Special Creative Commons BY-SA 3.0 License Edition . 8 bufResult.5 bufResult.5 < return:bufResult.5 < bufResult..append:#</td&<td ali%n"4#center4#&#.$ you nee to use ##L..toString:. even sel$3signe or e...5 bufResult.pire onesD >r o you Cant to ask the user i$ they (9% Subscribe to updates at http://commonsware.getTime:.5 bufResult..Communicating via the 8nternet for :Eorecast forecast ! forecasts.

$irst mentione in the pre%e ing %hapter. . Iventually. Ce %an still use A!. )ttpClient. like +avaMail.As.s like +avaMail. though.n the meantime. an hol onto the . esigne to monitor an email a%%ount $or neC messages. An roi 3style evi%es Cill e. is esigne $or single3threa e use. Case in point is the Mail6u'' proOe%t. Subscribe to updates at http://commonsware. but you Cill nee to either roll your oCn #M5!. there are %aveats to going this route. you %an rea ily set up )ttpClient to support multiple threa s N again. memory. grab the messages. $o%use on An roi 3style eployments. so long as Ce live Cith the limitations. eventually. Ivery time Ce %he%k $or neC messages.tra%t the Messa%e(.As is missing any $rom the Oust3retreive set o$ . an it shoCs o$$ integrating +avaMail ni%ely. (or the purposes o$ Mail/uKK. plus the use o$ servi%es.MA! on your An roi evi%e.Communicating via the 8nternet really Cant to use some strange %erti$i%atesD 5he )ttpClient Web site has instru%tions $or a ing ##L support Cith various %erti$i%ate poli%ies to your proOe%t. su%h as bloating the siKe o$ your appli%ation. 5his isn7t a $ull email %lient.0 License Edition . by e$ault. . or use one $rom a thir 3party. though. Ce see i$ the last set o$ message . !>!?. As es%ribe in the %hapter on integrating thir 3party +ava %o e. Ce7ll $o%us on the +avaMail si e.n this %hapter. Email over Cava An roi has no built3in $a%ility to sen ing or re%eiving emails. the )ttpClient Web site has the instru%tions. Chat Ce Cant is to %onne%t to a mail server. or .$ you Cill be using )ttpClient $rom a servi%e or some other pla%e Chere multiple threa s might be an issue. Ce have a neC (9. 5his appli%ation %ombines an a%tivity an a servi%e. e.As N i$ so.com Special Creative Commons BY-SA 3.MA! %lient %o e.d hea ers. An . o$ %ourse.pan their storage. an C!" %apa%ities. Qlean an meanQ e itions o$ these libraries Cill spring up. #imilarly. but it is a $eature you might $in in $ull email %lient. $or a%%essing !>!? an . . 5his oesn7t pre%lu e you $rom oing so yoursel$. 5his is not meant to be a thorough +avaMail tutorial.

R)AD*. 8 (9$ Subscribe to updates at http://commonsware..5 < private static Strin%OP get'essageIds:Strin% typeG Strin% serverG Strin% userG Strin% pw.android.get"older:#.nternet %onne%tion.getStore:type..mail.service5 import import import import import import java.mail. that assumes a %onstant .Store5 public class MailClient 8 public static Strin%OP get&O&0'essageIds:Strin% serverG Strin% userG Strin% pw.5 Store store"session. While Ce %oul use +avaMail7s Messa%eCount+istener to more ire%tly ete%t neC messages. t$rows Messa%in%)xception 8 return:get'essageIds:#popI#G serverG userG pw.U#.MA! an !>!? logi% is en%apsulate in the MailClient %lass* packa%e com.getDefaultInstance:System.Messa%in%)xception5 javax.Communicating via the 8nternet message an %an pop up a QneC mail:Q 0oti$i%ation./+F.Session5 javax.connect:serverG userG pw.com Special Creative Commons BY-SA 3.mail./6.. t$rows Messa%in%)xception 8 return:get'essageIds:#imap#G serverG userG pw.len%t$5iBB.0 License Edition .5 result"new Strin%Oms%s.get&roperties:.5 < public static Strin%OP getI'#&'essageIds:Strin% serverG Strin% userG Strin% pw.5 store.mail.get'essages:.commonsware.Messa%e5 javax.len%t$P5 for :int i"@5i<ms%s. it shoul han le a greater range o$ real3Corl situations.Eolder5 javax. t$rows Messa%in%)xception 8 Strin%OP result"null5 Session session"Session. While this implementation is e%i e ly more %lunky.security.5 try 8 Eolder folder"store.5 try 8 Messa%eOP ms%s"folder.mail.open:Eolder. an that7s $ar $rom assure Cith a mobile evi%e.5 folder. 5he .Security5 javax.

Close the $ol er an e.close:false. server.d#.U $or neC messages =.1IMessa%e.MA1Messa%e. an %et.get(eader:#Messa%e(.. pouring the results into a Strin%OP Chi%h is returne to the overall %aller 2. or in %ase an (9/ Subscribe to updates at http://commonsware.ds:. 8et the messages in the $ol er 4. so Chile the publi% A!. stati% metho .close:. an passCor as parameters. 8et a Session 2. Chi%h takes the type &!>!? or .5 < return:result.Communicating via the 8nternet Strin%OP $eaders"ms%sOiP. . i$ any.ds:.5 if :$eaders""null./6.ds:. >pen the Eolder $or rea operations B.d hea er. 8 resultOiP"null5 < else 8 resultOiP"$eadersO@P5 < < < finally 8 folder.5 < < +avaMail oes a ni%e Oob o$ abstra%ting out the i$$eren%es betCeen the proto%ols.MA!'.s are %et1. 8et a Store o$ the spe%i$i% type an %onne%t to the server ?. typi%ally . user. 8et a%%ess to the proper mail Eolder. 5he +avaMail pattern is* -.terate over the messages an get the Messa%e(.com Special Creative Commons BY-SA 3.0 License Edition .5 < < finally 8 store.%eption is raise store on the Cay ba%k out. the guts are %ontaine in a %ommon %etMessa%e.

%ombine Cith the hooks to the +avaMail +ARs es%ribe in the pre%e ing %hapter.0 License Edition .As o$ the messages in the inbo.com Special Creative Commons BY-SA 3. gives Mail/uKK a%%ess to the message . (90 Subscribe to updates at http://commonsware. o$ the user3supplie mail a%%ount.Communicating via the 8nternet 5his %o e.

0 License Edition .com Special Creative Commons BY-SA 3.PART IV – Intents Subscribe to updates at http://commonsware.

Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

o$ %ourse.. .something: @eah:Q )oC spe%i$i% the QsomethingQ is epen s on the situation N sometimes you knoC e. What you might a%%omplish in a esktop 8". so Ce %an %reate more %omple.0 License Edition .g.n the abstra%t. noC that Ce are Cell3verse in %reating a%tivities. (99 Subscribe to updates at http://commonsware. )oCever.somehoC. #o.es. via ialog bo. an sometimes you on7t. Q@o: . 5his.a%tly Chat you Cant to o &e. is the most obvious %ase $or getting your a%tivity up an visible to the user. An ..com Special Creative Commons BY-SA 3. the $o%us o$ this book has been on a%tivities opene ire%tly by the user $rom the evi%e7s laun%her.. Cant to o.er. in that it shoCs up in the laun%her.CHAPTER &1 Creating 8ntent !ilters "p to noC.. let7s ive into intents.. appli%ations Chile simultaneously being Qgoo An roi %itiKensQ. %hil Cin oCs. An roi is all about intents an re%eivers o$ those intents. remember that the An roi system is base upon lots o$ loosely3 %ouple %omponents. 5he QhoCQ is via intents. While one a%tivity Cill be Qspe%ialQ. in many %ases it is the primary Cay the user Cill start using your appli%ation. an the like are mostly suppose to be in epen ent a%tivities.. open up one o$ your other a%tivities'. An intent is basi%ally a message that you pass to An roi saying.. the other a%tivities all nee to be rea%he .

A%tions are %onstants./ &to bring up a vieCer $or the resour%e'. 5he verb in i%ate Chat shoul be one* 8I5 to retrieve it.t 5rans$er !roto%ol N )55! N he set up a system o$ verbs plus a resses in the $orm o$ "RLs. 5here are other %riteria you %an pla%e insi e an intent &represente as an . .-*AC-. an the Q ataQ is a 2ri..ntent obOe%t'.. .t Cith An roi intents than there are Cith )55! verbs an resour%es.. in that they represent an a%tion plus %onte. 5he a ress in i%ate a resour%e. Pieces o. graphi%. et%.a%tly analogous to )55! verbs an "RLs N the a%tion is the verb. !>#5 to sen $orm ata to it $or pro%essing. content!//contacts/people/?. 5here are more a%tions an more %omponents to the %onte. Intents 5he tCo most important pie%es o$ an intent are the a%tion an Chat An roi re$ers to as the Q ataQ./ Cith a %ontent "ri o$ an pass that intent to An roi . or server3si e program.. 5hese are almost e. Subscribe to updates at http://commonsware./ &to e it the resour%e'..t.)C*AC-. +ust as a Web broCser knoCs hoC to pro%ess a verbV"RL pair. su%h as a Web page.CM*AC-.)C*AC-. An roi knoCs hoC to $in a%tivities or other appli%ation logi% that Cill han le a given intent. su%h as content!//contacts/people/? representing a %onta%t in the %onta%ts atabase. but the %on%ept is still the same.0 License Edition .com Special Creative Commons BY-SA 3. su%h as content!//contacts/people'. besi es the a%tion an Q ataQ 2ri.$ you Cere to %reate an intent %ombining 7. An roi Coul knoC to $in an open an a%tivity %apable o$ vieCing that resour%e./ &to %hoose an available item given a 2ri representing a %olle%tion. su%h as 7.ntents are similar. su%h as* %. )D.Creating 8ntent !ilters WhatAs -our 8ntent: When #ir 5im /erners3Lee %ooke up the )yperte. or 1.

A %omponent./S)R-*AC-. "sing %omponents this Cay obviates the nee $or the other properties o$ the intent./ MA./ %./ 0)-*C./ S)ARC3*AC-. in i%ating the type o$ resour%e you Cant to operate on.MI type. >ther a%tivities Cill probably be in the D)EA2+./ D.com Special Creative Commons BY-SA 3./ D)+)-)*AC-. • • • Stoc$ 0ptions #ome o$ the a%tions e$ine as part o$ An roi $or laun%hing a%tivities are* • • • • • • • • • • • • • • • A/SC)R*AC-. in i%ating it shoul shoC up on the laun%her menu.CM*AC-.*AC-. Chi%h is a 6undle o$ other in$ormation you Cant to pass along to the re%eiver Cith the intent. A M./ 1.. What pie%es o$ in$ormation a given re%eiver %an use is up to the re%eiver an &hope$ully' is Cell3 o%umente .. it oes make the intent more $ragile./ CA++*AC-.-*AC-../-)/-*AC-. @our QmainQ a%tivity Cill be in the +A2/C3)R %ategory. the %lass o$ the a%tivity that is suppose to re%eive this intent.. as it assumes spe%i$i% implementations.Creating 8ntent !ilters • A %ategory./ S)/D-./ R2/*AC-.7) %ategories.or A+-)R/A-.( Subscribe to updates at http://commonsware.../ 1..trasQ.. that the re%eiver might Cant to take a vantage o$./ EAC-.CM*AC-.0 License Edition ./ S)/D*AC-.-F*AC-./ .. Chi%h is to say...A+*AC-.. )oCever.. QI.. i$ you on7t knoC a %olle%tion 2ri.RF*-)S-*AC-./*AC-.7../ )D.

.RF +A2/C3)R*CA-)0.CSA6+)*CA-)0.RF being the ones you Cill use most'* • • • • • • • • • • A+-)R/A-..RF 3. An roi has no oubt Chere the intent is suppose to be route to N it Cill laun%h the name a%tivity../ an )D./*AC-.RF D)EA2+-*CA-)0./ to alloC other appli%ations to sele%t an item $rom your %ontent.)C*AC-./ 5he main ones you Cill use are MA.% Subscribe to updates at http://commonsware. i$ you spe%i$y the target %omponent in your intent.M)*CA-)0. . 7.RF 0AD0)-*CA-)0.7)*CA-)0.CM*AC-. 0ote that there are also some a%tions spe%i$i%ally $or Qbroa %astQ intents N intents that %an be pi%ke up by many a%tivities or listeners.RF 6R. here are the stan ar available %ategories &Cith D)EA2+-*CA-)0.2/-)D*AC-./ 7.. su%h as M)D. #imilarly. there are many other intent a%tions not aime at starting a%tivities. not Oust one. in i%ating that a me ia %ar has been mounte in the system.0 License Edition .RF -)S-*CA-)0./ $or vieCing an e iting %ontent./ $or the main entry point o$ your appli%ation. an 1.RF an +A2/C3)R*CA-)0. 5his might be >F i$ the target intent is in your appli%ation..RF Intent Routin! As note above.Creating 8ntent !ilters • • • SF/C*AC-.t e$initely is not re%ommen e $or sen ing intents to other %.RF 1R)E)R)/C)*CA-)0.RF S)+)C-)D*A+-)R/A-.com Special Creative Commons BY-SA 3./ C)6*S)ARC3*AC-..-*AC-. #imilarly..)C*AC-.7)*CA-)0.A*M.RF -A6*CA-)0../.

ample proOe%ts have intent $ilters e$ine .MI type &i$ supplie ' ?. %ourtesy o$ the An roi appli%ation3buil ing s%ript &activityCreator. Component names.. all o$ Chi%h must be true $or a given a%tivity to be eligible $or a given intent* -. there are three rules.com Special Creative Commons BY-SA 3.amples later in this %hapter. Stating -our 8ntent#ions& All An roi %omponents that Cish to be noti$ie via intents must e%lare intent $ilters. are %onsi ere private to the appli%ation an are subOe%t to %hange.Creating 8ntent !ilters appli%ations. Content 2ri templates an M. you nee to a intent(filter elements to your AndroidManifest. Subscribe to updates at http://commonsware.py or the . as you Cill see later in this %hapter. 5he a%tivity must support the spe%i$ie a%tion 2. /asi%ally...AI e<uivalent'. 5hat is the. All o$ the e. then An roi has to $igure out Chat a%tivities &or other intent re%eivers' are eligible to re%eive the intent. an no more spe%i$i% than that. 5o o this. 5he a%tivity must support all o$ the %ategories name in the intent 5he upshot is that you Cant to make your intents spe%i$i% enough to $in the right re%eiver&s'..intent &par on the pun'. by an large. 5hey look something like this* %.MI types are the pre$erre Cays o$ i enti$ying servi%es you Cish thir 3party %o e to supply.ummm. as a broa ly3Critten intent might Cell resolve to several a%tivities.. 5his routing approa%h is re$erre to as impli%it routing. 5he a%tivity must support the state M. 0ote the use o$ the plural Qa%tivitiesQ.xml $ile.0 License Edition .$ you o not spe%i$y the target %omponent. . so An roi knoCs Chi%h intents shoul go to that %omponent. 5his Cill be%ome %learer as Ce Cork through some e.

prefs#& <application& <activity android!name"#.MI type N either ire%tly.t is in the +A2/C3)R %ategory. More than likely. Ce e%lare that this a%tivity* • • .g.MA. this %ontrols the name asso%iate Cith the appli%ation7s i%on in the main menu. i$ an intent is targete $or that M.com/apk/res/android# packa%e"#com.ample.MI type o$ ata they Cork on.s the main a%tivity $or this appli%ation .android.n this %ase.cate%ory./# /& <cate%ory android!name"#android./' a%tivities spe%i$y the M.0 License Edition . meaning it gets an i%on in the An roi main menu /e%ause this a%tivity is the main one $or the appli%ation. 5hat in i%ates that the asso%iate %omponent &e.1refsDemo# android!label"#1refsDemo#& <intent(filter& <action android!name"#android. you Cill also Cant to have your se%on ary &non3MA.action. @ou are Cel%ome to have more than one a%tion or more than one %ategory in your intent $ilters.$ Subscribe to updates at http://commonsware..android. )ere. you %oul have an a%tivity e%lare like this* %. 5he intent $ilter also has a label &android!label " #1refsDemo#'. . a%tivity' han les multiple i$$erent sorts o$ intents.com Special Creative Commons BY-SA 3. (or e. 5hen.intent.commonsware.+A2/C3)R# /& </intent(filter& </activity& </application& </manifest& 0ote the intent(filter element un er the a%tivity element. An roi knoCs this is the %omponent it shoul laun%h Chen somebo y %hooses the appli%ation $rom the main menu.Creating 8ntent !ilters <manifest xmlns!android"#$ttp!//sc$emas.intent. or in ire%tly by the 2ri re$eren%ing something o$ that type N An roi Cill knoC that the %omponent han les su%h ata.

ntent:.)C# /& <cate%ory android!name"#android. typi%ally involving laun%hing other intents to trigger logi% in an a%tivity.cate%ory.0 License Edition .g.intent.tour pie%e o$ %ontent. e$ine as a %lass implementing the .-our7iewActivity#& <intent(filter& <action android!name"#android.D)EA2+-# /& <data android!mime-ype"#vnd.xml $ile* %.ntent re%eivers are isposable obOe%ts esigne to re%eive intents N parti%ularly broa %ast intents N an take a%tion.0 a%tivity $or this appli%ation' or $rom another a%tivity in another An roi appli%ation that happens to knoC a 2ri that this a%tivity han les.. then laun%h a%tivity 0' • (or these %ases. the intent $ilters Cere set up on a%tivities.commonsware.Creating 8ntent !ilters <activity android!name"#.ntent re%eivers implement that metho .ntentReceiver inter$a%e has only one metho * onReceive. . #ometimes.item/vnd.com Special Creative Commons BY-SA 3.g.a%tly Chat Ce Cant* • #ome system events might %ause us to Cant to trigger something in a servi%e rather than an a%tivity #ome events might nee to laun%h i$$erent a%tivities in i$$erent %ir%umstan%es.cursor.intent.n the e. 5he . servi%e.. tying intents to a%tivities is not e.action. then laun%h a%tivity MP i$ the atabase oes not have a @. .ntentReceiver inter$a%e.android. Chere the %riteria are not solely base on the intent itsel$. An roi o$$ers the intent re%eiver./ Subscribe to updates at http://commonsware.amples shoCn above. but some other state &e..android. Chere they o Chatever it is they Cish to o upon an in%oming intent. the MA. 5hat intent %oul %ome $rom another a%tivity in the same appli%ation &e.cursor. i$ Ce get intent E an the atabase has a @. or other %omponent.item/vnd.commonsware. 5o e%lare an intent re%eiver.tour# /& </intent(filter& </activity& 5his a%tivity Cill get laun%he by an intent re<uesting to vieC a 2ri representing a vnd. a an re%eiver element to your AndroidManifest.7. 5arro4 2eceivers .

.. an they %annot open a ialog bo. $rom your Activity7s on1ause:.com Special Creative Commons BY-SA 3. %. the re%eiver instan%e is subOe%t to garbage %olle%tion an Cill not be reuse . su%h as an a%tivity or servi%e N in that %ase. in this %ase. %allba%k to e%lare interest in an intent.ample.xml.My. (or e. 5his means intent re%eivers are someChat limite in Chat they %an o.ntentReceiver is implemente on some longer3live %omponent.g.ntentReceiverClass/ame# /& An intent re%eiver is only alive $or as long as it takes to pro%ess onReceive. the intent re%eiver lives as long as its QhostQ oes &e. until the a%tivity is $roKen'. you nee to %all re%ister. mostly to avoi anything that involves any sort o$ %allba%k.t sample appli%ation. Chen you no longer nee those intents. N as soon as that metho returns.ntent:.ntent:. @ou %an see an e.ample o$ an intent re%eiver in a%tion in the 5our.ntent:. you %annot e%lare the intent re%eiver via AndroidManifest. then %all unre%ister. 5he e.0 Subscribe to updates at http://commonsware.Creating 8ntent !ilters <receiver android!name"#.0 License Edition .nstea . they %annot bin to a servi%e.. )oCever.%eption is i$ the . on your Activity7s onResume:.

a %alen ar appli%ation %oul have a%tivities $or vieCing the %alen ar.ample. (or e. Cith one QmainQ a%tivity being the one laun%he by the An roi laun%her. ar%hite%ture is that evelopers shoul e%ompose their appli%ation into istin%t a%tivities.3 Subscribe to updates at http://commonsware. 5his.something. you nee to be able to %ause the vieC3 event a%tivity to laun%h an shoC a spe%i$i% event &the one the user %li%ke upon'..0 License Edition .something Cith it. @ou knoC Chat a%tivity you Cant to laun%h. vieCing a single event. 5his %an be $urther broken oCn into tCo s%enarios* -.. implies that one o$ your a%tivities has the means to start up another a%tivity.CHAPTER && aunching )ctivities and Sub" )ctivities As is%usse previously. but you o not knoC up $ront Chat the options are %. e iting an event &in%lu ing a ing a neC one'. @ou have a %ontent 2ri to. the theory behin the An roi ". somehoC. you might Cant to shoC the vieC3event a%tivity $or that event. probably be%ause it is another a%tivity in your oCn appli%ation 2. ea%h rea%hable via intents. (or e. o$ %ourse. i$ somebo y %li%ks on an event $rom the vieC3 %alen ar a%tivity.com Special Creative Commons BY-SA 3.. an you Cant your users to be able to o. an so $orth. ea%h implemente as an Activity.ample.. 5his means that.

your main a%tivity Cill nee to knoC Chen the authenti%ation is %omplete so it %an start to use the Web servi%e. you probably Cant to laun%h the %hil as a sub3a%tivity. suppose you Cant to spaCn an a%tivity to %olle%t authenti%ation in$ormation $or some Web servi%e you are %onne%ting to N maybe you nee to authenti%ate Cith >pen. When the user ele%ts to vieC an atta%hment. Peers and Subs >ne key <uestion you nee to ansCer Chen you e%i e to laun%h an a%tivity is* oes your a%tivity nee to knoC Chen the laun%he a%tivity en sD (or e. the laun%he a%tivity is more a peer o$ your a%tivity.7 Subscribe to updates at http://commonsware.aunching )ctivities and Sub")ctivities 5his %hapter %overs the $irst s%enarioP the ne. . @our a%tivity Cill not be in$orme Chen the 6%hil 9 is one.n that %ase. Chi%h means your a%tivity Cill be noti$ie Chen the %hil a%tivity is %omplete.n this %ase.n the $irst s%enario.A in or er to use an >Auth servi%e.n the se%on s%enario. neither you nor the user ne%essarily e. . Start AEm >p 5he tCo pie%es $or starting an a%tivity are an intent an your %hoi%e o$ hoC to start it up. so you probably Cant to laun%h the 6%hil 9 Oust as a regular a%tivity. but. your a%tivity really oesn7t nee to knoC. >n the other han . . . %.com Special Creative Commons BY-SA 3.ample.0 License Edition . then again.t %hapter han les the se%on . imagine an email appli%ation in An roi .pe%t the main a%tivity to knoC Chen the user is one vieCing that atta%hment. the laun%he a%tivity is %learly subor inate to the laun%hing a%tivity.

$ the a%tivity you inten to laun%h is one o$ your oCn. you nee to pass it to An roi an get the %hil a%tivity to laun%h.toString:./'. you %oul put together an intent $or some 2ri. given that Ce have the latitu e an longitu e o$ some position &lat an lon.5 )ere.. you %oul %reate an intent like this* new Intent:t$isG 3elpActivity.0 License Edition .xml $ile. ./G uri. 5he simplest option is to %all startActivity:.B #G#Blon. 5his a%tivity Coul nee to be name in your AndroidManifest. you may $in it simplest to %reate an e. though not ne%essarily Cith any intent $ilter. Ce %onstru%t a %eo s%heme 2ri an %reate an intent re<uesting to vieC this 2ri &7. @our a%tivity Cill not be in$orme Chen the 6%hil 9 a%tivity is %omplete.ample. sin%e you are trying to re<uest it ire%tly. Cith the intent N this Cill %ause An roi to $in the best3mat%h a%tivity or intent re%eiver an pass the intent to it $or han ling.9 Subscribe to updates at http://commonsware.ntent.com Special Creative Commons BY-SA 3...parse:#%eo!#Blat. re<uesting a parti%ular a%tion* 2ri uri"2ri. $rom Cithin your a%tivity. $or some a%tivity or other intent re%eiver to o something.)C*AC-.ntent i"new Intent:.pli%it intent. intents en%apsulate a re<uest. @ou have $our %hoi%es* -.toString:.5 5his Coul stipulate that you Cante to laun%h the 3elpActivity.5 . % $e the C ll >n%e you have your intent. %. >r. ma e to An roi .)C*AC-.7.aunching )ctivities and Sub")ctivities % $e n Intent As is%usse in a previous %hapter. naming the %omponent you Cish to laun%h.class. (or e. respe%tively' o$ type Double.

CM*AC-. With startSubActivity:. a 1. take a peek at the +aunc$ sample appli%ation.ntentSeriali'ed:. =. An roi Cill pass the intent to all %an i ate a%tivities an intent re%eivers one at a time N i$ any one 6%onsumes9 the intent.RS-*2S)R' An optional Strin% %ontaining some result ata. An roi Cill pass the intent to all registere a%tivities an intent re%eivers that %oul possibly Cant this intent.. your a%tivity Cill be noti$ie Chen the %hil a%tivity is %omplete via the onActivityResult:.ntent:. $rom the %hil a%tivity %alling setResult:. you %an implement the to be noti$ie Chen the %hil a%tivity has %omplete its Cork.aunching )ctivities and Sub")ctivities 2. passing it the intent an a number &uni<ue to the %alling a%tivity'. though you %an %reate your oCn return %o es &pi%k a number starting Cith R)S2+-*E.. %allba%k as note . the rest o$ the the %an i ates are not noti$ie .com Special Creative Commons BY-SA 3. )ere. @ou %an %all broadcast. not Oust the best mat%h.ternal resour%e N $or e.. @ou also get* • A result %o e... 5he EML layout is $airly straight$orCar * tCo $iel s $or the latitu e an longitu e. or startSubActivity:. 5he %allba%k re%eives the uni<ue number supplie to startSubActivity:.ample. N broa %ast intents are more typi%ally raise by the An roi system itsel$./ intent typi%ally returns the sele%te bit o$ %ontent via this ata string An optional 6undle %ontaining a result %o e an ata string itional in$ormation beyon the • • 5o emonstrate laun%hing a peer a%tivity.n this %ase.M or R)S2+-*CA/C)++)D. ?. Subscribe to updates at http://commonsware. An roi Cill $in the best3mat%h han ler an pass the intent over to it. @ou %an %all broadcast.0 License Edition . possibly a "RL to some internal or e. Most o$ the time. @ou %an %all startSubActivity:. onActivityResult:.. )oCever. so you %an etermine Chi%h %hil a%tivity is the one that has %omplete . 5ypi%ally this is R)S2+-*. . %allba%k &see beloC'. plus a button* %(.. you Cill Cin up using startActivity:.

ntent5 import android.commonsware.android.Activity5 import android.2ri5 %(( Subscribe to updates at http://commonsware.app.com Special Creative Commons BY-SA 3.net.aunching )ctivities and Sub")ctivities <>xml version"#?.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-able+ayout android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!stretc$Columns"#?GH# & <-ableRow& <-ext7iew android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!paddin%+eft"#Hdip# android!paddin%Ri%$t"#Ndip# android!text"#+ocation!# /& <)dit-ext android!id"#9Bid/lat# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!cursor7isible"#true# android!editable"#true# android!sin%le+ine"#true# android!layout*wei%$t"#?# /& <)dit-ext android!id"#9Bid/lon# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!cursor7isible"#true# android!editable"#true# android!sin%le+ine"#true# android!layout*wei%$t"#?# /& </-ableRow& </-able+ayout& <6utton android!id"#9Bid/map# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!text"#S$ow MeW# /& </+inear+ayout& 5he button7s .@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.0 License Edition ..nClick+istener simply takes the latitu e an longitu e. pours them into a %eo s%heme 2ri.activities5 import android.content.android. then starts the a%tivity. packa%e com.

lat.5 btn..)dit-ext5 public class +aunc$Demo extends Activity 8 private )dit-ext lat5 private )dit-ext lon5 9. 8 Strin% *lat"lat.wid%et.setOnClickListener:new 7iew.6undle5 android.view.id.5 Strin% *lon"lon.lon..map.aunching )ctivities and Sub")ctivities import import import import android.findViewById:R.5 < <.5 lat":)dit-ext.OnClickListener:.5 2ri uri"2ri.main.7.getText:.wid%et.onCreate:icicle.findViewById:R. 8 super.5 start#cti ity:new Intent:./G uri.)C*AC-.layout..toString:.7iew5 android.ntent.6utton5 android.5 setContentView:R.5 < < 5he a%tivity is not mu%h to look at* %(% Subscribe to updates at http://commonsware. 8 public void onClick:7iew view..getText:.verride public void onCreate:6undle icicle.parse:#%eo!#B*latB#G#B*lon.findViewById:R.com Special Creative Commons BY-SA 3.toString:.id.os.0 License Edition .5 6utton btn":6utton.id.5 lon":)dit-ext.

the resulting map is more interesting.aunching )ctivities and Sub")ctivities !igure /%< The aunch. 0ote that this is the built3in An roi map a%tivity N Ce i not %reate our oCn a%tivity to isplay this map.g.0-??? longitu e' an %li%k the button. %(.emo sample application6 as initially launched .0 License Edition . =0.com Special Creative Commons BY-SA 3.2--42 latitu e an 32=.. Subscribe to updates at http://commonsware.$ you $ill in a lo%ation &e.

emo6 sho4ing the region kno4n as ='round Jero= in 5e4 -ork City .0 License Edition .aunching )ctivities and Sub")ctivities !igure /. you Cill see hoC you %an %reate maps in your oCn a%tivities. in %ase you nee greater %ontrol over hoC the map is isplaye . %($ Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.< The map launched by aunch .n a later %hapter.

%(/ Subscribe to updates at http://commonsware. #ometimes. you7re lost. ask $or all pie%es o$ %ontent re$eren%ing some tag. Web "RLs. Chere users %oul tag pie%es o$ %ontent N %onta%ts. #ometimes. @our subsystem Coul hol onto the 2ri o$ the %ontent plus the asso%iate tags. )oCever. say. su%h as vieC the %ontent represente by a 2ri. 5his might even serve as a <uasi3bookmark servi%e $or items on their phone.0 License Edition . geographi% lo%ations.pe%t to be able to o use$ul things Cith the %ontent they $in in your subsystem. 5hat7s all Cell an goo . 5he problem is. you knoC Oust Chat you Cant to o. suppose you Cere %reating a %ommon tagging subsystem $or An roi .com Special Creative Commons BY-SA 3. All you have is a %ontent 2ri. an you on7t really knoC Chat you %an o Cith it.CHAPTER &' !inding )vailable )ctions via 8ntrospection #ometimes. you probably nee some sort o$ maintenan%e a%tivity. or have the user pi%k a pie%e o$ %ontent o$ some M. so other subsystems %oul . et%.MI type. (or e. the user is going to e. you have a pretty goo i ea o$ Chat you Cant to o.ample. su%h as isplay one o$ your other a%tivities. Chere users %oul vieC all their tags an the pie%es o$ %ontent so tagge . su%h as ial a %onta%t or shoC a map $or a lo%ation.

@ou probably %an vieC any o$ them..com Special Creative Commons BY-SA 3.M result %o e. 5o o this. %allba%k $or this re<uest gets a R)S2+-*. An roi o$$ers various means by Chi%h you %an present to your users a set o$ likely a%tivities to spaCn $or a given %ontent 2ri.0 License Edition .$ your onActivityResult:.g. tag it. 5his a%tivity gives you a $iel $or a %olle%tion 2ri &Cith content!//contacts/people pre3 $ille in $or your %onvenien%e'.plores some o$ these 2ri a%tion introspe%tion tools. (or e.even i$ you have no i ea Chat that %ontent 2ri really represents.n this %ase.' to alloC the user to pi%k a pie%e o$ %ontent o$ the spe%i$ie type. su%h as content!//contacts/people representing the list o$ %onta%ts in the sto%k An roi %onta%ts list.CM*AC-. but %an you e it themD Can you ial themD #in%e neC appli%ations Cith neC types o$ %ontent %oul be a e by any user at any time.. (ortunately./ on the target 2ri.. the An roi evelopers thought o$ this.!inding )vailable )ctions via 8ntrospection 5he problem is.-F*AC-. you knoC your %ontent 2ri represents a %olle%tion o$ some type. you have absolutely no i ea Chat is all possible Cith any given %ontent 2ri. . you nee to %reate an intent $or the 1.. you %an7t even assume you knoC all possible %ombinations Oust by looking at the sto%k appli%ations shippe on all An roi evi%es.ample. 5his %hapter e. .com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <)dit-ext android!id"#9Bid/type# %(0 Subscribe to updates at http://commonsware. Pick AEm #ometimes. plus a really big 68imme:9 button* <>xml version"#?. take a look at 1ick in the sample appli%ations.7. you %an let the user pi%k a %onta%t that your a%tivity %an then use &e.android. then start a sub a%tivity &via startSubActivity:. your ata string %an be parse into a 2ri representing the %hosen pie%e o$ %ontent. ial it'.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.

!inding )vailable )ctions via 8ntrospection /& <6utton android!id"#9Bid/pick# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!text"#0immeW# android!layout*wei%$t"#?# /& </+inear+ayout& android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!cursor7isible"#true# android!editable"#true# android!sin%le+ine"#true# android!text"#content!//contacts/people# "pon being %li%ke . packa%e com./ is invoke on the resulting %ontent 2ri. 8 super..content.5 btn..view.Activity5 android.layout. 8 .7. When that sub3 a%tivity %ompletes Cith R)S2+-*.parse:type.pick. 8 public void onClick:7iew view.)dit-ext5 public class 1ickDemo extends Activity 8 static final int 1.ntent.CM*AC-.introspection5 import import import import import import import android.toString:.7iew5 android.getText:./ on the user3supplie %olle%tion 2ri an starts the sub3a%tivity..onCreate:icicle.android.wid%et.1.wid%et.type.-F*AC-.5 < startSu!#cti ity:iG 1..CM*R)T2)S.net." ?II]5 private )dit-ext type5 9.verride public void onCreate:6undle icicle.os.M.findViewById:R.0 License Edition .ntent5 android..com Special Creative Commons BY-SA 3.6undle5 android.2ri5 android.setOnClickListener:new 7iew.5 setContentView:R..app./G 2ri. the button %reates the 1.findViewById:R.OnClickListener:.commonsware.id.6utton5 android.5 6utton btn":6utton.5 %(3 Subscribe to updates at http://commonsware.. the 7.ntent i"new Intent:.5 type":)dit-ext.)C*AC-.main.id.CM*R)T2)S-.CM*AC-.

.5 < protected void on#cti ity$esult:int reJuestCodeG int resultCodeG Strin% dataG 6undle extras.ntent.com Special Creative Commons BY-SA 3.emo sample application6 as initially launched %(7 Subscribe to updates at http://commonsware./G 2ri.CM*R)T2)S-. !igure /$< The Pick.)C*AC-. 8 if :resultCode""R)S2+-*. pi%ks a pie%e o$ %ontent..7..5 < < < < 5he result* the user %hooses a %olle%tion.0 License Edition .M. an vieCs it.parse:data.!inding )vailable )ctions via 8ntrospection <. 8 start#cti ity:new Intent:. 8 if :reJuestCode""1.

0 License Edition .emo after choosing one of the people from the pick list %(9 Subscribe to updates at http://commonsware.!inding )vailable )ctions via 8ntrospection !igure //< The same application6 after clicking the ='imme!= button6 sho4ing the list of available people !igure /0< ) vie4 of a contact6 launched by Pick.com Special Creative Commons BY-SA 3.

5he layout noC a s a +ist7iew.com Special Creative Commons BY-SA 3.g. let7s embellish the previous e. to shoC the available a%tions* %%. to take the user to the a%tivity they re<ueste .ample N %opie into Adapter N to give the user some %hoi%es $or Chat to o Cith the pi%ke pie%e o$ %ontent.ntent.5 #o.parse:data. meaning they supply %hil vieCs to sele%tion Ci gets like +ist7iew an Spinner. All Cithout you having to knoC anything about Chat the %ontent is.conAdapter. 6I it Conta%t9' an an i%on asso%iate Cith the a%tion. We7ll %over more about re<uesting &an re<uiring' permissions later in this book. rather than alCays Oust vieCing it as be$ore. 5hat intent %an be ire%tly passe to startActivity:. (or the sample.!inding )vailable )ctions via 8ntrospection >ne $laC in this appli%ation is that it may not have permission to vieC Chatever %ontent %olle%tion the user entere . >ne %on$using $a%et o$ ActivityAdapter an Activity. Ce ha to spe%i$i%ally re<uest permission to rea the user7s %onta%ts. they supply a list o$ available a%tions to take on the %ontent N an $or Activity.n this %ase. 5his means you nee to Crap the 2ri $or the %ontent in an otherCise3empty .0 License Edition .xml.. not a 2ri. 5hese are +istAdapter sub%lasses..5 i.conAdapter. >n%e a user has %hosen an a%tion N $or e.ntent i"new Intent:. it in%lu es both a name &e. by %li%king on a list item N you %an get the intent that %ombines the %hosen a%tion Cith the %ontent 2ri o$ the pie%e o$ %ontent. on their %onstru%tor. Subscribe to updates at http://commonsware.ntent in or er to satis$y the %onstru%tor7s re<uest* .conAdapter is that they take an . via a uses3 permission element in AndroidManifest. .5 +istAdapter adapter"new #cti ity#dapter:t$isG i.setData:2ri. )daptable )dapters >ne Cay to present your users Cith available a%tions to take on a pie%e o$ %ontent is to use ActivityAdapter or Activity.ample.

android.0 License Edition .!inding )vailable )ctions via 8ntrospection <>xml version"#?.n-op"#false# android!layout*wei%$t"#?# /& </+inear+ayout& 5he resulting ".com Special Creative Commons BY-SA 3.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. noC shoCs the available a%tions* %%( Subscribe to updates at http://commonsware.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <)dit-ext android!id"#9Bid/type# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!cursor7isible"#true# android!editable"#true# android!sin%le+ine"#true# android!text"#content!//contacts/people# /& <6utton android!id"#9Bid/pick# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!text"#0immeW# /& <+ist7iew android!id"#9android!id/list# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!drawSelector.

com Special Creative Commons BY-SA 3.!inding )vailable )ctions via 8ntrospection !igure /3< The )ctivity)dapter. )en%e.0 License Edition . at the time o$ this Criting. the user is given a%tion options that may not be alloCe %%% Subscribe to updates at http://commonsware.emo sample application6 as initially launched !igure /7< The same application6 after clicking ='imme!= and choosing a person 0ote that. An roi oes not $ilter the available a%tions to only be the ones that are possible $rom the a%tivity N it shoCs them all.

RF is the %%. an Ce knoC nothing about it.ptions:. the %ontent Cas $rom some other An roi appli%ation. every time they Cante to tag a pie%e o$ %ontent. 5o a%%omplish this. Would -ou ike to See the *enu: Another Cay to give the user Cays to take a%tions on a pie%e o$ %ontent.ample. is to inOe%t a set o$ menu %hoi%es into the options menu via add. . shoCing ActivityAdapter. 5his metho . (or e. 5he %anoni%al e.com Special Creative Commons BY-SA 3. takes an .ample. they Coul probably pre$er a menu %hoi%e in the %ontent7s oCn 6home9 a%tivity Chere they %an in i%ate they Cant to tag it. $or e.ample./' an a %ategory o$ A+-)R/A-)*CA-)0.ntent an other parameters an $ills in a set o$ menu %hoi%es on the Menu instan%e.pe%t to be one Cith your %ontent.ntent. imagine the tagging subsystem mentione in the intro u%tion to this %hapter. Chi%h lea s them to the set3a3tag a%tivity an tells that a%tivity Chat %ontent shoul get tagge . supporting any pie%e o$ %ontent.0 License Edition . though. Choosing one o$ those menu %hoi%es spaCns the asso%iate a%tivity.ptions:. illustrates another $lavor o$ having a pie%e o$ %ontent an not knoCing the a%tions that %an be taken.$ you run the supplie sample %o e Cithout mo i$i%ations.!inding )vailable )ctions via 8ntrospection ue to insu$$i%ient permissions. .RF. the tagging subsystem shoul set up an intent $ilter. Subscribe to updates at http://commonsware.nstea . there may be other options you are unaCare o$ that are available to users. -A0*AC-. but not e it them.ntent. you Cill be able to vieC a %hosen %onta%t. .ample o$ using add.t Coul be very annoying to users i$. An roi appli%ations are per$e%tly %apable o$ a ing neC a%tions to e. Cithout you knoCing Chat a%tions are possible.n the previous e. .g..isting %ontent types. )oCever. then turn aroun an pi%k the %ontent they Oust ha been Corking on &i$ that is even te%hni%ally possible' be$ore asso%iating tags Cith it.. Cith their oCn a%tion &e. that Ce knoC $ull Cell Chat the %ontent is N it7s ours. they ha to go to a separate tagging tool.. so even though you Crote your appli%ation an knoC Chat you e. ea%h representing one possible a%tion. 5he %ategory A+-)R/A-)*CA-)0.t is also possible. available on Menu. .

ing a%tions to another appli%ation7s .ntent $or Chi%h you Cant the available a%tions • • • • %%$ Subscribe to updates at http://commonsware.7)*CA-)0. .ntent. so the a%tivity %an han le its oCn a%tions as it sees $it An array o$ .RF.addCategory:.7)*CA-)0.n this %ase. su%h as the $olloCing* .com Special Creative Commons BY-SA 3.A+-)R/A-. an the $olloCing parameters* • 5he sort position $or this set o$ menu %hoi%es.ntent Ce are using to pi%k a%tions $rom re<uires that appropriate intent re%eivers support the A+-)R/A-.7) &appear a$ter other menu %hoi%es' A uni<ue number $or this set o$ menu %hoi%es. myContent2ri is the %ontent 2ri o$ Chatever is being vieCe by the user in this a%tivity. to a those a 3ons7 a%tions to your options menu.addIntentOptions:Menu.class. the . typi%ally set to @ &appear in the or er a e to the menu' or A+-)R/A-.0 License Edition .ntent.5 )ere. 5hen. you shoul use add.5 menu.!inding )vailable )ctions via 8ntrospection %onvention $or one appli%ation a %ontent. or @ i$ you o not nee a number A Component/ame instan%e representing the a%tivity that is populating its menu N this is use to $ilter out the a%tivity7s oCn a%tions.5 intent.RF.ntent. MyActivity is the name o$ the a%tivity %lass.$ you Cant to Crite a%tivities that are aCare o$ possible a 3ons like tagging.ptions:. Ce a the options to the menu Cith add.A+-)R/A-.ntent intent " new Intent:nullG myContent2ri. an menu is the menu being mo i$ie .7)G @G new Component%ame:t$isG MyActivity.ptions:.G nullG intentG @G null.ntent instan%es that are the 6spe%i$i%9 mat%hes N any a%tions mat%hing those intents are shoCn $irst in the menu be$ore any other possible a%tions 5he .

Chi%h means mat%hing a%tions must also implement the D)EA2+-*CA-)0.ptions:.ptions:.$ you Coul like to o$$er alternative a%tions to users. 5he only one o$ likely relevan%e is represente as MA-C3*D)EA2+-*. Chi%h is available to your a%tivity via %et1acka%eMana%er:.ntent representing the a%tions you are seeking..0 License Edition . Cith the 6spe%i$i%s9 ones $irst.ptions:.t returns a +ist o$ .ntent.ntent instan%es supplie as the 6spe%i$i%s9.$ you o not nee this.ptions:. get the .ntent. the overall ..com Special Creative Commons BY-SA 3. you %oul %all Juery. $or the 6heavy li$ting9 o$ $in ing possible a%tions.ntent instan%es mat%hing the state %riteria. An array o$ Menu./+F. metho takes some o$ the same parameters as oes add. use a value o$ @ $or the $lags.. .ntentActivity. but by means other than the ActivityAdapter an add.ntent.. %%/ Subscribe to updates at http://commonsware. use Juery. or null i$ you o not nee those items &or are not using 6spe%i$i%s9' • )sking )round /oth the ActivityAdapter $amily an add. the 6spe%i$i%s9 array o$ . an the set o$ $lags. metho is implemente on 1acka%eMana%er. 5he Juery..RF %ategory.!inding )vailable )ctions via 8ntrospection • A set o$ $lags.ntentActivity.ptions:. 5he Juery. a toolbar'.tem. means. notably the %aller Component/ame. Chi%h Cill hol the menu items mat%hing the array o$ . .ptions:.ptions:. then use them to populate some other user inter$a%e &e.ntentActivity.g.ntent instan%es. .ntent instan%es.ntentActivity.

com Special Creative Commons BY-SA 3.Subscribe to updates at http://commonsware.0 License Edition .

PART V – Content Providers and Services Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

0 License Edition .com Special Creative Commons BY-SA 3.Subscribe to updates at http://commonsware.

t %hapter Cill e. all separate by %%9 Subscribe to updates at http://commonsware. up ate that ata. 8iven a %olle%tion 2ri. 5he ata %oul be store in a #HLite atabase. you %an %reate neC pie%es o$ %ontent via insert operations.nternet. you %an rea ata represente by the 2ri. elete' operations using a %ontent provi er. or be store on some $ar3o$$ server a%%esse over the . 2ri instan%es %an represent either %olle%tions or in ivi ual pie%es o$ %ontent. Pieces of *e 5he simpli$ie mo el o$ the %onstru%tion o$ a %ontent 2ri is the s%heme. so long as it is available to you Chen nee e . Content provi ers o$$er ata en%apsulation using 2ri instan%es as han les N you neither knoC nor %are Chere the ata represente by the 2ri %omes $rom. 5his %hapter %overs using %ontent provi ersP the ne. 8iven a 2ri. optionally. An roi lets you use e.0 License Edition .plain hoC you %an serve up your oCn ata using the %ontent provi er $rameCork. an .isting %ontent provi ers. rea . 8iven an instan%e 2ri. the namespa%e o$ ata. or in $lat $iles. you %an per$orm basi% CR"A &%reate. or elete the instan%e outright. the instan%e i enti$ier. up ate. or retrieve o$$ a evi%e. plus %reate your oCn.CHAPTER &( >sing a Content Provider Any 2ri in An roi that begins Cith the content!// s%heme represents a resour%e serve up by a %ontent provi er.com Special Creative Commons BY-SA 3.

though in %ommon is%ussion. Subscribe to updates at http://commonsware.provider.ample. 5he s%heme o$ a %ontent "ri is alCays content!//. so you have a 2ri $or the instan%e.C. 'etting a Dandle #o. as the %onta%ts %ontent provi er may serve up other ata using other base 2ri values. bi%y%le tours $rom the 5our. you %an %all add./-)/-*2R.ample.pe%t these to be 2ri obOe%ts. . is to get the base 2ri $rom the %ontent provi er itsel$ in %o e.g. #o. (or e. a %ontent 2ri o$ content!//tours/L represents the tours instan%e Cith an i enti$ier o$ L.. or a set o$ ata supporte by a %ontent provi er.$ you Oust nee the %olle%tion. . B' represents a single instan%e. 5he base 2ri %ombine Cith an instan%e i enti$ier &e. is the base 2ri $or %onta%ts represente as people N this maps to content!//contacts/people. Most o$ the An roi A!. stati% metho %reates a 2ri out o$ the string representation.s e. Chere o these 2ri instan%es %ome $romD 5he most popular starting point.com Special Creative Commons BY-SA 3..ample above. this 2ri Corks as3isP i$ you nee an instan%e an knoC its i enti$ier.parse:.>sing a Content Provider slashes in "RL3style notation.d:. it is simpler to think o$ them as strings. android. 5he 2ri. i$ you knoC the type o$ ata you Cant to Cork Cith.n the e. 5he %ombination o$ the s%heme an the namespa%e is knoCn as the 6base "ri9 o$ a %ontent provi er.0 License Edition . %. the base 2ri $or %onta%ts is content!//contacts/people. 5he base 2ri %an be more %ompli%ate . 5he base 2ri represents a %olle%tion o$ instan%es. on the 2ri to inOe%t it. content!//tours is the base 2ri $or a %ontent provi er that serves up in$ormation about 6tours9 &in this %ase.t sample appli%ation'. (or e.

>sing a Content Provider @ou might also get 2ri instan%es han e to you $rom other sour%es.. 5he i$$eren%e is that this re<uest is being ma e o$ a %ontent provi er. as the base 2ri values %oul %on%eivably %hange over time. or the instan%e 2ri o$ a spe%i$i% obOe%t to <uery 2. 5he base 2ri o$ the %ontent provi er to <uery.parse:. (or e./ intents. 5he ne. a sort or er.( Subscribe to updates at http://commonsware. Chi%h you %an use to retrieve the ata returne by the <uery. et%.. not ire%tly o$ some atabase &e. $un%tioning like a #HL C3)R) %lause =. @ou %an also har 3Cire literal Strin% obOe%ts an %onvert them into 2ri instan%es via 2ri.CM*AC-. *akinA Fueries 8iven a base 2ri. A %onstraint statement.unless you e%i e to pi%k it apart using the various getters on the 2ri %lass.n the pre%e ing %hapter.ample. $un%tioning like a #HL . . B. in the pre%e ing %hapter. the 2ri is truly an opa<ue han le. metho available to your a%tivity. An array o$ properties o$ instan%es $rom that %ontent provi er that you Cant returne by the <uery ?.n this %ase.. you %an run a <uery to return ata out o$ the %ontent provi er relate to that 2ri.0 License Edition . 5his isn7t an i eal solution.RD)R 6F %lause 5his metho returns a Cursor obOe%t. . An optional sort statement. Ce saC hoC you got 2ri han les $or %onta%ts via sub3 a%tivities respon ing to 1. 5his metho takes $ive parameters* -.com Special Creative Commons BY-SA 3. the %onstraints to etermine Chi%h 6roCs9 to return. 5his has mu%h o$ the $eel o$ #HL* you spe%i$y the 6%olumns9 to return.. An optional set o$ parameters to bin repla%ing any > that appear there into the %onstraint %lause.g. #HLite'. %.us o$ this is the mana%edTuery:.. the sample %o e use an )dit7iew Cith content!//contacts/people pre3$ille in.

Chi%h shoCs the %ue sheet $or a sele%te bi%y%le tour* try 8 if :c""null.=)C-.% Subscribe to updates at http://commonsware. 8 android.e:#-our.amples %ome $rom the 5our.1R.getData:.getData:.G c..=)C-. . in i%ating that Ce o not nee a %onstraint %lause &the 2ri represents the instan%e Ce nee '.5 tour"new Tour:getIntent:. #pe%i$i%ally.G -our. nor a sort or er &Ce shoul only get one entry ba%k' • • %..>sing a Content Provider 6!roperties9 is to %ontent provi ers as %olumns are to atabases..5 < catc$ :-$rowable t.tW ( #Btour.n the %all to mana%edTuery:.5 setTitle:#-our. the $olloCing %o e $ragment is $rom the -our7iewActivity. ea%h representing some pie%e o$ ata.ample. supplie to us by our -our mo el %lass &1R.n other Cor s.first:.com Special Creative Commons BY-SA 3..5 < else 8 c.5 int sel"getSelectedItem&osition:.5 < c./' 5hree null values.getTitle:. >ur %ontent provi er e. 5his Cill hope$ully make more sense given an e.t#G #)xception creatin% tour#G t. Ce provi e* • 5he 2ri passe into the a%tivity by the %aller &%et..5 setList#dapter:new $oute#dapter:tourG t$is.util. provi e to -our7iewActivity $rom the invoking a%tivity &-our+istActivity' A list o$ properties to retrieve.+o%. ea%h instan%e &roC' returne by a <uery %onsists o$ a set o$ properties &%olumns'.5 < .re-uery:. A.'.uery:getIntent:./G nullG nullG null.. 8 c"managed. in this %ase representing a spe%i$i% bi%y%le tour.t sample appli%ation.5 setSelection:sel. as es%ribe in Appen i.%etData:.0 License Edition .ntent:.. nor parameters $or the %onstraint..

-ours. via ata it is retrieving $rom the tour %ontent provi er.0 License Edition . 5his %lass bri ges betCeen the Cursor an a sele%tion Ci get.)D*DA-)"#modified#5 R.-ours. it has the ata ne%essary to %reate the %orrespon ing -our mo el.>sing a Content Provider 5he biggest 6magi%9 here is the list o$ properties.2-)"#route#5 #o. 5he tour %ontent provi er.D.. su%h as a +ist7iew or Spinner.2-)<5 5he proOe%tion is simply an array o$ strings.M.. $or e.-. Subscribe to updates at http://commonsware. 5he lineup o$ Chat properties are possible $or a given %ontent provi er shoul be provi e by the o%umentation &or sour%e %o e' $or the %ontent provi er itsel$.-ours. !our the Cursor into a %. listing properties e. Chen the -our7iewActivity invokes the <uery an gets the Cursor. )oCever.1-. simply provi es values $or these symboli% names* public public public public public static static static static static final final final final final Strin% Strin% Strin% Strin% Strin% -.D)SCR.=)C-. in turn. Ce elegate to the -our mo el %lass the responsibility o$ telling us Chi%h properties it nee s to $ully represent the obOe%t* class -our 8 public static final Strin%OP 1R.)D*DA-)G 1rovider.E.-ours.ample. )dapting to the Circumstances 0oC that Ce have a Cursor via mana%edTuery:.CR)A-)D*DA-)G 1rovider. manually e. ./G 1rovider.1-.-ours.-+)G 1rovider. you probably shoul %onsi er using SimpleCursorAdapter.-+)"#title#5 D)SCR.E./"#desc#5 CR)A-)D*DA-)"#created#5 M..D. @ou might./ " new Strin%OP 8 1rovider...R.-ours.com Special Creative Commons BY-SA 3.DG 1rovider.n this %ase.. i$ the goal o$ the <uery Cas to return a list $rom Chi%h the user shoul %hoose an item.pose by the tour %ontent provi er &1rovider'. Ce have a%%ess to the <uery results an %an o Chatever Ce Cant Cith them.tra%t ata $rom the Cursor to populate Ci gets or other obOe%ts N -our7iewActivity oes this by populating a -our mo el obOe%t out o$ its Cursor.

han the a apter o$$ to the Ci get.setOnItemClickListener:t$is.ample.-.com Special Creative Commons BY-SA 3.-+)<G new intOP 8android.5 list.>sing a Content Provider SimpleCursorAdapter.$ Subscribe to updates at http://commonsware.5 list.ieC instan%es &-.tourlist*itemG toursCursorG new Strin%OP 81rovider.uery:getIntent:.text?<. an Ce get* %.R.-+)' 5he %orrespon ing i enti$iers o$ -ext7iew Ci gets in the list entry layout that those properties shoul go into &android./G nullG nullG null.5 A$ter e.5 +istAdapter adapter " new SimpleCursor#dapter:t$isG R. here is a $ragment o$ the onCreate:.tourlist*item' 5he %ursor &toursCursor' 5he properties to pull out o$ the %ursor an use $or %on$iguring the list entry .-ours.0 License Edition . -our+istActivity %reates a SimpleCursorAdapter Cith the $olloCing parameters* • 5he a%tivity &or other Context' %reating the a apterP in this %ase.text?' • • • • A$ter that..id.findViewById:android.list.R.set#dapter:adapter.layout. metho -our+istActivity.id.getData:. the -our+istActivity itsel$ 5he i enti$ier $or a layout to be use $or ren ering the list entries &R. Ce put the a apter into the +ist7iew. an getting the Cursor.5 list":+ist7iew. an you7re set N your Ci get Cill shoC the available options. Chi%h gives the user a list o$ tours to %hoose $rom* $rom toursCursor " managed.R.id.=)C-..layout. (or e.e%uting the mana%edTuery:.G 1R.

5o get to the various roCs. to %reate your oCn Ci gets to go into the list. to move to the $irst roC in the result set or last:. as emonstrate earlier in this book.>sing a Content Provider !igure /9< Tour ist)ctivity6 sho4ing a list of tours . you %an use* Cursor • first:. akin to the +ava .terator inter$a%e.oing 8t By Dand >$ %ourse. to move to the last roC in the result set %.com Special Creative Commons BY-SA 3. though./ Subscribe to updates at http://commonsware. as alCays. 5he Cursor inter$a%e is similar in %on%ept to other atabase a%%ess A!.s o$$ering %ursors as obOe%ts. Position instan%es have a built3in notion o$ position. sub%lass SimpleCursorAdapter an overri e %et7iew:.0 License Edition .$ you nee more %ontrol over the vieCs than you %an reasonably a%hieve Cith the sto%k vieC %onstru%tion logi%. you %an alCays o it the 6har Cay9 N pulling ata out o$ the Cursor by han . the evil is in the etails. .

as Cursor obOe%ts are mutable. a Chole host o$ %on ition metho s. et%. you %an use is/ull:. the assumptions regar ing the -our7s Cursor are probably sa$e. or move:. as an e. #o.t roC an etermine i$ there is yet another roC to pro%ess &next:. an isAfter+ast:. /ut.$ this Cere a publi% inter$a%e. let7s e. %et. %etEloat:. 8 return:c. in%lu ing isEirst:. to move to a spe%i$i% in e. returns true i$ it points to another roC a$ter moving. Ia%h metho takes the Kero3base in e.>sing a Content Provider • to move to the ne. false otherCise' next:.5 < void setTitle:Strin% title. .. 5he un erlying assumption o$ the -our is that it is provi e a Cursor Cith only one roC.. 8 c.'.. to move to a relative position plus or minus $rom your %urrent position position:. is+ast:. Gettin! Properties >n%e you have the Cursor positione at a roC o$ interest. you have a variety o$ metho s to retrieve properties $rom that roC.. is6eforeEirst:. this approa%h Coul be s%ary. move-o:. to return your %urrent in • • • • e.. o$ the property you Cant to retrieve. as the opposite to next:.0 Subscribe to updates at http://commonsware. an that Cursor Cill remain pointe to that roC $or the li$espan o$ the -our instan%e. prev:.nt:. here are some %ursor3Crapping a%%essors $rom -our* Strin% getTitle:. 5hat being sai .updateString:?G title. . to move to the previous roC. sin%e the -our mo el is use only Cithin a $airly small appli%ation.com Special Creative Commons BY-SA 3...amine hoC the -our mo el %lass a%%esses its Cursor.5 < %. Cith i$$erent metho s supporting i$$erent types &%etStrin%:.0 License Edition . to test it $or null3ness.$ you Cant to see i$ a given property has a value.ample..getString:?.

5o %ommit those %hanges to the %ontent provi er.>sing a Content Provider Rather than %opying properties into lo%al $iel s. )en%e. on the Cursor to re3e.g. #o. trun%ating strings'. the -our parses the +#>0 an populates Caypoint an Direction mo el obOe%ts. but %hange it as Cell. %et-itle:.'.. Settin! Properties instan%es not only let you rea ata. to persist the %hanges Call reJuery:.. o$ the property to alter an the neC value $or that property.. retrieves the property value at in e. your Cursor is stale N the %ontent provi er might alter the ata you supplie to $it some %ontent3spe%i$i% %onventions &e.g. on a ContentResolver &usually obtaine by an a%tivity via %etContentResolver:. you nee to %all commit2pdates:.nitially. At this point. those %hanges are Oust in the Cursor itsel$.'. supplying the in e. putStrin%:. ?. 5his Corks akin to a #HL 21DA-) statement an takes $our parameters* • • A 2ri representing the %olle%tion &or instan%e' you Cish to up ate A Content7alues &Map3like %olle%tion' instan%e representing the properties you Cish to %hange %. though. though.com Special Creative Commons BY-SA 3. Chi%h is represente in the atabase as a path to a $ile in +#>0 $ormat N $or this. Chi%h pa%kages up the %hange&s' to your roC&s'.nt:.%eption is the route &Caypoints an ire%tions'. put. to re%ap. Cursor .e%ute the original <uery an thereby 6re$resh9 the Cursor7s ren ition o$ the ata. you shoul %all reJuery:. 5he e. .$ you are going to %ontinue using the Cursor.3 Subscribe to updates at http://commonsware.0 License Edition . #imply use the setters &e. @ou %an also %all update:. the $loC is* • • • Call setters to make %hanges Call commit2pdates:. to re$resh the Cursor i$ you Cill %ontinue using it @ou o not ne%essarily nee a Cursor to make %hanges. roun ing o$ $loats. the -our simply hol s onto the Cursor.. an so $orth.

here is a snippet o$ %o e $rom -our)ditActivity to insert a neC tour into the %ontent provi er* if :tour""null.5 c"managed. update:. Cith a %olle%tion 2ri an an array o$ Content7alues stru%tures to populate several roCs at on%e 5he insert:.-ours. to your a%tivity'* -. "se insert:. "se bulk..G values./G nullG null. Cith a %olle%tion 2ri an a Content7alues stru%ture es%ribing the initial set o$ ata to put in the roC 2.-ours.ample. you have tCo options available on the Content1rovider inter$a%e &available through %etContent1rovider:.5 values./-)/-*2R.-+)G tour. 8 Content7alues values"new ContentValues:.1R.com Special Creative Commons BY-SA 3. 5o insert ata into a %ontent provi er.nsert:..uery:urlG -our. as etermine by the %onstraint statement an parameters.=)C-.>sing a Content Provider • A %onstraint statement.insert:1rovider. 5he bulk. to etermine Chi%h roCs shoul be up ate An optional set o$ parameters to bin repla%ing any > that appear there into the %onstraint %lause.nsert:. (ortunately.7 Subscribe to updates at http://commonsware. $un%tioning like a #HL C3)R) %lause.-. %ontent provi ers Coul be astonishingly Ceak i$ you %oul n7t a or remove ata $rom them.C.0 License Edition .5 2ri url"getContent$esol er:. only up ate Chat is there.put:1rovider. metho returns the number o$ %reate roCsP you Coul nee to o a <uery to get ba%k at the ata you Oust inserte . 'ive and Take >$ %ourse. • As Cith a #HL 21DA-) statement. %oul a$$e%t Kero to several roCs..5 %.getTitle:. %ontent provi ers o$$er these abilities as Cell. metho returns a 2ri $or you to use $or $uture operations on that neC obOe%t. (or e.

an %et.. Huite possibly.save*failedG H@@@.isting up ate logi% to a in any a itional ata beyon the title itsel$. An optional set o$ parameters to bin repla%ing any > that appear there into the %onstraint %lause. (or e. via a Cursor. 5o elete one or more roCs $rom the %ontent provi er.0 License Edition .' an reuse our e. to etermine Chi%h roCs shoul be up ate ?. A 2ri representing the %olle%tion &or instan%e' you Cish to up ate 2.5 -oast.com Special Creative Commons BY-SA 3. the rationale is to minimiKe unne%essary ata %opying.5 return5 < < .first:. metho on ContentResolver. #in%e Ce get a 2ri ba%k.=)C-. a property in the %ontent provi er Cill give you the %ontent 2ri $or that parti%ular /L>/. Rather. oes not provi e ire%t a%%ess to binary ata.n this %ase.strin%. the An roi mo el is more aime at supporting su%h hunks o$ ata via their oCn separate %ontent 2ri values. use the delete:.nputStream:. in%lu ing #HLite.>sing a Content Provider c. 8 android.t#G #)xception creatin% tour#G t. all Ce o is populate the title.show:./G nullG null.+o%. 5his Corks akin to a #HL D)+)-) statement an takes three parameters* -.makeText:t$isG R.util. $un%tioning like a #HL C3)R) %lause. @ou %an use %et.e:#-our.5 < catc$ :-$rowable t. A %ontent provi er. like photos. Ce %an turn aroun an get a Cursor on that 2ri &via mana%edTuery:uriG 1R.utputStream:. on your Content1rovider to rea an Crite the binary ata.ample.. the primary use o$ a photo in An roi is to isplay it to the user.9 Subscribe to updates at http://commonsware. )oCever. Be4are of the B +B! /inary large obOe%ts N /L>/s N are supporte in many atabases. %.5 try 8 tour"new Tour:urlG c. A %onstraint statement. there$ore.

>sing a Content Provider 5he .0 License Edition . /y storing the photo in a manner that has its oCn 2ri.pe%tation. 5he e. via a %ontent 2ri to a +!I8.ma%e7iew Ci get %an o Oust that. Subscribe to updates at http://commonsware. is that $eC An roi appli%ations Cill o mu%h more than uploa binary ata an use Ci gets or built3in a%tivities to isplay that ata. presumably. %$.com Special Creative Commons BY-SA 3. you o not nee to %opy ata out o$ the %ontent provi er into some temporary hol ing area Oust to be able to isplay it N Oust use the 2ri.

i$ you Cant your ata to possibly be use by others N $or e. you are buil ing a $ee rea er an you Cant other programs to be able to a%%ess the $ee s you are oCnloa ing an %a%hing N then a %ontent provi er is right $or you. or %onstru%t a 2ri to a spe%i$i% instan%e i$ you knoC the instan%e i enti$ier. until you try using it. !irst6 Some . 5here are many re<uirements o$ a %ontent provi er. in terms o$ metho s to implement an publi% ata members to supply. %$( Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. buil ing an a%tivity an getting vali ation errors $rom the resour%e %ompiler'.issection As Cas is%usse in the previous %hapter. /ut. . you have no great Cay o$ telling i$ you i any o$ it %orre%tly &versus. the %ontent 2ri is the lin%hpin behin a%%essing ata insi e a %ontent provi er.0 License Edition .CHAPTER &) Building a Content Provider /uil ing a %ontent provi er is probably the most %ompli%ate an te ious task in all o$ An roi evelopment. buil ing a %ontent provi er is o$ huge importan%e i$ your appli%ation Cishes to make ata available to other appli%ations. Oust a%%essing the ata ire%tly $rom your a%tivities.$ your appli%ation is keeping its ata solely to itsel$.ample. When using a %ontent provi er. say. all you really nee to knoC is the provi er7s base 2riP $rom there you %an run <ueries as nee e . you may be able to avoi %reating a %ontent provi er. 5hat being sai . An .

5ext6 Some Typing 0e. An roi uses both the %ontent 2ri an the M. >r. Chi%h is the list o$ path segments a$ter the authority an be$ore the instan%e i enti$ier &i$ any'. Chi%h Coul re$er to a pie%e o$ %ontent &i enti$ie as ?]' manage by the sekrits %ontent provi er that is o$ the ata type card/pin. epen ing on situation* • .g. A %olle%tion %ontent 2ri N or. Chi%h is an integer i enti$ying a spe%i$i% pie%e o$ %ontent. . you nee to knoC a bit more about the innar s o$ the %ontent 2ri. .t %an be a single path segment &foo' or a %hain o$ path segments &foo/bar/%oo' as nee e to han le Chatever ata a%%ess s%enarios the %ontent provi er re<uires. the %ombination authority an ata type path N shoul map to a pair o$ M.ample.0 License Edition . Chi%h is the $irst path segment a$ter the s%heme.. 5he ata type path %an be empty. Chi%h Coul re$er to the %olle%tion o$ %ontent hel by Chatever %ontent provi er Cas tie to the sekrits authority &e. . • • • (or e. it %oul be as %omple. A %ontent 2ri has tCo to $our pie%es. in i%ating it is a %ontent 2ri instea o$ a 2ri to a Web resour%e &$ttp!//'. . 5he authority is a uni<ue string i enti$ying the %ontent provi er that han les the %ontent asso%iate Cith this 2ri. A %ontent 2ri Cithout an instan%e i enti$ier re$ers to the %olle%tion o$ %ontent represente by the authority &an . more a%%urately.com Special Creative Commons BY-SA 3.Building a Content Provider When buil ing a %ontent provi er.t may have a ata type path.t alCays has a s%heme &content!//'. Secrets1rovider'.t.MI types %orrespon ing Cith the %ontent your %ontent provi er Cill provi e. i$ the %ontent provi er only han les one type o$ %ontent.MI %$% Subscribe to updates at http://commonsware. Chere provi e . you nee to %ome up Cith some M. as content!//sekrits/card/pin/?]. the ata path'.MI type as Cays to i enti$y %ontent on the evi%e.t alCays has an authority. a %ontent 2ri %oul be as simple as content!//sekrits.t may have an instan%e i enti$ier. though.

so is a %ontent provi er.g.cursor. >ne M. Step K(H Create a Provider Class +ust as an a%tivity an intent re%eiver are both +ava %lasses.. As you saC earlier in this book.ntent to the proper a%tivity &e. 5he %olle%tion M.MI type &though that is not stri%tly re<uire '.. 1. or elete %ontent. you %an $ill in a M. Subscribe to updates at http://commonsware. #o. the big step in %reating a %ontent provi er is %ra$ting its +ava %lass.U. per$orm the servi%es that a %ontent provi er is suppose to o$$er to a%tivities Cishing to %reate.card. usually $or the same values o$ U an F as you use $or the %olle%tion M. up ate. organiKation.ample.Building a Content Provider types. you might use vnd. metho s that.ntent to route the .MI type $or your %olle%tion o$ se%rets. %hoosing as a base %lass either Content1rovider or DatabaseContent1rovider.MI type to %all up a sele%tion a%tivity to pi%k an instan%e out o$ that %olle%tion'. DatabaseContent1rovider o$$ers some e.tra hooks to help Cith %ontent provi ers using #HLite atabases $or storage. rea . )ere7s hoC you e.MI type Cill represent the %olle%tionP the other Cill represent an instan%e. you are responsible $or implementing si. 5he instan%e M.com Special Creative Commons BY-SA 3. $or e.item/F. #o.ten these base %lasses to make up your %ontent provi er.dir/sekrits. Chere U is the name o$ your $irm.dir/F. 5hese map to the 2ri patterns above $or no3i enti$ier an i enti$ier. %$.MI type into an . or proOe%t. an F is a ot3 elimite type name./ on a %olle%tion M.0 License Edition .tla%ency.$ you implement a sub%lass o$ Content1rovider. ContentProvider .MI type shoul be o$ the $orm vnd.U.cursor. respe%tively.CM*AC-. Chereas Content1rovider is more general3purpose. 0ot surprisingly.cursor.MI type shoul be o$ the $orm vnd.pin as the M. Chen %ombine .

.ample.verride %$$ Subscribe to updates at http://commonsware.Building a Content Provider onCreate&' As Cith an a%tivity. i$ you plan on storing your ata in su%h3an 3so ire%tory on an #A %ar . Chen onCreate:.verride public boolean onCreate:. i$ you have reCritten your %ontent provi er su$$i%iently to %ause the ata store to shi$t stru%ture. is %alle . i$ not. .5 < return :db "" null. the $irst time $or a neC release o$ a %ontent provi er that Cas upgra e in3pla%e.openData!ase:getContext:. 8 db":new Data!ase(elper:.ample. you shoul %he%k an see i$ that ire%tory an EML $ile are there an .0 License Edition .$ your %ontent provi er uses #HLite $or storage..G getD!%ame:. . )ere. you %an ete%t to see i$ your tables e. %reate them so the rest o$ your %ontent provi er knoCs they are out there an available $or use. you shoul %he%k to see Chat stru%ture you have noC an a Oust it i$ Chat you have is out o$ ate.n parti%ular.ist by <uerying on the sJlite*master table.. i$ this is the $irst time ever $or the %ontent provi er. #imilarly. an you are not using DatabaseContent1rovider. (or e.t sample appli%ation* 9.com Special Creative Commons BY-SA 3. or i$ this is Oust a normal startup. > false ! true5 While that oesn7t seem all that spe%ial. here is the onCreate:. you %an o Chatever initialiKation you Cant.. 5his is use$ul $or laKy3%reating a table your %ontent provi er Cill nee .G nullG getD!Version:. (or e. the Qmagi%Q is in the private Database3elper obOe%t* private class Database3elper extends ST+ite. Cith an EML $ile serving as a Qtable o$ %ontentsQ. metho $or 1rovider.pen3elper 8 9. here is Chere you shoul laKy3initialiKe your ata store. $rom the 5our. @ou on7t Crite your oCn QinstallerQ program an so have no great Cay o$ etermining i$. the main entry point to a %ontent provi er is onCreate:.

exists:.5 map.5 if :tour.5 db.e%ute some #HL to %reate the table.t#G #2p%radin% databaseG w$ic$ will destroy all old data#. 5hose are poure into the table via insert:.close:. 8 Cursor c"db.name ER.""@.uery:#S)+)C.1 -A6+) . >therCise.S-S tours#. 8 if :f./-)0)RG route -)UD)EA2+.util.M sJlite*master C3)R) type"ZtableZ A/D name"ZtoursZ#G null. 8 Eile tour"new "ile:fG #tour.Z8<Z.get%ame:. %alls. 8 lon% now"System.0 License Edition ..ZZG created .5 map.5 map. then s%an the #A %ar to see i$ Ce %an $in any tours that nee to be loa e .com Special Creative Commons BY-SA 3.5 < 9..put:#title#G f.5 if :sdcard./-)0)RG modified . 8 for :Eile f ! sdcard.Building a Content Provider public void onCreate:ST+iteDatabase db.put:#modified#G now.5 < < < < < < < finally 8 c.currentTime'illis:..get&ath:..5 map.verride public void on)pgrade:ST+iteDatabase dbG int old7ersionG int new7ersion.D)EA2+.insert:#tours#G nullG map.exists:. Ce7re one.5 Content7alues map"new ContentValues:..5 db.+o%.L:#DR.5 Eile sdcard"new "ile:#/sdcard/tourit#. 8 db.5 try 8 if :c..js#.E )U.list"iles:./CR)M)/-G title -)U-G desc -)U.put:#created#G now./-)0)R 1R.. 8 android.raw. Ce e. Ce <uery sJlite*master to see i$ our table is there N i$ it is.isDirectory:.5 < < (irst.5#.5 onCreate:db.put:#route#G tour.count:. %$/ Subscribe to updates at http://commonsware.w:#-our.L:#CR)A-) -A6+) tours :*id .MARF M)F A2-.execS.execS.

Building a Content Provider 5he metho behin this ma ness is %overe in greater etail in Appen i. but you nee to o%ument that $a%t so a%tivities only attempt to <uery you by instan%e 2ri an not using parameters you ele%t not to han le.pe%t. as parameters* • • A 2ri representing the %olle%tion or instan%e being <uerie A Strin%OP representing the list o$ properties that shoul returne be • A Strin% representing Chat amounts to a #HL C3)R) %lause. A. @ou are Cel%ome to ignore some o$ these parameters &e. "se a ST+iteTuery6uilder to %onvert the various parameters into a single #HL statement. As you %an imagine. 5he <uery metho gets. hoCever. (uery&' As one might e. metho implementation shoul be largely boilerplate.t is up to you to a%tually pro%ess sai <uery. Chere Ce %over 5our. the Juery:. (or #HLite3ba%ke storage provi ers. %onstraining Chi%h instan%es shoul be %onsi ere $or the <uery results A Strin%OP representing values to Qpour intoQ the C3)R) %lause. metho is Chere your %ontent provi er gets etails on a <uery some a%tivity Cants to per$orm.. these parameters are aime toCar s people using a #HLite atabase $or storage.t in more etail. . repla%ing any > $oun there A Strin% representing Chat amounts to a #HL .com Special Creative Commons BY-SA 3.RD)R 6F %lause • • @ou are responsible $or interpreting these parameters hoCever they make sense an returning a Cursor that %an be use to iterate over an a%%ess the ata.g. you ele%t not to try to roll your oCn #HL C3)R) %lause parser'.0 License Edition . then use %$0 Subscribe to updates at http://commonsware. the Juery:.

setTa!les:getTa!le%ame:...A to the <uery. 8 order6y"getDefaultSortOrder:.get:?. Ce use the Juery:.Lite.com Special Creative Commons BY-SA 3.G url.ueryBuilder:. metho then returns.set%otification)ri:getContext:. metho on the buil er to get a Cursor $or the results. 8 Jb. insert&' @our insert&' metho Cill re%eive a 2ri representing the %olle%tion an a Content7alues stru%ture Cith the initial ata $or the neC instan%e.5 < else 8 order6y"sort5 < Cursor c"Jb.B#"# B url.5 < Strin% order6y5 if :-ext2tils..verride public Cursor -uery:2ri urlG Strin%OP projectionG Strin% selectionG Strin%OP selectionAr%sG Strin% sort. $rom 1rovider* 9.5 if :isCollection)ri:url.append*here:getIdColumn%ame:.5 Jb.5 < else 8 Jb..get&athSegments:. an returning a 2ri to the neC instan%e.getContent$esol er:. here is Juery:.5 c.0 License Edition .. %$3 Subscribe to updates at http://commonsware.set&ro/ection'ap:getDefault&ro/ection:. on the buil er to a%tually invoke the <uery an give you a Cursor ba%k.. @ou are responsible $or %reating the neC instan%e. (or e.5 return c5 < We %reate a ST+iteTuery6uilder an pour the <uery etails into the buil er. When one. 5he Cursor is Chat your Juery:. $illing in the supplie ata.Building a Content Provider Juery:. Ce nee to a the instan%e .-uery:dbG projectionG selectionG selectionAr%sG nullG nullG order6y. 8 ST+iteTuery6uilder Jb"new S.is+mpty:sort.ample.. 0ote that the <uery %oul be base aroun either a %olle%tion or an instan%e 2ri N in the latter %ase.

contains1ey:col/ame. $rom 1rovider* 9.5 < if :WisCollection)ri:url. 8 if :values.5 if :row. %$7 Subscribe to updates at http://commonsware.0 License Edition .notifyChange:uriG null.ample.insert:getTa!le%ame:.5 < else 8 values"new ContentValues:. 8 lon% row.D"db. the implementation is mostly boilerplate* vali ate that all re<uire values Cere supplie by the a%tivity.with#ppendedId:getContent)ri:...Building a Content Provider . on%e again. on the atabase to a%tually %reate the instan%e.5 < 5he pattern is the same as be$ore* use the provi er parti%ulars plus the ata to be inserte to a%tually o the insertion. so Ce vali ate that by %alling isCollection2ri:.. an %all insert:.verride public 2ri insert:2ri urlG Content7alues initial7alues. "" false.5 < for :Strin% col/ame ! get$e-uiredColumns:. 8 2ri uri"Content2ris. 8 t$row new Illegal#rgument+xception:#2nknown 2R+ # B url.L+xception:#Eailed to insert row into # B url.5 return uri5 < t$row new S. 8 values"new ContentValues:initial7alues.$ this is a #HLite3ba%ke %ontent provi er.G row.getContent$esol er:. here is insert:.D.D & @.5 < < populateDefaultValues:values. (or e.com Special Creative Commons BY-SA 3.G get%ullColumn(ack:. >$ note* • @ou %an only insert into a %olle%tion 2ri.5 row.G values.D5 Content7alues values5 if :initial7aluesW"null.. merge your oCn notion o$ e$ault values Cith the supplie ata. 8 t$row new Illegal#rgument+xception:#Missin% column! #Bcol/ame.5 getContext:.

0 License Edition . metho gets the 2ri o$ the instan%e or %olle%tion to %hange. unless you7re using #HLite $or storage.update:getTa!le%ame:.' $or %olumns not supplie in the insert:..5 < else 8 Strin% se%ment"url.getContent$esol er:. then repla%e those instan%es7 %urrent property values Cith the ones supplie . you %an pretty mu%h pass all the parameters you re%eive to the update:. (or e. @our responsibility is to i enti$y the instan%e&s' to be mo i$ie &base on the 2ri an C3)R) %lause'. %all Cill vary slightly epen ing on Chether you are up ating one instan%e or several. %all an not automati%ally han le by the #HLite table e$inition • update&' @our update:. $rom 1rovider* 9.verride public int update:2ri urlG Content7alues valuesG Strin% w$ereG Strin%OP w$ereAr%s. 5his Cill be annoying.ample. so Ce iterate over those an %on$irm our supplie values %over the re<uirements 5he provi er is also responsible $or $illing in any e$ault values &populateDefault7alues:.5 count"db . 8 int count5 if :isCollection)ri:url. an a Strin%OP Cith parameters to use to repla%e > $oun in the C3)R) %lause..'. here is update:. a Content7alues stru%ture Cith the neC values to apply.get&athSegments:.Z ! ##.B#"# B se%ment B :W-ext2tils.. %all to the atabase. a #tring $or a #HL C3)R) %lause.5 < getContext:. > # A/D :# B w$ere B Z.G valuesG getIdColumn%ame:.notifyChange:urlG null.get:?. 5hen.com Special Creative Commons BY-SA 3. 8 count"db.G w$ereAr%s.is+mpty:w$ere.Building a Content Provider • 5he provi er also knoCs Chat %olumns are re<uire &%etReJuiredColumns:.5 %$9 Subscribe to updates at http://commonsware.. though the update:.update:getTa!le%ame:.G valuesG w$ereG w$ereAr%s.

5 < %/.$ the a%tivity is eleting a single instan%e. delete&' As Cith update:. (or e.0 License Edition .$ Ce are up ating a single instan%e.parseLong:se%ment.delete:getTa!le%ame:.get&athSegments:.n this %ase. Oust per$orm the up ate.G w$ereAr%s.delete:getTa!le%ame:.. Subscribe to updates at http://commonsware. using the C3)R) %lause to %onstrain Chi%h ones to elete. Ce nee to a a %onstraint to the C3)R) %lause to only up ate $or the re<ueste roC.is+mpty:w$ere. on the atabase. $rom 1rovider* 9. up ates %an either be to a spe%i$i% instan%e or applie a%ross the entire %olle%tion. though. . > # A/D :# B w$ere B Z.G w$ereG w$ereAr%s.. /ut. . delete:.com Special Creative Commons BY-SA 3. As Cith update:.Building a Content Provider return count5 < .. so Ce %he%k the 2ri &isCollection2ri:. the 2ri shoul represent that instan%e an the C3)R) %lause may be null. re%eives a 2ri representing the instan%e or %olle%tion to Cork Cith an a C3)R) %lause an parameters.G getIdColumn%ame:. the a%tivity might be re<uesting to elete an open3en e set o$ instan%es.ample.' an . 8 int count5 lon% row.verride public int delete:2ri urlG Strin% w$ereG Strin%OP w$ereAr%s.get:?. 8 count"db.5 row.B#"# B se%ment B :W-ext2tils.5 < else 8 Strin% se%ment"url. this is simple i$ you are using #HLite $or atabase storage &sense a themeD'.d"@5 if :isCollection)ri:url. @ou %an let it han le the i iosyn%rasies o$ parsing an applying the C3)R) %lause N all you have to o is %all delete:. i$ it is an up ate $or the %olle%tion.Z ! ##..d"+on%.5 count"db . here is delete:.

Building a Content Provider

getContext:;.getContent$esol er:;.notifyChange:urlG null;5 return count5 <

5his is almost a %lone o$ the update:; implementation es%ribe above N either elete a subset o$ the entire %olle%tion or elete a single instan%e &i$ it also satis$ies the supplie C3)R) %lause'.

getType&'
5he last metho you nee returns the M.MI type %olle%tion or an instan%e an return the %orrespon to implement is %et-ype:;. 5his takes a 2ri an asso%iate Cith that 2ri. 5he 2ri %oul be a 2riP you nee to etermine Chi%h Cas provi e ing M.MI type.

(or e;ample, here is %et-ype:; $rom 1rovider*
9,verride public Strin% getType:2ri url; 8 if :isCollection)ri:url;; 8 return:getCollectionType:;;5 < return:getSingleType:;;5 <

As you %an see, most o$ the logi% elegates to private %etCollection-ype:; an %etSin%le-ype:; metho s*
private Strin% getCollectionType:; 8 return:#vnd.android.cursor.dir/vnd.commonsware.tour#;5 < private Strin% getSingleType:; 8 return:#vnd.android.cursor.item/vnd.commonsware.tour#;5 <

%/(
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Building a Content Provider

D t 5 seContentProvider
.$ you Cant to use DatabaseContent1rovider as a base %lass, here is Chat you nee to o*
• •

@ou still nee %et-ype:; as es%ribe in the pre%e ing se%tion @ou may ele%t to overri e onCreate:; $or your oCn initialiKation, but be sure to %hain upCar to the super%lass &super.onCreate:;' @ou may ele%t to overri e up%radeDatabases:; to rebuil your tables i$ your atabase s%hema has %hange @ou nee to implement Juery.nternal:;, insert.nternal:;, update.nternal:;, an delete.nternal:; mu%h as es%ribe above $or Juery:;, insert:;, update:;, an delete:; respe%tively

Step K%H Supply a >ri
@ou also nee to a a publi% stati% member...someChere, %ontaining the 2ri $or ea%h %olle%tion your %ontent provi er supports. 5ypi%ally, this is a publi% stati% $inal 2ri put on the %ontent provi er %lass itsel$*
public static final 2ri C,/-)/-*2R." 2ri.parse:#content!//com.commonsware.android.tourit.1rovider/tours#;5

@ou may Cish to use the same namespa%e $or the %ontent 2ri that you use $or your +ava %lasses, to re u%e the %han%e o$ %ollision Cith others.

Step K,H .eclare the Properties
Remember those properties you re$eren%e Chen you Cere using a %ontent provi er, in the previous %hapterD Well, you nee to have those too $or your oCn %ontent provi er. #pe%i$i%ally, you Cant a publi% stati% %lass implementing 6aseColumns that %ontains your property names, su%h as this e;ample $rom 1rovider*

%/%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Building a Content Provider

public static final class -ours implements 6aseColumns 8 public static final 2ri C,/-)/-*2R. "2ri.parse:#content!//com.commonsware.android.tourit.1rovider/tours#;5 public static final Strin% D)EA2+-*S,R-*,RD)R"#title#5 public static final Strin% .D"#*id#5 public static final Strin% -.-+)"#title#5 public static final Strin% D)SCR.1-.,/"#desc#5 public static final Strin% CR)A-)D*DA-)"#created#5 public static final Strin% M,D.E.)D*DA-)"#modified#5 public static final Strin% R,2-)"#route#5 <

.$ you are using #HLite as a ata store, the values $or the property name %onstants shoul be the %orrespon ing %olumn name in the table, so you %an Oust pass the proOe%tion &array o$ properties' to #HLite on a Juery:;, or pass the Content7alues on an insert:; or update:;. 0ote that nothing in here stipulates the types o$ the properties. 5hey %oul be strings, integers, or Chatever. 5he biggest limitation is Chat a Cursor %an provi e a%%ess to via its property getters. 5he $a%t that there is nothing in %o e that en$or%es type sa$ety means you shoul o%ument the property types Cell, so people attempting to use your %ontent provi er knoC Chat they %an e;pe%t.

Step K$H >pdate the *anifest
5he glue tying the %ontent provi er implementation to the rest o$ your appli%ation resi es in your AndroidManifest.xml $ile. #imply a a <provider& element as a %hil o$ the <application& element*
<provider android!name"#.1rovider# android!aut$orities"#com.commonsware.android.tourit.1rovider# /&

5he android!name property is the name o$ the %ontent provi er %lass, Cith a lea ing ot to in i%ate it is in the sto%k namespa%e $or this appli%ation7s %lasses &Oust like you use Cith a%tivities'. 5he android!aut$orities property shoul be a semi%olon3 elimite list o$ the authority values supporte by the %ontent provi er. Re%all, $rom earlier
%/,
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Building a Content Provider

in this %hapter, that ea%h %ontent 2ri is ma e up o$ a s%heme, authority, ata type path, an instan%e i enti$ier. Ia%h authority $rom ea%h C,/-)/-*2R. value shoul be in%lu e in the android!aut$orities list. 0oC, Chen An roi en%ounters a %ontent 2ri, it %an si$t through the provi ers registere through mani$ests to $in a mat%hing authority. 5hat tells An roi Chi%h appli%ation an %lass implements the %ontent provi er, an $rom there An roi %an bri ge betCeen the %alling a%tivity an the %ontent provi er being %alle .

5otify"+n"Change Support
An optional $eature your %ontent provi er to its %lients is noti$y3on3%hange support. 5his means that your %ontent provi er Cill let %lients knoC i$ the ata $or a given %ontent 2ri %hanges. (or e;ample, suppose you have %reate a %ontent provi er that retrieves R## an Atom $ee s $rom the .nternet base on the user7s $ee subs%riptions &via >!ML, perhaps'. 5he %ontent provi er o$$ers rea 3only a%%ess to the %ontents o$ the $ee s, Cith an eye toCar s several appli%ations on the phone using those $ee s versus everyone implementing their oCn $ee poll3$et%h3 an 3%a%he system. @ou have also implemente a servi%e that Cill get up ates to those $ee s asyn%hronously, up ating the un erlying ata store. @our %ontent provi er %oul alert appli%ations using the $ee s that su%h3an 3so $ee Cas up ate , so appli%ations using that spe%i$i% $ee %an re$resh an get the latest ata. >n the %ontent provi er si e, to o this, %all notifyC$an%e:; on your ContentResolver instan%e &available in your %ontent provi er via %etContext:;.%etContentResolver:;'. 5his takes tCo parameters* the 2ri o$ the pie%e o$ %ontent that %hange an the Content,bserver that initiate the %hange. .n many %ases, the latter Cill be nullP a non3null value simply means that observer Cill not be noti$ie o$ its oCn %hanges. >n the %ontent

%onsumer si e, an a%tivity %an %all re%isterContent,bserver:; on its ContentResolver &via %etContentResolver:;'.
%/$
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Building a Content Provider

5his ties a Content,bserver instan%e to a supplie 2ri N the observer Cill be noti$ie Chenever notifyC$an%e:; is %alle $or that spe%i$i% 2ri. When the %onsumer is one Cith the 2ri, unre%isterContent,bserver:; releases the %onne%tion.

%//
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

CHAPTER &*

2equesting and 2equiring Permissions

.n the late -1107s, a Cave o$ viruses sprea through the .nternet, elivere via email, using %onta%t in$ormation %ulle $rom Mi%roso$t >utlook. A virus Coul simply email %opies o$ itsel$ to ea%h o$ the >utlook %onta%ts that ha an email a ress. 5his Cas possible be%ause, at the time, >utlook i not take any steps to prote%t ata $rom programs using the >utlook A!., sin%e that A!. Cas esigne $or or inary evelopers, not virus authors. 0oCa ays, many appli%ations that hol onto %onta%t ata se%ure that ata by re<uiring that a user e;pli%itly grant rights $or other programs to a%%ess the %onta%t in$ormation. 5hose rights %oul be grante on a %ase3by3%ase basis or a on%e at install time. An roi is no i$$erent, in that it re<uires permissions $or appli%ations to rea or Crite %onta%t ata. An roi 7s permission system is use$ul Cell beyon %onta%t ata, an $or %ontent provi ers an servi%es beyon those supplie by the An roi $rameCork. @ou, as an An roi eveloper, Cill $re<uently nee to ensure your appli%ations have the appropriate permissions to o Chat you Cant to o Cith other appli%ations7 ata. @ou may also ele%t to re<uire permissions $or other appli%ations to use your ata or servi%es, i$ you make those available to other An roi %omponents. 5his %hapter %overs hoC to a%%omplish both these en s.
%/3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

2equesting and 2equiring Permissions

*other6 *ay 8:
Re<uesting the use o$ other appli%ations7 ata or servi%es re<uires the uses( permission element to be a e to your AndroidManifest.xml $ile. @our mani$est may have Kero or more uses(permission elements, all as ire%t %hil ren o$ the root manifest element. 5he uses(permission element takes a single attribute, android!name, Chi%h is the name o$ the permission your appli%ation re<uires*
<uses(permission android!name"#android.permission.ACC)SS*+,CA-.,/# /&

5he sto%k system permissions all begin Cith android.permission an are liste in the o%umentation $or Manifest.permission in the online An roi o%umentation. 5hir 3party appli%ations may have their oCn permissions, Chi%h hope$ully they have o%umente $or you. !ermissions are %on$irme at the time the appli%ation is installe N the user Cill be prompte to %on$irm it is >F $or your appli%ation to o Chat the permission %alls $or. 5his prompt is not available in the %urrent emulator, hoCever. .$ you o not have the esire permission an try to o something that nee s it, you may get a Security)xception in$orming you o$ the missing permission, but this is not a guarantee N $ailures may %ome in other $orms, epen ing on i$ something else is %at%hing an trying to han le that e;%eption. 5o see the e$$e%ts o$ permissions, go ba%k to the 1ick e;ample proOe%t. .$ you look at the AndroidManifest.xml $ile, you Cill see it re<uests the R)AD*C,/-AC-S permission. 5his is Chat alloCs you to vieC the %onta%t in$ormation. Comment out the uses(permission element in the mani$est, re%ompile, an try out the neC version in the emulator. @ou shoul get a Security)xception. >AT.* you may nee to restart the emulator, i$ you Cere using the 1ickDemo be$ore uring this same emulator session.

%/7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

0 License Edition .pense. is to se%ure your oCn appli%ation. you put %ontent provi ers or servi%es in your appli%ation. se%urity is mu%h more important. %/9 Subscribe to updates at http://commonsware.$. you Cill Cant to implement 6inboun 9 se%urity to %ontrol Chi%h appli%ations %an o Chat Cith the ata. Chere you re<uest permission to use resour%es o$ other appli%ations. Chi%h only stores bi%y%le tours N se%urity is less an issue. but rather about priva%y o$ the user7s in$ormation or use o$ servi%es that might in%ur e. your appli%ation stores private ata. . .t.$ your appli%ation is merely a%tivities an intent re%eivers. 5hat is Chere the sto%k permissions $or built3in An roi appli%ations are $o%use N %an you rea or mo i$y %onta%ts.com Special Creative Commons BY-SA 3.$. o$ %ourse.2equesting and 2equiring Permissions !igure 0. 0ote that the issue here is less about Chether other appli%ations might 6mess up9 your ata. su%h as me i%al in$ormation. . et%.< ) security exception Dalt! Who 'oes There: 5he other si e o$ the %oin. se%urity may be Oust an 6outboun 9 thing. on the other han . %an you sen #M#.$ your appli%ation oes not store in$ormation that might be %onsi ere private N su%h as 5our. . on the other han .

. A label $or the permission* something short that Coul un erstan able by users ?. >n%e again. 5here are three pie%es o$ in$ormation you nee to supply* -. you shoul use your appli%ation7s +ava namespa%e as a pre$i.2equesting and 2equiring Permissions 5he $irst step to se%uring your oCn appli%ation using permissions is to e%lare sai permissions. it in i%ates that it is a possible permissionP your appli%ation must still $lag se%urity violations as they o%%ur. all as ire%t %hil ren o$ the root manifest element. be 2.tla%ency. A es%ription $or the permission* something a Cee bit longer that is un erstan able by your users <permission android!name"#vnd. servi%es. an intent re%eivers %an all e%lare an attribute name android!permission. you a permission elements. Chose value is the name o$ the permission that is re<uire to a%%ess those items* <activity android!name"#. instea o$ uses(permission. you %an have Kero or more permission elements.n this %ase.est 5here are tCo Cays $or your appli%ation to en$or%e permissions.0 License Edition .orcin! Permissions vi the % ni. En. 5o keep your permissions $rom %olli ing Cith those $rom other appli%ations.S))*S)MR. i%tating Chere an un er Chat %ir%umstan%es they are re<uire . 5he easier one is to in i%ate in the mani$est Chere permissions are re<uire .com Special Creative Commons BY-SA 3.SekritApp# android!label"#-op Sekrit# %0.-S# android!label"#9strin%/see*sekrits*label# android!description"#9strin%/see*sekrits*description# /& 5his oes not en$or%e the permission. Subscribe to updates at http://commonsware. Ae%laring a permission is slightly more %ompli%ate than using a permission. A%tivities. on%e again in the AndroidManifest.sekrits. 5he symboli% name o$ the permission. Rather.xml $ile.

M.ntent re%eivers ignore messages sent via broadcast.Sekrit1rovider# android!read1ermission"#vnd.-S# /& .0 License Edition .n this %ase. i$ your servi%e implements separate rea an Crite c$eckCallin%1ermission:.sekrits.+A2/C3)R# /& </intent(filter& </activity& >nly appli%ations that have re<ueste your in i%ate permission Cill be able to a%%ess the se%ure %omponent.MA.tla.ample. up ate.S))*S)MR.Sekrit1rovider# android!aut$orities"#vnd../# /& <cate%ory android!name"#android. .tla./*D)/. read1ermission %ontrols a%%ess to <uerying the %ontent provi er.sekrits.D*S)MR.intent.com Special Creative Commons BY-SA 3.orcin! Permissions Else#here .action../*0RA/-)D or on Chether the %aller has the permission you spe%i$ie . En.tla%ency.ntent:.tla. Chile write1ermission %ontrols a%%ess to insert.S))*S)MR.2equesting and 2equiring Permissions android!permission"#vnd.n this %ase.n your %o e.SS.cate%ory.-S# android!write1ermission"#vnd. 6a%%ess9 means* • • A%tivities %annot be starte Cithout the permission #ervi%es %annot be starte . you have tCo a @our servi%es %an %he%k itional Cays to en$or%e permissions.sekrits. (or e. stoppe . or boun to an a%tivity Cithout the permission . permissions on a per3%all basis via 5his returns 1)RM. or elete ata in the %ontent provi er.-S#& <intent(filter& <action android!name"#android.. 1)RM.sekrits.)D epen ing %0( Subscribe to updates at http://commonsware.SS.intent. unless the sen er has the permission istin%t attributes* read1ermission an • Content provi ers o$$er tCo write1ermission* <provider android!name"#.

lest they get %on$use by the <uestion pose by the phone an ele%t to not install or use your appli%ation. >therCise. %0% Subscribe to updates at http://commonsware. the An roi subsystem presumably in%lu es the R)C). Also. (urthermore..ocuments: 5here is no automati% is%overy o$ permissions at %ompile timeP all permission $ailures o%%ur at runtime.s.ntent:. (or e.com Special Creative Commons BY-SA 3. it is important that you o%ument the permissions re<uire $or your publi% A!. you %an in%lu e a permission Chen you %all broadcast. you %oul get the e$$e%t o$ read1ermission an write1ermission in %o e by %he%king those metho s $or the permissions you nee $rom +ava.7)*SMS permission Chen it broa %asts that an #M# message has arrive N this Cill restri%t the re%eivers o$ that intent to be only those authoriKe to re%eive #M# messages. you shoul e.pe%t. servi%es. 5his means that eligible re%eivers must hol that permissionP those Cithout the permission are ineligible to re%eive it.pe%t that users o$ your appli%ation Cill be prompte to %on$irm any permissions your appli%ation says it nee s. )en%e. the programmers attempting to inter$a%e Cith your appli%ation Cill have to $in out the permission rules by trial an error. )en%e. an a%tivities inten e $or laun%hing $rom other a%tivities.2equesting and 2equiring Permissions metho s.ample. in%lu ing %ontent provi ers. you nee to o%ument $or your users Chat they shoul e.0 License Edition . *ay 8 See -our .

/oth %hapters Cill analyKe the Mail/uKK sample appli%ation &Mail6u'''. 5his %hapter %overs hoC you %an %reate your oCn servi%esP the ne. either on3 eman or on a state interval. Running $or a long time isn7t Cithout its %osts.nternet $or R##UAtom $ee up ates. to see i$ neC messages have arrive . Mail6u''Service polls a supplie email a%%ount.0 License Edition . though. %0. #ervi%es are %reate Chen manually starte &via an A!.t %hapter %overs hoC you %an use su%h servi%es $rom your a%tivities or other %onte. polling the . %all' or Chen some a%tivity tries %onne%ting to the servi%e via inter3pro%ess %ommuni%ation &.!C'. Subscribe to updates at http://commonsware. at Chi%h it Cill post a /otification &as es%ribe in the %hapter on noti$i%ations'. so servi%es nee to be %are$ul not to use too mu%h C!" or keep ra ios a%tive too mu%h o$ the time.CHAPTER &- Creating a Service As note previously. I. #ervi%es Cill live until no longer nee e an i$ RAM nee s to be re%laime . An roi servi%es are $or long3running pro%esses that may nee to keep running even Chen e%ouple $rom any a%tivity.amples in%lu e playing musi% even i$ the QplayerQ a%tivity gets garbage3%olle%te .ts. lest the servi%e %ause the evi%e7s battery to get use up too <ui%kly. an maintaining an online %hat %onne%tion even i$ the %hat %lient loses $o%us ue to an in%oming phone %all.com Special Creative Commons BY-SA 3. Cith this %hapter $o%using mostly on the Mail6u''Service implementation.

.. +ust as a%tivities have onCreate:.ten the Service %lass.P onStart:. an kin.. When neC messages arrive. Service implementations %an overri e three i$$erent li$e%y%le metho s* -. on1ause:.Creating a Service 'etting BuLLed 5he Mail/uKK appli%ation is an email monitoring appli%ation. in our %ase Cith our oCn Mail6u''Service sub%lass. an Crite emails is le$t as an Service 4ith Class Creating a servi%e implementation shares many %hara%teristi%s Cith buil ing an a%tivity. the $irst step in %reating a servi%e is to e. overri e some li$e%y%le metho s. 5he a%tivity alloCs you to spe%i$y an email a%%ount to monitorP the servi%e oes the a%tual monitoring. versus being impli%itly starte as the result o$ an .0 License Edition . onStart:.t %hapter' ?.. Chi%h is %alle as the servi%e is being shut oCn Common startup an shut oCn logi% shoul go in onCreate:. @ou inherit $rom an An roi 3supplie base %lass.er%ise $or the rea er. onDestroy:. is mostly i$ your servi%e nee s ata passe into it &via the supplie 6undle' $rom the starting pro%ess an you on7t Cish to use . (or e. an onDestroy:. metho $or Mail6u''Service* %0$ Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. as Cith servi%es. #o. here is the onCreate:.!C. the servi%e noti$ies the user. an hook the servi%e into the system via the mani$est. Chi%h is %alle Chen a servi%e is manually starte by some other pro%ess. %ombining an a%tivity an a servi%e. is %alle pro%ess is %reate Chen the servi%e 2. Chi%h.ample. onResume:.!C re<uest & is%usse more in the ne. !rovi ing an appli%ation to a%tually rea e. onCreate:.

metho * private void setupTimer:. the <ueue alloCs us to o the a%tual polling $or neC messages in a separate threa than those use $or either the perio i% timer or the in%oming . 8 // just end t$e back%round t$read < < <. so An roi %an o any setup Cork it nee s to have one.5 < else if :eventW"S32-D.0 License Edition .5 setupTimer:. 8 if :get&ollState:.QS@@@@5 task"new TimerTask:. 8 -$read. 0e.start:. 8 check#ccount:..verride public void onCreate:.++.poll:.Creating a Service 9.sleep:?@@@. looking $or neC events.com Special Creative Commons BY-SA 3. 8 event"Jueue.5 int poll1eriod"settin%s. 8 try 8 Strin% event"null5 w$ile :eventW"S32-D.5 < < < catc$ :-$rowable t.5 < (irst. 5he onCreate:.5 back%round"new Thread:new $unna!le:. Ce set up a ba%kgroun threa to monitor a Concurrent+inkedTueue on%e every se%on . 8 super.C/.!C metho %alls $rom the Mail6u'' a%tivity.C/. 8 S$ared1references settin%s"get&refs:. 8 check#ccountImpl:. 8 public void run:.5 if :event""1.5 back%round.getInt:#poll1eriod#G L.5 < <5 %0/ Subscribe to updates at http://commonsware.onCreate:. Ce %hain upCar to the super%lass. As Ce7ll see. 8 public void run:. metho Craps up by %alling a private setup-imer:.t.

Ce shut oCn the timer i$ it Cas alrea y starte .5 < else if :taskW"null. .5 Jueue.cancel:. . an Ce7ll $ill in the $ull implementation in the ne. Chi%h is the lin%hpin behin the . Ce set up a -imer-ask to post a 1. metho is mu%h simpler* 9. Ia%h servi%e %00 Subscribe to updates at http://commonsware.5 timer.Creating a Service < timer. When 8PC )ttacks! #ervi%es Cill ten to o$$er inter3pro%ess %ommuni%ation &. in a ition to %haining upCar to the super%lass $or any An roi internal bookkeeping that might be nee e . 8 task. .!C me%hanism.com Special Creative Commons BY-SA 3.schedule#t"ixed$ate:taskG poll1eriodG poll1eriod.onDestroy:.6inder.$ Ce are not suppose to be perio i%ally %he%king $or message. but setup-imer:. Ce Oust shut oCn the timer an ba%kgroun threa ..5 task"null5 < 5his %he%ks to see i$ Ce7re suppose to be perio i%ally %he%king $or neC messages or not. Oust have this metho return null $or noC. e.++ message on our <ueue. .C/..cancel:. gets %alle not only $rom onCreate:. though. 5his may seem super$luous. but Chen the perio i%3%he%k status %hanges. 8 super. 5he onDestroy:. 5his metho returns an . your servi%e also nee s to implement on6ind:.add:S32-D.5 < )ere. an set up that task to be invoke base on an a%tivity3supplie perio .$ you7re %reating a servi%e %lass Chile rea ing this %hapter.verride public void onDestroy:.0 License Edition .t se%tion.presse in minutes.$ Ce are.!C' as a means o$ intera%ting Cith a%tivities or other An roi %omponents.n a ition to those li$e%y%le metho s.

!C me%hanisms like C>M. <'. are %riti%al.5 boolean is+na!led:.$ you have use . An . on the other han . (or e. let7s take a look at A.AL an . is e.. . you list the metho s you are making available. as Cith a +ava inter$a%e. C>R/A.android.AL $or the Mail6u''Service* packa%e com.Creating a Service e%lares Chat metho s it is making available over .' %03 Subscribe to updates at http://commonsware. 3rite the AID= .AL.AL spells out the publi% .!CP those metho s are then available $or other %omponents to %all. 5he i$$eren%es.!C.!C inter$a%e. Cith An roi han ling all the messy etails involve Cith making metho %alls a%ross %omponent or pro%ess boun aries. looks a lot like a +ava inter$a%e. 5he guts o$ this.service5 // Declare t$e interface.6u'' 8 void check%ow:. boolean.com Special Creative Commons BY-SA 3. not every +ava type %an be use as a parameter.. A. you e%lare a pa%kage at the top. double.nter$a%e Aes%ription Language. you Cill re%ogniKe the notion o$ . though. As Cith a +ava inter$a%e.0 License Edition . With that in min . (irst. an An roi supplies tools to buil the %lient an server si e o$ that inter$a%e.5 void ena!le:in boolean enabled.ample. $rom the stan point o$ the eveloper.presse in A. interface .AL. here is the A. the metho s are Crappe in an inter$a%e e%laration &interface .6u'' 8 . float.commonsware.5 < As Cith a +ava inter$a%e.. et%. or the like.AL* the An roi . A.ALs are $re<uently Critten in a Qlanguage3neutralQ synta. @our %hoi%es are* • !rimitive values &int.

int' %an only be inP Ce in%lu e in $or the A. the aidl utility $rom the An roi #AF Cill translate your A.g.util' Any other A. or inout. import com. !rimitives &e.alues that are out or inout %an be %hange by the servi%e an those %hanges Cill be propagate ba%k to the %lient.Somet$in%'.commonsware.android.%eptions.AL3 e$ine inter$a%es Any +ava %lasses that implement the 1arcelable inter$a%e.n the %ase o$ the latter tCo %ategories.0 License Edition . Also. 5his is true even i$ these %lasses are in your oCn pa%kage N you have to import them anyCay. or by routing the stub implementation to other metho s you have alrea y Critten.g.. . you %annot throC any e. 5he me%hani%s o$ this are $airly straight$orCar * %07 Subscribe to updates at http://commonsware. out. you nee to in%lu e import statements re$eren%ing the names o$ the %lasses or inter$a%es that you are using &e.AL3%reate server stub. Oust $or illustration purposes.%eptions in your %o e. @ou Cill nee to %at%h all e. parameters %an be %lassi$ie as in.t. Implement the Inter. an return $ailure in i%ations some other Cay &e.AI or via Ant. eal Cith them.g. error %o e return values'. ce 8iven the A. noC you nee to implement the servi%e. Chi%h is An roi 7s $lavor o$ serialiKation &see beloC' . 0e.aidl e..AL into a server stub an a %lient pro. either via an . 0ame your A.tension an pla%e them in the proper ire%tory base on the pa%kage name. either ire%tly in the stub. When you buil your proOe%t.AL $iles Cith the .Creating a Service • • • • Strin% an C$arSeJuence +ist an Map &$rom java.y.com Special Creative Commons BY-SA 3..AL $or enable:..

Stub binder"new .putBoolean:#enabled#G enabled.com Special Creative Commons BY-SA 3.5 < private boolean get&ollState:.5 editor.6u''.5 < public boolean is+na!led:.0 License Edition .5 < public void ena!le:boolean enabled.add:1. • .5 • pops a 1.AL Return this private instan%e $rom your on6ind:.Stub' . 8 return:get&ollState:. %09 Subscribe to updates at http://commonsware.mplement metho s mat%hing up Cith ea%h o$ the metho s you pla%e in the A.)ditor editor"settin%s.6u''..commit:. 8 S$ared1references settin%s"get&refs:.++.AL3generate .Stub instan%e* private final . 8 S$ared1references settin%s"get&refs:.getBoolean:#enabled#G false. the stub %alls %orrespon ing metho s on the servi%e itsel$. 8 check#ccount:..Stu!:. so our ba%kgroun threa %an poll the mail server c$eckAccount:.5 < private void ena!le&oll:boolean enabled.5 editor.Stub %lass &e. 8 public void check%ow:.ample.5 S$ared1references..6u''.5 < <5 . 8 ena!le&oll:enabled.edit:.++ message on our <ueue. 5hose metho s are shoCn beloC* private void check#ccount:.5 < return:settin%s.5 setupTimer:.Creating a Service • Create a private instan%e o$ the A. 8 Jueue.g. metho Service sub%lass in the • (or e.6u''. here is the .n this %ase.

ample.android. 5hat is simply a matter o$ a ing a service element as a %hil o$ the application element. Cere to ire%tly %he%k the mail server itsel$. enable1oll:. the a%tivity %alling c$eckAccount:. an so the %aller is blo%ke until the .estiny (inally.t runs. your servi%es nee to be <ui%k about their Cork.action.intent.xml $ile.!C %alls are syn%hronous. (or e./# /& <cate%ory android!name"#android. • simply returns the pre$eren%e up ate by 0ote that A. *anifest .com/apk/res/android# packa%e"#com.mpl:.Creating a Service • up ates our pre$eren%es so Ce knoC to start or stop polling Chen the servi%e ne. then %alls setup-imer:. instea o$ using the ba%kgroun <ueue. putting the real c$eckAccount:.!C metho returns.0 License Edition . Subscribe to updates at http://commonsware.service#& <application& <activity android!name"#. here is the AndroidManifest.Mail6u''Service#' to re$eren%e our %lass. Cork &c$eckAccount.Mail6u''Service# /& </application& </manifest& #in%e the servi%e %lass is in the same +ava namespa%e as everything else in this appli%ation. $or it to be re%ogniKe as an available servi%e $or use.' in a <ueue3base ba%kgroun threa provi es $or a %leaner user e. %3. %et1ollState:.AL .+A2/C3)R# /& </intent(filter& </activity& <service android!name"#. Ce %an use the shorthan ot3notation &#.com Special Creative Commons BY-SA 3.cate%ory.$ c$eckAccount:.commonsware.Mail6u''# android!label"#Mail6u''#& <intent(filter& <action android!name"#android.MA. #in%e that takes a noti%eable amount o$ time.intent.xml $ile $or Mail/uKK* <manifest xmlns!android"#$ttp!//sc$emas. you nee to a the servi%e to your AndroidManifest. . provi ing android!name to re$eren%e your servi%e %lass. to start or stop the polling enable1oll:. )en%e.perien%e. Coul be $roKen until the mail server respon e .android.

com Special Creative Commons BY-SA 3. a an android!permission attribute naming the permission you are man ating N see the %hapter on permissions $or more etails.Creating a Service . %3( Subscribe to updates at http://commonsware. servi%es %an either be lo%al or remote. Lo%al servi%es run in the same pro%ess as the laun%hing a%tivityP remote servi%es run in their oCn pro%ess.0 License Edition . WhereAs the 2emote: .$ you Cish to re<uire some permission o$ those Cho Cish to start or bin to the servi%e. A etaile is%ussion o$ remote servi%es Cill be a e to a $uture e ition o$ this book.n An roi .

com Special Creative Commons BY-SA 3.0 License Edition .Subscribe to updates at http://commonsware.

intent re%eivers that are not part o$ an a%tivity'. the a%tivity looks like this* %3. an another button to %he%k right noC $or neC messages. a button to push the a%%ount in$ormation to the servi%e.'. a %he%kbo. in i%ating you no longer nee the servi%e.n this %hapter. 0otably. server.AL inter$a%e $or the servi%e. sin%e those Cill get garbage %olle%te imme iately a$ter ea%h instan%e pro%esses one in%oming .0 License Edition . %ontent provi ers.ntent. 5his in%lu es a%tivities. 5he Mail/uKK a%tivity provi es $iel s $or the a%%ount in$ormation &server type. et%. you %an release the inter$a%e.e.. Subscribe to updates at http://commonsware. .CHAPTER &/ 8nvoking a Service #ervi%es %an be use by any appli%ation %omponent that Qhangs aroun Q $or a reasonable perio o$ time. When one. 5o use a servi%e. you nee to get an instan%e o$ the A. When run. to toggle Chether polling $or neC mail shoul go on. then %all metho s on that inter$a%e as i$ it Cere a lo%al obOe%t.com Special Creative Commons BY-SA 3. an other servi%es. it oes not in%lu e pure intent re%eivers &i. Ce Cill look at the %lient si e o$ the Mail/uKK sample appli%ation &Mail6u'''.

ample. 8 service".onSer iceDisconnected:null.0 License Edition . you $irst nee to %reate an instan%e o$ your oCn ServiceConnection %lass. 8 public void onSer iceConnected:Component/ame class/ameG .bject)xception e.5 set)nabled.set+na!led:true.5 setAccount6utton.is+na!led:.setChecked:service.5 < catc$ :Dead.5 < < %3$ Subscribe to updates at http://commonsware.!C %alls. as the name suggests. ServiceConnection.5 c$eck/ow6utton..asInterface:binder.com Special Creative Commons BY-SA 3.5 try 8 set)nabled. here is the ServiceConnection $rom the Mail6u'' %lass in the Mail6u'' proOe%t* private ServiceConnection svcConn"new Ser iceConnection:.8nvoking a Service !igure 0(< The *ailBuLL service client Bound for Success 5o use a servi%e. (or e.Stub. 8 svcConn.set+na!led:true.6inder binder. represents your %onne%tion to the servi%e $or the purposes o$ making .6u''.set+na!led:true.

6inder into an instan%e o$ your A.set+na!led:false.ntent:t$isG Mail6u''Service. onServiceDisconnected:. Chi%h is %alle i$ your %onne%tion en s normally. 5o a%tually hook your a%tivity to the servi%e. your onServiceConnected:.5 5he bindService:.. Chi%h Cill start up the servi%e i$ it is not alrea y running A$ter your bindService:. An .5 set)nabled.' 2. it7s easiest to use an intent re$eren%ing the servi%e %lass ire%tly &new .AL inter$a%e %lass.class.. Chi%h is your gateCay to the . metho takes three parameters* -.nterface:binder. A set o$ $lags N most times.6u''. at Chi%h time your %onne%tion is rea y $or use.!C inter$a%e.8nvoking a Service <5 public void onSer iceDisconnected:Component/ame class/ame. onServiceConnected:. More importantly.!C as i$ you Cere %alling regular metho s on a regular +ava %lass &. onServiceConnected:. so you %an use .ntent representing the servi%e you Cish to invoke N $or your oCn servi%e./D*A2-.*CR)A-). Chi%h is %alle on%e your a%tivity is boun to the servi%e 2. 8 service"null5 c$eck/ow6utton. on the a%tivity* !indSer ice:service.0 License Edition .set+na!led:false./D*A2-. @ou Cill Cant to %onvert the .5 < @our ServiceConnection sub%lass nee s to implement tCo metho s* -.'. Chi%h simply i enti$ies the servi%e you %onne%te to.Stub. %allba%k in the ServiceConnection Cill eventually be invoke . you Cill Cant to pass in 6.6inder instan%e.as. re%eives an .ntentG svcConnG 6. %all. %3/ Subscribe to updates at http://commonsware.*CR)A-).set+na!led:false.com Special Creative Commons BY-SA 3. su%h as you unbin ing your a%tivity $rom the servi%e Ia%h o$ those metho s re%eives a Component/ame. @our ServiceConnection instan%e ?. %all bindService:.5 setAccount6utton.

Prometheus >nbound When you are one Cith the . shoCn above.'.nterface:binder. Ce %all is)nabled:.n $a%t.com Special Creative Commons BY-SA 3.ample. .. you %an start %alling metho s on it as you nee to.0 License Edition . %all unbindService:.as.n a ition to bin ing to the servi%e $or the purposes o$ .n this %ase. i$ you nee to use it again. isable relevant Ci gets. you %an manually start an stop the servi%e.bject)xception N i$ this is raise .8nvoking a Service 2equest for Service >n%e your servi%e inter$a%e obOe%t is rea y &. on%e Ce have the servi%e inter$a%e obOe%t. @ou %an alCays re%onne%t to the servi%e... manually. *anual Transmission . you Cill Cant to trap Dead. .6u'' servi%e obOe%t an isable the tCo buttons an %he%kbo. i$ you isable some Ci gets aCaiting the %onne%tion. 5his is parti%ularly use$ul in %ases Chere %30 Subscribe to updates at http://commonsware. via bindService:.6u''.'. Iventually.ample. your %onne%tion7s onServiceDisconnected:. in onServiceConnected:. or otherCise $lag yoursel$ as no longer being able to use the servi%e. (or e. )oCever.!C inter$a%e. perhaps by %alling onServiceDisconnected:. Ce null out the .pe%te ly. to etermine i$ the QInable pollingQ %he%kbo. your servi%e %onne%tion terminate une. passing in the ServiceConnection. as shoCn above.. in the Mail/uKK implementation o$ onServiceDisconnected:.!C. shoul be %he%ke or not &via setC$ecked:.Stub. you shoul unCin your use o$ the servi%e. noC is a $ine time to re3enable them &see the above ServiceConnection implementation'. (or e. %allba%k Cill be invoke . at Chi%h point you shoul null out your inter$a%e obOe%t.

%33 Subscribe to updates at http://commonsware.8nvoking a Service you Cant the servi%e to keep running in epen ently o$ your a%tivities N otherCise. here is the Mail/uKK %o e behin %he%kbo. Chi%h eventually gets passe to the servi%e7s onStart:.5 0ot only o Ce %all the servi%e7s enable:.bject)xception e.ntent spe%i$ying the servi%e to start &again. but Ce also start an stop the servi%e.id. state. 5o start a servi%e.. provi ing tCo parameters* -. A 6undle provi ing %on$iguration ata.5 < catc$ :Dead. even i$ Ce later unbin $rom the servi%e.onSer iceDisconnected:null. to stop the servi%e.enabled. 8 startSer ice:service. 8 svcConn. %all. >nly Chen Ce both unbin $rom the servi%e an stop the servi%e Cill the servi%e be $ully shut oCn.5 < < <.ena!le:isC$ecked. i$ its your oCn servi%e' 2. 8 public void onCheckedChanged:Compound6utton button7iewG boolean isC$ecked. the easiest Cay is probably to spe%i$y the servi%e %lass.0 License Edition .com Special Creative Commons BY-SA 3.ntentG new Bundle:. your servi%e %oul Cell be %lose oCn. 5he . Cith the .ntent you use in the %orrespon ing startService:.findViewById:R.OnCheckedChangeListener:. . simply %all startService:.setOnCheckedChangeListener:new Compound6utton. /y starting the servi%e. base on the %he%kbo. 8 try 8 if :isC$ecked. on%e you unbin the servi%e. (or e..ntent. metho Conversely.* the QInable pollingQ set)nabled":C$eck6ox.5 < else 8 stopSer ice:service.5 < service.ample. %all stopService:.5 set)nabled. the servi%e Cill keep running an polling $or neC messages.!C metho .

Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

(or this. appointment noti$i%ations.ample. su%h as Chen email has been re%eive . @ou are no oubt use to programs trying to get your attention. Types of Pestering A servi%e. an the like. the servi%e may nee some Cay to steer the user to an a%tivity Chere they %an a%t upon the event N rea ing a re%eive message. Cith an eye toCar s having them appear only Chen nee e &e. With An roi ..0 License Edition .t message or email. $lashing lights. @our phone also probably %hirps at you $or more than Oust in%oming %alls* loC battery. $or e. An roi has a Chole $rameCork $or ealing Cith these sorts o$ things. alarm %lo%ks. An roi supplies status bar i%ons. a message has arrive '.CHAPTER &2 )lerting >sers Gia 5otifications !op3up messages. Chether /luetooth is enable . nee s a Cay to users knoC something o$ interest has o%%urre . %39 Subscribe to updates at http://commonsware. an other in i%ators %olle%tively knoCn as Qnoti$i%ationsQ. @our %urrent phone may Cell have su%h i%ons. to in i%ate battery li$e. appli%ations %an a their oCn status bar i%ons. sometimes $or goo reason. in%oming te. running in the ba%kgroun . %olle%tively %alle Qnoti$i%ationsQ.com Special Creative Commons BY-SA 3. 0ot surprisingly. signal strength. /oun%ing o%k i%ons. Moreover.g. 5ray i%ons an their asso%iate QbubbleQ messages. et%.

'.n An roi .0 License Edition . %7. by a ContentMana%er &sound'.nMS an led. using a 2ri to a pie%e o$ %ontent hel .com Special Creative Commons BY-SA 3. @ou %an vibrate the evi%e.C)../*S)R7. also spe%i$ying the %olor &as an DAR06 value in ledAR06' an Chat pattern the light shoul blink in &by provi ing o$$Uon urations in millise%on s $or the light via led. 5he notify:. 5hink o$ this as a QringtoneQ $or your appli%ation.CA-. )ere is Chat is at your isposal &bearing in min that not all evi%es Cill ne%essarily support all o$ these'* H rd# re "oti. in i%ating that the har Care noti$i%ations &e. 5o use it.ic tions @ou %an $lash LIAs on the evi%e by setting lights to true. or you might make it an option the user %an %hoose Chen %ir%umstan%es re<uire a more subtle noti$i%ation than a ringtone. but rather shoul repeat until you %an%el the noti$i%ation.ffMS'.)lerting >sers Gia 5otifications . Subscribe to updates at http://commonsware.. @ou might o this by e$ault. 5he /otificationMana%er is a system servi%e. you %an raise noti$i%ations via the /otificationMana%er. $rom your a%tivity. %ontrolle via a lon%OP in i%ating the onUo$$ patterns &in millise%on s' $or the vibration &vibrate'.E. vibration' shoul not be playe Oust on%e. @ou %an play a soun .-. metho takes a /otification. Chi%h is a ata stru%ture that spells out Chat $orm your pestering shoul take. you nee to get the servi%e obOe%t via %etSystemService:/. perhaps.' an one to stop pestering &cancel:.g. 5he /otificationMana%er gives you tCo metho s* one to pester &notify:. @ou might also Cant to set insistent to true.

i%ons are esigne to take them the ne. an vibrations are aime at getting somebo y to look at the evi%e. @ou shoul be sure the . 5o %an%el a noti$i%ation.t %an $in this out N here7s hoC it noti$ies the users.t knoCs they are nearing Caypoints is through the lo%ation servi%es o$$ere by An roi . you %an use the notify:. simply %all cancel:. Chere you spe%i$y the noti$i%ation i enti$ier an a /otification obOe%t. to take appropriate steps to let the user eal Cith the event triggering the noti$i%ation. etting -our Presence Be !elt 5o raise a /otification. @ou shoul o this Chen the noti$i%ation i%on is no longer nee e &e. the user rea the message an so there are no unrea messages to alert the user about'. Chere you provi e the i enti$ier o$ a Drawable resour%e representing the i%on. (or e.g. the 5our.com Special Creative Commons BY-SA 3. )oC 5our.t sample appli%ation uses noti$i%ations to alert ri ers that they are nearing Caypoints on their %hosen tour. on the /otificationMana%er servi%e obOe%t. soun s. 5he i enti$ier is simply a number. 5o set up an i%on $or a /otification.ample. (or the moment. metho on the /otificationMana%er servi%e obOe%t. provi ing your i enti$ier $or the noti$i%ation.ntent Cill be %aught by something.ntent.t step an tell them Chat7s so important. that i enti$ies this spe%i$i% noti$i%ation &versus any others your appli%ation might be raising'.)lerting >sers Gia 5otifications Icons While the $lashing lights.ntent to be raise Chen the i%on is %li%ke .con.t blurbs to appear Chen the i%on is put on the status bar &status6ar-icker-ext' an Chen the i%on is sele%te but not yet %li%ke &status6ar6alloon-ext'.0 License Edition . an status6arClick.. you nee to set status6ar. %7( Subscribe to updates at http://commonsware. is%usse later in this book. uni<ue Cithin your appli%ation. perhaps your oCn appli%ation %o e. @ou %an also supply te. assume that 5our. Chere you supply an .

8 notif.drawable.tourit/#BR.E.parse:#android.tW#G null. high' an the message QWaypoint nearby:Q sets up a vibration pattern.strin%.-.currentTime'illis:.5 /otification notif " new %otification: -our7iewActivity.sound"2ri.nsistent5 nm.%o*buttonG notif.)lerting >sers Gia 5otifications When a Caypoint is near.drawable.0 License Edition .ale rt.CA-.C).insistent"alert.G nullG nullG nullG R. 8 /otificationMana%er nm " :/otificationMana%er.raw. on -our7iewActivity* private void show%otification:.vibrate " new lon%OP 8 ?@@G HL@G ?@@G L@@<5 < if :alertSound.com Special Creative Commons BY-SA 3.resource!//com.w$eel*?SG #-our.commonsware.getSystemSer ice:/. i$ the user %hose to be noti$ie by a soun %on$igures the noti$i%ation to be insistent. i$ the user %hose &via the Confi%Activity' to be noti$ie by vibration sets up the QCaypoint3toneQ to play.5 < notif. 8 notif.5 < 5his metho * • sets up the noti$i%ation to shoC a Cheel i%on &-4p./*S)R7.5 // after a ?@@ms delayG vibrate for HL@msG pause for ?@@ ms and // t$en vibrate for L@@ms..t$isG R. if :alert7ibrate.t invokes s$ow/otification:. 5our.w$eel*?SG #Caypoint nearbyW#G System. so the vibration or soun Cill keep playing isplays the noti$i%ation • • • • %7% Subscribe to updates at http://commonsware.notify:R.

5 < <5 < %7. -our7iewActivity %an%els the noti$i%ation* private 3andler $andler"new (andler:.5 if :tmp&(?+ YY System.0 License Edition .strin%.cancel:R.E.%o*button. 8 9.5 lastAlertSeen.)lerting >sers Gia 5otifications Later on.verride public void handle'essage:Messa%e ms%.currentTime'illis:. Chen the Caypoint is su$$i%iently istant. Subscribe to updates at http://commonsware./*S)R7. 8 /otificationMana%er nm":/otificationMana%er.5 nm.(tmp&H@@@.CA-.com Special Creative Commons BY-SA 3.-.set:(?+.C).getSystemSer ice:/.. 8 lon% tmp"lastAlertSeen.get:.

0 License Edition .Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

0 License Edition .PART VI – Other Android Capabilities Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

0 License Edition .Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

ample. %73 Subscribe to updates at http://commonsware. so the evi%e %an tell you Chere you are at any point in time.com Special Creative Commons BY-SA 3.0 License Edition . While the most popular use o$ 8!# servi%e is mapping an ire%tions. 5he Iuropean e<uivalent to 8!#. Chi%h is still un er evelopment at the time o$ this Criting Cell toCer triangulation. >r. you %oul automati%ally QgeotagQ posts to 5Citter or similar servi%es. 8!# is not the only Cay a mobile Alternatives in%lu e* • evi%e %an i enti$y your lo%ation. as a eveloper. 5here are even Cays $or you to simulate your lo%ation in the emulator. plus etails on Chat provi ers are available. %an ask the evi%e $or your lo%ation.CHAPTER '4 )ccessing ocation"Based Services A popular $eature on %urrent3era mobile evi%es is 8!# %apability. %alle 8alileo. @ou. $or use in testing your lo%ation3enable appli%ations. (or e.imity to publi% Wi(i QhotspotsQ that have knoCn geographi% lo%ations • • An roi evi%es may have one or more o$ these servi%es available to them. so you7re %hatting Cith those you are nearest. you might set up a ynami% %hat appli%ation Chere the people you %an %hat Cith are base on physi%al lo%ation. there are other things you %an o i$ you knoC your lo%ation. Chere your position is etermine base on signal strength to nearby %ell toCers !ro.

S-)D*01S.-. as a eveloper. Chi%h hol s the set. Chile others may have a %ost asso%iate Cith them. in terms o$ a%%ura%y. !rovi ers knoC not only your lo%ation.)ccessing ocation"Based Services ocation ProvidersH They @no4 Where -ouAre Diding An roi evi%es %an have a%%ess to several i$$erent means o$ etermining your lo%ation. or ACC)SS*C)++*. Cill use a +ocationMana%er.D. Aepen ing on Chi%h lo%ation provi ers you Cish to use. @ou. or your %urrent spee . has abstra%te all this out into a set o$ +ocation1rovider obOe%ts. you nee to . Ask the user to pi%k a provi er %77 Subscribe to updates at http://commonsware. ACC)SS*ASS. there$ore. you may nee other permissions as Cell.com Special Creative Commons BY-SA 3./ permission in your appli%ation. one $or ea%h istin%t lo%ating servi%e that is available on the evi%e. #ome may be $ree. 5he ne. #ome Cill have better a%%ura%y than others. @our An roi environment Cill have Kero or more +ocation1rovider instan%es. #ome may be able to tell you more than Oust your %urrent position. su%h as ACC)SS*01S. +ocation1rovider !inding -ourself 5he obvious thing to o Cith a lo%ation servi%e is to $igure out Chere you are right noC. su%h as your elevation over sea level. @ou Cill also nee the ACC)SS*1./*S)R7. $rom your a%tivity or servi%e an %ast it to be a +ocationMana%er.s Cill $ail ue to a se%urity violation.S. )ere.0 License Edition 5o o that.C). get a +ocationMana%er N %all %etSystemService:+.CA-. but their oCn %hara%teristi%s. et%. you have tCo main options* -.. to $igure out Chi%h +ocation1rovider is right $or your parti%ular %ir%umstan%e. or the various lo%ation A!. %ost..t step to $in out Chere you are is to get the name o$ the +ocation1rovider you Cant to use. An roi .

tra Cork.getSystemSer ice:Context. or Crapping ea%h +ocation1rovider in your oCn obOe%t that implements toStrin%:.layout.CA-.5 +ocationMana%er m%r":+ocationMana%er.verride public void onCreate:6undle icicle..id. so you nee to o a little e.providers.spinnerG :+ist. %alling %et1roviders:.5 providers":Spinner. Chi%h you %an then Crap in an ArrayAdapter an use $or the sele%tion Ci get o$ your %hoi%e.5 providers. 8 t$is. 5he %at%h is that +ocation1rovider oes not have a use$ul toStrin%:.findViewById:R.listCrappers. 5our.get%ame:./*S)R7.$ you Cant the user to pi%k a provi er. 8 super.5 < < %79 Subscribe to updates at http://commonsware. 8 return:p.5 setContentView:R.p"p5 < public Strin% toString:.R. on the +ocationMana%er Cill give you a +ist o$ provi ers.t takes the latter approa%h in Confi%Activity* 9.5 < ArrayAdapter<Caypoint& aa"new ArrayAdapter<Caypoint&:t$isG R.5 < Chere 1roviderCrapper is* class 1roviderCrapper 8 +ocation1rovider p5 &ro ider*rapper:+ocation1rovider p.get&ro iders:.)ccessing ocation"Based Services 2.layout. implementation..5 for :+ocation1rovider p ! m%r.add:new &ro ider*rapper:p.C).5 aa. metho . (in the best3mat%h provi er base on a set o$ %riteria .set#dapter:aa.confi%. either overri ing ArrayAdapter to populate your vieCs by han . 8 listCrappers. by %alling the provi er7s %et/ame:.simple*spinner*dropdown*item..com Special Creative Commons BY-SA 3.0 License Edition .setDropDownView$esource:android..onCreate:icicle.layout.+.

Cill return the altitu e in meters. phone Cas turne o$$'. • • %9.$ the parti%ular lo%ation provi er o$$ers other ata.)ccessing ocation"Based Services >r. you %an %reate an populate a Criteria obOe%t. %ompass3style ire%tion'. %et+astMnown1osition:. su%h as* • setAltitudeReJuired:. to $in out Chere you Cere re%ently. stating the parti%ulars o$ Chat you Cant out o$ a +ocation1rovider. you %an %all to turn on the lo%ation provi er an get an up3to3 ate $i.g. Cill return it as egrees east o$ true north. Cill tell you i$ the spee is knoCn an %etSpeed:. Cill tell you i$ there is a bearing available. or you %an %all %et+astMnown1osition:. 0ote. an An roi Cill si$t through the %riteria an give you the best ansCer. hoCever. >n%e you knoC the name o$ the +ocation1rovider. (or bearing &i. Cill return the spee in meters per se%on . $asSpeed:. in%urs no monetary or poCer %ost. >n the other han .e. to in i%ate i$ you nee the %urrent altitu e or to set a minimum level o$ a%%ura%y. 5hese metho s return a +ocation obOe%t. %etCurrent+ocation:. Chi%h %an give you the latitu e an longitu e o$ the evi%e in egrees as a +ava double.com Special Creative Commons BY-SA 3.e i$ nothing mat%hes. that Qre%entlyQ might be $airly out o$ ate &e. $or the position • setCostAllowed:. an %etAltitude:. 0ote that not all o$ your %riteria Cill be met N all but the monetary %ost %riterion might be rela. you %an get at that as Cell* • (or altitu e. sin%e the provi er oes not nee to be a%tivate to get the value. $asAltitude:. in meters. %all %et6est1rovider:. . not • setAccuracy:. to %ontrol i$ the provi er must be $ree or i$ it %an in%ur a %ost on behal$ o$ the evi%e user 8iven a $ille 3in Critieria obOe%t. $as6earin%:. Subscribe to updates at http://commonsware. (or spee . on your +ocationMana%er.. an %et6earin%:.. Cill tell you i$ there is an altitu e value..0 License Edition .

1R)ESG @..)ccessing ocation"Based Services (or e.setText:new Dou!le:loc.D)RG null. $ille in by the Confi%Activity an up ate in -our)ditActivity7s onResume:. 8 Criteria crit"new Criteria:.setOnClickListener:new 7iew..* 9.getLatitude:.0 License Edition ...setCost#llowed:true..fillin. 8 if :p..setBearing$e-uired:false.e-uals:provider/ame.setText:new Dou!le:loc./*1R.getLongitude:.get&ro iders:. -our)ditActivity alloCs users to %li%k a button to $ill in the %urrent lo%ation Chen e iting Caypoint N the theory being that the user is ri ing the tour an taking lo%ations along the Cay to up ate the otherCise3 %omplete tour e$inition. 5he user7s pre$erre lo%ation provi er is store in a pre$eren%e.5 pt*lon%.5 provider"my+ocationMana%er.getCurrentLocation:provider. 8 if :providerW"null.5 < < 5hen.setText:new Dou!le:loc.5 btn. an $ills in the lo%ation in the appropriate $iel s* 6utton btn":6utton.OnClickListener:.toString:.5 if :provider/ameW"null.CA-.5 crit..ample. it gets a %urrent $i.5 crit. 8 for :+ocation1rovider p ! my+ocationMana%er. 8 +ocation loc"my+ocationMana%er. 8 public void onClick:7iew view.get%ame:.getBest&ro ider:crit.get#ltitude:. Chen the button is %li%ke ..5 pt*ele.5 crit..id.get%ame:.5 pt*lat.5 Strin% provider/ame"prefs. 8 provider"p5 break5 < < < if :provider""null.5 crit.toString:. 8 super..7.setSpeed$e-uired:false.5 %9( Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.set#ltitude$e-uired:false.on$esume:..findViewById:R.5 S$ared1references prefs"getShared&references:Confi%Activity..getString:Confi%Activity.+.toString:..verride public void on$esume:..

0 License Edition . the up ates Cill never be a%te upon. take a time &in millise%on s' an istan%e &in meters' N only i$ the re<ueste time has elapse and the position has %hange by the re<ueste istan%e Cill the . 5his %oul be an en estination.ample. %9% Subscribe to updates at http://commonsware.t Caypoint on the tour. $or e. Chere you %an $ire perio i%ally.t might Cant to knoC Chere you7re going. metho s.t. so Ce %an prompt them $or the ire%tion to go to get to the ne.5 +n the *ove 0oC that you knoC Chere you are. pair o$ reJuest2pdates:.ntent be ispat%he .)ccessing ocation"Based Services < < <. so you %an give the user the ne. . .ntent to be )re We There -et: )re We There -et: )re We There -et: #ometimes. to keep you in$orme o$ your %urrent position.ntent you registere .n 5our. Cith the . an you Cill only get up ates base o$$ o$ that provi erP the other $lavor takes a Criteria an Cill use the best3mat%h provi er. When you no longer nee the up ates. takes a +ocation1rovider. it Coul be ni%e to knoC Chen a ri er gets to a Caypoint.t step on a set o$ ire%tions. but Chen you get to Chere you7re going. or even Chen you move. +ocationMana%er sports a register an . /oth $lavors o$ reJuest2pdates:.ntent you register Cith reJuest2pdates:.t is up to you to arrange $or an a%tivity or intent re%eiver to respon to the . you Cant to knoC not Chere you are noC.t turn.com Special Creative Commons BY-SA 3. or it %oul be getting to the ne. you ne. >therCise. >ne $lavor o$ reJuest2pdates:.. %all remove2pdates:.

log the in$ormation to a %ontent provi er.imity alert. . )en%e.0 License Edition . plus sets up the a%tivity itsel$ as being an intent re%eiver $or the intent $or these alerts* %9.t is up to you to arrange $or an a%tivity or intent re%eiver to respon to the .ntent.. or i$ the evi%e is not in the target Kone uring the perio o$ time the pro.presse by the position an ra ius • • 0ote that it is not guarantee that you Cill a%tually re%eive an .ntent to be raise A uration $or the registration. to enable alerts.ntent.imity alerts $or all o$ the Caypoints in the tour.g. Chen vieCing the %ue sheet $or a tour &-our7iewActivity'. the user has a %he%kbo. -our7iewActivity sets up pro. Subscribe to updates at http://commonsware. perhaps <uite a $eC times epen ing on the siKe o$ the target Kone an the spee o$ the evi%e7s movement.ntent arrives is up to you* set up a noti$i%ation &e. as parameters* • • 5he latitu e an longitu e o$ the position that you are intereste in A ra ius. in millise%on s N a$ter this perio . 5his registers an . 5he add1roximityAlert:.ntent to be raise Chen the evi%e is Cithin the Qtarget KoneQ e. the evi%e might only skirt the e ge o$ the target Kone.com Special Creative Commons BY-SA 3. 5he .ample. 0ote that you Cill re%eive the .n 5our. A value o$ (? means the registration lasts until you manually remove it via remove1roximityAlert:.ntent several times. What you then o Chen the .imity alert is a%tive. vibrate the evi%e'.)ccessing ocation"Based Services 5o a%%omplish this. +ocationMana%er o$$ers add1roximityAlert:. When %he%ke .ntent Chenever the position is sample an you are Cithin the target Kone N not Oust upon entering the Kone. metho takes. spe%i$ying hoC %lose you shoul be to that position $or the .. the registration automati%ally lapses. an the ra ius is a little too tight.ntent you register Cith the pro. or go by so <ui%kly that the evi%e7s lo%ation isn7t sample Chile in the target Kone. .t. i$ the position is o$$ by a bit.. i$ there is an interruption in lo%ation servi%es. Chi%h Cill be $ire o$$ Chen the evi%e gets Cithin a %ertain istan%e o$ a %ertain lo%ation. (or e. post a message to a Web site. et%. you Cill get the .

@fG NIH@@@@@G i.ntentEilter.ntent i"new Intent:1R.5 // ?H $ours max < < < proximity.drawable.getSystemSer ice:/. At the time o$ this Criting.getLongitude:.5 5he o$$i%ial An roi o%umentation says* !he intent will have an e"tra added with key #entering# and a boolean value.CA-.E.w$eel*?SG #-our.5 my+ocationMana%er.M.getLatitude:. Chen an alert . the device is entering the pro"imity region$ if false.ntents. 8 register$ecei er:receiverG proximitylocation. it sets up a noti$i%ation to alert the user that she is nearing a Caypoint* private void show%otification:.5 for :Caypoint pt ! tour. its private han les it is. 8 if :providerW"null.G ?@@.0 License Edition .add&roximity#lert:pt.tW#G null.-F*A+)R-.get$oute:.)ccessing ocation"Based Services private void ena!le#lerts:. more a%%urately. )en%e. If the value is true.5 5he Cay -our7iewActivity 1roximity.G pt.ntentReceiver %lass' %9$ Subscribe to updates at http://commonsware. it is e"iting.w$eel*?SG #Caypoint nearbyW#G System. ealing Cith the in%oming .5 /otification notif " new %otification: -our7iewActivity.currentTime'illis:.add:i.U.-.G nullG nullG nullG R. &or..t$isG R.ntent is $irst re%eive . 8 . that oes not seem to Cork properly.com Special Creative Commons BY-SA 3.. 8 /otificationMana%er nm " :/otificationMana%er.drawable.C).ntent stream is a bit tri%ky./*S)R7.

the noti$i%ation is isable an the me%hanism is reset to aCait the ne.strin%. 8 my+ocationMana%er.com Special Creative Commons BY-SA 3.cancel:R. 8 lon% tmp"lastAlertSeen.&@.si2e:.remo e&roximity#lert:i.clear:. or i$ the a%tivity is positively %lose .-. 8 9. 5our.ale rt.ntent i ! proximity.5 if :tmp&(?+ YY System.t . 8 notif./*S)R7.5 lastAlertSeen.5 %9/ Subscribe to updates at http://commonsware.get:.ntent re%eive ..5 nm. 8 unregister$ecei er:receiver.5 < proximity.t up ates a timestamp o$ Chen the last .ntent stream stops N i$ it is stoppe $or tCo se%on s or more. i$ the user un3%he%ks the alert %he%kbo.5 < (or ea%h .5 < <5 < (inally. .strin%..imity alerts are unregistere * private void disa!le#lerts:.5 < notif.E.0 License Edition .CA-.currentTime'illis:. 8 /otificationMana%er nm":/otificationMana%er.nsistent5 nm.ntents. all o$ the pro.getSystemSer ice:/.notify:R.5 for :.raw.set:(?+. if :alert7ibrate. 8 notif.insistent"alert.ntents.sound"2ri.ntent stream* private 3andler $andler"new (andler:.%o*button.%o*buttonG notif.parse:#android.resource!//com.t then uses a 3andler to monitor $or Chen the .(tmp&H@@@.tourit/#BR.C).)ccessing ocation"Based Services // after a ?@@ms delayG vibrate for HL@msG pause for ?@@ ms and // t$en vibrate for L@@ms.ntents. 8 if :providerW"null YY proximity.commonsware.ntent Cas re%eive .verride public void handle'essage:Messa%e ms%.vibrate " new lon%OP 8 ?@@G HL@G ?@@G L@@<5 < if :alertSound.

5he goo neCs is that the $ake 8!# provi er implemente by An roi is a%tually part o$ a larger system $or emulating lo%ation provi ers.nstea . . /etter smarts are probably nee e to han le other a%tivity li$e%y%le events.ntent. set to simulate your movement aroun a loop o$ positions in the #ili%on .com Special Creative Commons BY-SA 3.0 License Edition . the QenteringQ e. as it is un%lear Chat happens to registere pro.imity alerts i$ the a%tivity that registere them is kille o$$. #in%e the $ake38!# $iles re<uire latitu e an %90 Subscribe to updates at http://commonsware. 5ra%k/uil er is a sample appli%ation. . or i enti$y your lo%ation by some nearby Wi(i signal. eally. $rom 8!#. upon Chi%h you %an %li%k to note lo%ations along a tra%k o$ movement. 5he tra%k you re%or e is then available $or your testing use. an you %an move the ata $ile into the proper spot $or use Cith An roi 7s $ake38!# provi er. to simulate the movement o$ a evi%e. 5his. 5ra%k/uil er %an then save the tra%k.)ccessing ocation"Based Services < < 5his is not a per$e%t system by any means. it has abuilt3in $ake 8!# provi er. "nless the other in$ormation you are tying lo%ation to happens to be in that area. triangulate your position $rom %ell toCers.org site.alley area o$ Cali$ornia. or you %an %reate ata $iles %ontaining time o$$sets an positions.t is mu%h simpler. negating the nee $or the 3andler. is only nominally use$ul. o$ %ourse. . to use 5ra%k/uil er.tra value Coul be set on the . @ou %an either implement a $ull +ocation1rovider an tie it into the system.t uses An roi 7s oCn mapping logi% to present you Cith a map. Testing<<<Testing<<< 5he An roi emulator oes not have the ability to get a $i. though. poste to the an ev. . you Cill nee to simulate lo%ations someChere else.

i$ you o not Cant to e.com Special Creative Commons BY-SA 3. %93 Subscribe to updates at http://commonsware. . >n%e you have the $ake38!# ata $ile or %ustom +ocation1rovider in pla%e. though.t %oul be you only o$$er a manually3%on$igure +ocation1rovider Chen your appli%ation is in some sort o$ test mo e.pose that %hoi%e to a%tual users o$ your appli%ation.0 License Edition . you %an %hoose the right provi er to mat%h the test you are running. using 5ra%k/uil er beats han 3Criting those $iles in most situations. 5his is ma e more %ompli%ate i$ you have several $ake38!# ata $iles $or i$$erent test s%enarios. 5hat is Chy it is probably a goo i ea to alloC the user to %on$igure the +ocation1rovider that your appli%ation uses.)ccessing ocation"Based Services longitu e positions to several signi$i%ant igits. rather than merely relying upon Critieria3base sele%tion N that Cay Chen you are testing. you nee to have your appli%ation use that lo%ation sour%e versus any other.

0 License Edition .Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.

(ortunately. there is a $air bit o$ poCer available to you.0 License Edition . More relevant to you.CHAPTER '1 *apping 4ith *apGie4 and *ap)ctivity >ne o$ 8oogle7s most popular servi%es N a$ter sear%h. are Map7iew an MapActivity. o$ %ourse N is 8oogle Maps. an alloC people to pan aroun . The Bare Bones (ar an aCay the simplest Cay to get a map into your appli%ation is to %reate your oCn sub%lass o$ MapActivity. Chi%h alloC you to integrate maps into your oCn appli%ations. but you %an tie in An roi 7s lo%ation3base servi%es to shoC Chere the evi%e is an Chere it is going. integrating basi% mapping $eatures into your An roi proOe%t is $airly easy. )oCever. Chi%h Craps up some o$ the smarts behin having an a%tivity ominate by a +ist7iew. Like +istActivity. as a eveloper.10B miles:' to street vieCs an satellite imagery. %99 Subscribe to updates at http://commonsware. Chere you %an $in everything $rom the nearest piKKa parlor to ire%tions $rom 0eC @ork City to #an (ran%is%o &only 2. An roi . 0ot only %an you isplay maps. %ontrol the Koom level. integrates 8oogle Maps. 5here is a mapping a%tivity available to users straight o$$ the main An roi laun%her. i$ you Cant to get $an%y.com Special Creative Commons BY-SA 3. not surprisingly.

android.%oo%le.*apping 4ith *apGie4 and *ap)ctivity MapActivity han les some o$ the nuan%es o$ setting up an a%tivity ominate by a Map7iew.android. @ou %an give the Map7iew Ci get Chatever android!id attribute value you Cant.android.. $rom the -our.android.com Special Creative Commons BY-SA 3.Map7iew. com.Map7iew android!id"#9Bid/map# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#/& <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!layout*ali%n1arent6ottom"#true#& <Spinner android!id"#9Bid/waypoints# android!layout*wei%$t"#?# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!drawSelector.com/apk/res/android# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent#& <com. . by in%lu ing the $ull pa%kage name along Cith the %lass name. 5his is ne%essary be%ause Map7iew is not in the com.maps.n your layout $or the MapActivity sub%lass. 5his is the Qlonghan Q Cay to spell out the names o$ Ci get %lasses. Subscribe to updates at http://commonsware.n-op"#true# android!paddin%-op"#?@dip# android!visibility"#invisible# android!paddin%6ottom"#?@dip# /& <. (or e.0 License Edition . at the time o$ this Criting.t sample appli%ation* <>xml version"#?. here is the layout $or -ourMapActivity. plus han le all the layout etails to have it ren er properly alongsi e your other Ci gets.ample..ma%e6utton android!id"#9Bid/%o# android!src"#9drawable/%o*to*point# android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!%ravity"#center*vertical# android!layout*%ravity"#center*vertical# android!visibility"#invisible# android!paddin%-op"#?@dip# android!paddin%6ottom"#?@dip# /& </+inear+ayout& </Relative+ayout& .maps.%oo%le.%oo%le.@# encodin%"#utf(A#>& <Relative+ayout xmlns!android"#$ttp!//sc$emas.wid%et namespa%e. you nee to a an element name .

)oCever.=B4 pi.$ you Cere to o nothing else. people looking at a map on a phone Cill be e. ..( Subscribe to updates at http://commonsware.=?B. Ce nee to a things. metho .els Ci e.has the e<uator measuring 2B4 pi. you have a $air bit o$ %apability to etermine Chat the map shoCs an hoC it behaves. the user sees a small map $o%use on one tiny %orner o$ the globe.=?B..periment Cith.is the tightest Koom you %an get. A level o$ -4 Cill shoC you several %ity blo%ks in ea%h imension an is probably a reasonable starting point $or you to e. #in%e the phone7s isplay probably oesn7t have 248.els Ci e. @ou %an %ontrol the Koom level ire%tly via the 'oom-o:. the user %oul pan aroun the map using the ire%tional pa . an built that proOe%t an tosse it in the emulator.=B4 pi.com Special Creative Commons BY-SA 3.n theory.d:.els in either imension. . )ere are some likely $eatures you Cill Cant to use* >oom 5he map o$ the Corl you start Cith is rather broa . metho on the MapController. su%h as a $eC %ity blo%ks. a $eC Exercising -our Control @ou %an $in your Map7iew Ci get by find7iew6y. that7s not terribly use$ul Chen the user has the Chole Corl in her han s. #in%e a map o$ the Corl is not mu%h goo by itsel$. . plus to sub%lass your a%tivity $rom MapActivity. Chere is the Corl vieC an 2. 5his takes an integer representing the level o$ Koom. "sually. /etCeen the Map7iew an MapController. no i$$erent than any other Ci get.pe%ting something a bit narroCer in s%ope. you7 get a ni%e map o$ the Corl . Ia%h level is a oubling o$ the e$$e%tive resolution* ..has the e<uator measuring 248. Chile 2.0 License Edition . 5he Ci get itsel$ then o$$ers a %etMapController:..*apping 4ith *apGie4 and *ap)ctivity 5hat is pretty mu%h all you nee $or starters.

5his takes a 1oint as a parameter. 5his saves a bit o$ memory versus storing a float or double.*apping 4ith *apGie4 and *ap)ctivity o$$ers a to%%le)d%eKoomin%:. use your mouse to simulate the ragging motion. or a lo%ation save Cith some ata in your a%tivity.com Special Creative Commons BY-SA 3. on the MapController. then the user %an rag her $inger oCn the right e ge o$ the map to %hange the Koom level manually.% Subscribe to updates at http://commonsware.0 License Edition . Chi%h takes a boolean parameter in i%ating i$ this $eature shoul be on or o$$. .. . you Cill nee to %ontrol Chat the map is shoCing. su%h as the user7s %urrent lo%ation. 5o %hange the map7s position. beyon the Koom level. A 1oint represents a lo%ation. via latitu e an longitu e. %all centerMap-o:. Map7iew !igure 0%< *ap 4ith Loom indicator Center 5ypi%ally. 5he %at%h is that the !oint stores latitu e an longitu e as integers representing the a%tual latitu e an longitu e multiplie by ?)S. metho .n the emulator.$ it is enable . an it probably spee s up some internal %al%ulations An roi nee s to o to %onvert the .

you Cill probably Cant to a the $olloCing statement to your onCreate:.set$eticleDraw'ode: Map7iew. )oCever.DRAC*R)-. 5his Cill return a 1oint re$le%ting the position o$ the reti%le. perhaps using the option menu to signal to your a%tivity that it Cants some in$ormation about that point. tra$$i% in$ormation. Chere map is your Map7iew* map.. +ust as you %an set the map %enter.ReticleDrawMode.0 License Edition . Subscribe to updates at http://commonsware. 1oint Reticle 5he Qreti%leQ is the small %ir%le shoCing the %enter o$ the map. on the Map7iew. so too %an An roi maps.*apping 4ith *apGie4 and *ap)ctivity into a map position.C+)*2/D)R . it oes mean you have to remember to multiple the Qreal Corl Q latitu e an longitu e by ?)S. Traffic and Terrain +ust as the 8oogle Maps you use on your $ull3siKe %omputer %an isplay satellite imagery an .5 5his Cill ensure anything you raC on the map Cill not be obs%ure by the reti%le itsel$. $or some areas. %an use the reti%le to QpointQ at a spe%i$i% spot. you %an retrieve it by %alling %etMapCenter:. 5he user. !arti%ularly i$ you Cill be implementing overlays &see beloC'.. . metho .com Special Creative Commons BY-SA 3. in turn.

5 < else if :keyCode "" Mey)vent.M)FC. 8 // Switc$ on traffic overlays map.com Special Creative Commons BY-SA 3. .0 License Edition . as the names suggest. Chi%h. @ou %an have the user trigger these via an options menu or.5 return:true.5 5he thir .toggleTraffic:. an to%%le-raffic:.. to test to see Chi%h o$ these perspe%tives is visible.D)*-.< *ap sho4ing satellite vie4 o$$ers to%%leSatellite:.. 5here is also isSatellite:. 8 // Switc$ on t$e satellite ima%es map. an isStreet7iew:.M)FC. Chi%h %an be turne on via to%%leStreet7iew:..verride public boolean on1eyDown:int keyCodeG Mey)vent event. in the %ase o$ -ourMapActivity. via keypresses* Map7iew 9.. is-raffic:. toggle on an o$$ these perspe%tives on the area being vieCe ..toggleSatellite:.. e$ault perspe%tive is Qstreet vieCQ.on1eyDown:keyCodeG event.*apping 4ith *apGie4 and *ap)ctivity !igure 0. 8 if :keyCode "" Mey)vent.D)*S.5 return:true.5 < < return:super.$ Subscribe to updates at http://commonsware.

t.t7s as i$ you are stan ing still an the Corl is moving un erneath your Cheels &or $eet.ntent to be $ire (or e. via the metho on +ocationMana%er. 5his is a serious limitation Chen Corking Cith the emulator. as you have no great means o$ %ontrolling Chi%h lo%ation provi er is use by the map.. MapController. 5he goo i$$i%ult. .CA-. . 0e. the Qnormal mo eQ is $or the map to $olloC your position.t alloCs the user to %hoose a lo%ation provi er via the Confi%Activity. reJuest2pdates:. an so you might $in yoursel$ vieCing the map o$ Chere the lo%ation provi er thinks it is.on$esume:. though./ Subscribe to updates at http://commonsware.verride public void on$esume:. the map shoul re3%enter itsel$ as you available on move. you nee to re<uest up ates $rom that lo%ation provi er. An roi o$$ers a similar $eature via setEollowMy+ocation:. With this.1R)ESG @. or $lippers.0 License Edition .5 s$owMy+ocation"prefs./G true. or.*apping 4ith *apGie4 and *ap)ctivity !ollo4 -ou6 !ollo4 *e When you use a 8!# navigation system. 8 super.getBoolean:Confi%Activity.S3. N it oesn7t let you %ontrol Chi%h lo%ation provi er to use.'... $rom -ourMapActivity* 9. At the time o$ this Criting.5 S$ared1references prefs"getShared&references:Confi%Activity. 5our. rather than Chat you are trying to test.ample.. perhaps via an appli%ation pre$eren%e.C*+. there7s one big problem Cith setEollowMy+ocation:. 5his metho arranges $or an Chen the evi%e moves a %ertain istan%e over a %ertain minimum perio o$ time. as es%ribe in the previous %hapter..com Special Creative Commons BY-SA 3. here is onResume:. neCs is that Qrolling your oCnQ $olloC3me logi% is not that 5he $irst step is $iguring out Chi%h lo%ation provi er you Cant to use.5 .

R*21DA-)G my.get&ro iders:.ntentReceiver %lass' using our intent $ilter* new Intent"ilter:+.M)*6)-C))/*21DA-)G M..e-uals:provider/ame. .get%ame:.ntent intent.5 if :provider/ameW"null.. 8 register$ecei er:intentReceiverG my.getBoolean:Confi%Activity./*1R. 8 for :+ocation1rovider p ! my+ocationMana%er.updateView:./.5 if :providerW"null.D)RG null..getBest&ro ider:crit.verride public void on$ecei eIntent:Context contextG .CA-.setBearing$e-uired:false.com Special Creative Commons BY-SA 3..S-A/C)C3A/0)*E./*C3A/0)D*AC-.$ there is no spe%i$ie lo%ation provi er.ntentReceiver %lass is trivial./.t$is.M2M*-. 8 if :p. 8 Criteria crit"new Criteria:.setCost#llowed:true.++. Ce use a Criteria to $in one.0 Subscribe to updates at http://commonsware. Ce register our intent re%eiver &an instan%e o$ the private +ocation.0 License Edition .5 < provider"my+ocationMana%er.M2M*D.5 crit.set#ltitude$e-uired:false.5 crit. 8 provider"p5 break5 < < < if :provider""null.ntentEilter.ntentReceiver 8 9.5 crit..7..5 Strin% provider/ame"prefs.5 my+ocationMana%er.E.setSpeed$e-uired:false. 5hen./.*apping 4ith *apGie4 and *ap)ctivity followMe"prefs.5 .ntentReceiver extends .5 crit. 8 -ourMapActivity.C*M)G true.re-uest)pdates:providerG M.getString:Confi%Activity..5 < < We $irst $in out Chat the %hosen lo%ation provi er is an Chether or not the $olloC3me $eature shoul be enable .CA-.ntent.+. simply telling the a%tivity to up ate its vieC* class +ocation.5 >ur +ocation.

*apping 4ith *apGie4 and *ap)ctivity

< <

5he update7iew:; metho on -ourMapActivity %he%ks to see i$ $olloC3me is enable , an , i$ true, re3%enters the map on the %urrent position*
private void updateView:; 8 if :providerW"null; 8 my+ocation"my+ocationMana%er.getCurrentLocation:provider.get%ame:;;5 if :followMe; 8 Double lat"-ourMapActivity.t$is.my+ocation.getLatitude:; Q ?)S5 Double ln%"-ourMapActivity.t$is.my+ocation.getLongitude:; Q ?)S5 1oint point"new &oint:lat.intValue:;G ln%.intValue:;;5 < < mc.center'apTo:pointG false;5

map.in alidate:;5 <

/y this me%hanism, you %an have your $olloC3me $eature Chile o$$ering more ire%t %ontrol over Chi%h lo%ation provi er to use. .t is eminently possible the An roi A!. Cill be up ate to Qbake inQ this type o$ %apability, at Chi%h point the %o e shoCn here may be%ome obsolete.

ayers >pon ayers
.$ you have ever use the $ull3siKe e ition o$ 8oogle Maps, you are probably use to seeing things overlai atop the map itsel$, su%h as Qpush3pinsQ in i%ating businesses near the lo%ation being sear%he . .n map parlan%e N an , $or that matter, in many serious graphi% e itors N the push3pins are on a separate layer than the map itsel$, an Chat you are seeing is the %omposition o$ the push3pin layer atop the map layer. An roi 7s mapping alloCs you to %reate layers as Cell, so you %an mark up the maps as you nee to base on user input an your appli%ation7s purpose. (or e;ample, 5our.t uses a layer to shoC Chere all the Caypoints o$ the tour are, in se<uen%e, plus your %urrent lo%ation relative to those Caypoints.

,;3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

*apping 4ith *apGie4 and *ap)ctivity

0verl y Cl sses
Any overlay you Cant to a to your map nee s to be implemente as a sub%lass o$ ,verlay. 5his oes not have to be a publi% %lassP -ourMapActivity has a private inner %lass %alle Route,verlay to shoC the Caypoints an %urrent evi%e position. 5o atta%h an overlay %lass to your map, you nee ,verlayController an a the overlay to it*
map.createO erlayController:;.add:new $outeO erlay:t$is;G true;5

to get your map7s

5he $irst parameter is the ,verlay instan%e, in this %ase a neC Route,verlay, atta%he to the a%tivity. 5he se%on parameter is a boolean in i%ating i$ the overlay shoul be a%tivate . @ou %an e$ine overlays an a%tivate or ea%tivate them as nee e , Oust as you toggle betCeen regular an satellite vieCs. .n this %ase, sin%e Ce Cant the overlay to be visible at all times, Ce use true to a%tivate it imme iately.

Dr #in! the 0verl y
sub%lasses nee to implement a draw:; metho to a%tually put their material onto their layer $or superposition over the map sur$a%e. 5he draw:; metho takes three parameters*
,verlay

-.

A Canvas, use as the raCing sur$a%e

2. A 1ixelCalculator, to help you %onvert betCeen pi;els $or your raCing an real3Corl imensions on the map ?. A boolean in i%ating Chether this is the Qsha oCQ %all or not 5he draw:; metho is %alle tCi%e in su%%ession* on%e Cith s$adow " true, in i%ating that i$ your layer has any sort o$ ?A e$$e%t &e.g., sha oCs %ast by push3pins', you shoul raC those, an on%e Cith s$adow " false $or raCing the QregularQ part o$ the layer. While you shoul %hain upCar to the super%lass &via super.draw:canvasG calculatorG s$adow;', the e$ault

,;7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

*apping 4ith *apGie4 and *ap)ctivity

a%tion $or draw:; is to o nothing. )en%e, i$ you on7t have a sha oC, either ignore the parameter or only raC Chen s$adow " false. A Canvas o$$ers a range o$ raCing metho s, su%h as drawCircle:;, draw-ext:;, an so on. 5he %at%h is that the Canvas is e;pe%ting to be tol Chere to raC in terms o$ pi;els in %anvas3spa%e. @ou, on the other han , have your ata in terms o$ positions &latitu e an longitu e'. An , o$ %ourse, the user isn7t vieCing the Chole Corl at on%e, so there7s a <uestion o$ Chi%h subset o$ things you Cant to raC a%tually appear on the Canvas. (ortunately, An roi en%apsulates mu%h o$ those problems insi e the 1ixelCalculator. 5o raC things on the Canvas, you shoul * -. Convert your latitu e an longitu e into a 1oint...as note above, a 1oint uses a pair o$ integers $or the latitu e an longitu e, s%ale upCar s by a $a%tor o$ ?)S

2. Allo%ate an intOHP array to hol the pi;el %onversion o$ your 1oint ?. Call %et1ointUF:; on the 1ixelConverter, supplying your 1oint an intOHP array =. "se the intOHP array as ;Uy %oor inates $or your draw...:; metho s on the Canvas (or e;ample, here is the implementation o$ Route,verlay7s draw:; metho *
public void draw:Canvas canvasG 1ixelCalculator calculatorG boolean s$adow; 8 super.draw:canvasG calculatorG s$adow;5 if :show'yLocation:; YY -ourMapActivity.t$is.my+ocationW"null; 8 Double lat"-ourMapActivity.t$is.my+ocation.getLatitude:; Q ?)S5 Double ln%"-ourMapActivity.t$is.my+ocation.getLongitude:; Q ?)S5 1oint point"new &oint:lat.intValue:;G ln%.intValue:;;5 intOP myScreenCoords " new intOHP5 calculator.get&oint,3:pointG myScreenCoords;5 canvas.drawCircle:myScreenCoordsO@PG myScreenCoordsO?PG LG paintI;5 < int i"@5 for :Caypoint pt ! tour.get$oute:;; 8 ,;9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

*apping 4ith *apGie4 and *ap)ctivity

iBB5 1oint position"pt.get&osition:;5 if :positionW"null; 8 intOP screenCoords"new intOHP5 calculator.get&oint,3:positionG screenCoords;5 canvas.drawCircle:screenCoordsO@PG screenCoordsO?PG ?HG paint?;5 canvas.drawText:.nte%er.toString:i;G screenCoordsO@P ( NG screenCoordsO?P B NG paintH;5 < < <

A$ter %haining upCar to the super%lass, Ce $irst etermine i$ Ce7re suppose to be shoCing the evi%e7s position. .$ so, Ce buil a 1oint, %onvert it to ;Uy %oor inates, an raC a L3pi;el ra ius re %ir%le at those %oor inates &paintI is e$ine up in onCreate:; as being R8/ re '. 5hen, $or ea%h Caypoint in the tour, Ce o mu%h the same thing* buil a 1oint, %onvert it to ;Uy %oor inates, raC a ?H3pi;el ra ius bla%k %ir%le, an Crite in the %ir%le the Caypoint number in Chite.

H ndlin! Screen T ps
An ,verlay sub%lass %an also implement on-ap:;, to be noti$ie Chen the user taps on the map, so the overlay %an a Oust Chat it raCs. (or e;ample, in $ull3siKe 8oogle Maps, %li%king on a push3pin pops up a bubble Cith in$ormation about the business at that pin7s lo%ation. With on-ap:;, you %an o mu%h the same in An roi . 5he on-ap:; metho re%eives three parameters* -. A Q evi%e typeQ, in i%ating Chat generate tra%kball, et%.' the tap &tou%hs%reen,

2. 5he 1oint representing the real3Corl tappe the map

lo%ation Chere the user ;Uy

?. A 1ixelCalculator to help you %onvert betCeen 1oint an %oor inates, i$ nee e
,(;
Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

*apping 4ith *apGie4 and *ap)ctivity

.t is up to you to etermine i$ the supplie 1oint represents something o$ interest an , i$ so, Chat to isplay. .n the %ase o$ Route,verlay, on-ap:; looks like this*
9,verride public boolean onTap:com.%oo%le.android.maps.Map7iew.Device-ype device-ypeG 1oint pG 1ixelCalculator calculator; 8 for :Caypoint pt ! tour.get$oute:;; 8 1oint position"pt.get&osition:;5 if :positionW"null; 8 intOP screenCoords"new intOHP5 RectE rect"new $ect":;5 calculator.get&oint,3:positionG screenCoords;5 rect.set:(?HG(?HG?HG?H;5 rect.offset:screenCoordsO@PG screenCoordsO?P;5 calculator.get&oint,3:pG screenCoords;5 if :rect.contains:screenCoordsO@PG screenCoordsO?P;; 8 -oast.makeText:parentG pt.getTitle:;G H@@@;.show:;5 <

< < <

return:super.onTap:device-ypeG pG calculator;;5

We iterate over the Caypoints an use the RectE helper %lass to %onstru%t a 2=;2= pi;el s<uare aroun ea%h Caypoint7s on3s%reen representation. 5his s<uare isn7t raCn on s%reenP rather, it is use solely to etermine i$ the tap &represente by the supplie 1oint' o%%urre Cithin that s<uare. .$ so, Ce %onsi er the user to have tappe on that Caypoint, an Ce shoC a -oast Cith the name o$ the Caypoint &e.g., QMosser #t. G )amiltonQ'.

,((
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

CHAPTER '&

Playing *edia

!retty mu%h every phone %laiming to be a QsmartphoneQ has the ability to at least play ba%k musi%, i$ not vi eo. Iven many more or inary phones are $ull3$le ge M!? players, in a ition to o$$ering ringtones an Chatnot. 0ot surprisingly, An roi aims to mat%h the best o$ them. An roi has $ull %apability to play ba%k an re%or au io an vi eo. 5his in%lu es*
• • • • •

!layba%k o$ au io, su%h as oCnloa e M!? tra%ks #hoCing photos !laying ba%k vi eo %lips ,oi%e re%or ing through the mi%rophone Camera $or still pi%tures or vi eo %lips

I;a%tly hoC robust these %apabilities Cill be is heavily evi%e3 epen ent. Mobile evi%e %ameras range $rom e;%ellent to atro%ious. #%reen resolutions an siKes Cill vary, an vi eo playba%k Corks better on better s%reens. Whi%h %o e%s a evi%e manu$a%turer Cill li%ense &e.g., Chat types o$ vi eo %an it playD' an Chi%h /luetooth pro$iles a evi%e Cill support &e.g., A2A! $or stereoD' Cill also have an impa%t on Chat results any given person Cill have Cith their phone.

,(,
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Playing *edia

@ou as a eveloper %an integrate me ia playba%k an re%or ing into your appli%ations. Re%or ing is outsi e the s%ope o$ this book, in large part be%ause the %urrent emulator has re%or ing limitations at this time. An , vieCing pi%tures is mostly a matter o$ putting an .ma%e7iew Ci get into an a%tivity. 5his %hapter, there$ore, $o%uses on playba%k o$ au io an vi eo. As Cith many a van%e An roi $eatures, e;pe%t %hanges in $uture releases o$ their toolkit. (or e;ample, at the time o$ this Criting, there is no built3in au io or vi eo playba%k a%tivity. )en%e, you %annot Oust %ra$t an .ntent to, say, an M!? "RL, an han it o$$ to An roi Cith 7.)C*AC-.,/ to initiate playba%k. Right noC, you nee to han le the playba%k yoursel$. .t is probably sa$e to assume, though, that stan ar a%tivities $or this Cill be $orth%oming, alloCing you to Qtake the easy Cay outQ i$ you Cant to play ba%k me ia but o not nee to %ontrol that playba%k mu%h yoursel$.

'et -our *edia +n
.n An roi , you have $ive i$$erent pla%es you %an pull me ia %lips $rom N one o$ these Cill hope$ully $it your nee s* -. @ou %an pa%kage me ia %lips as raC resour%es &res/raw in your proOe%t', so they are bun le Cith your appli%ation. 5he bene$it is that you7re guarantee the %lips Cill be thereP the oCnsi e is that they %annot be repla%e Cithout upgra ing the appli%ation.

2. @ou %an pa%kage me ia %lips as assets &assets/ in your proOe%t' an re$eren%e them via file!///android*asset/ "RLs in a 2ri. 5he bene$it over raC resour%es is that this lo%ation Corks Cith A!.s that e;pe%t 2ri parameters instea o$ resour%e .As. 5he oCnsi e N assets are only repla%eable Chen the appli%ation is upgra e N remains. ?. @ou %an store me ia in an appli%ation3lo%al ire%tory, su%h as %ontent you oCnloa o$$ the .nternet. @our me ia may or may not be there, an your storage spa%e isn7t in$inite, but you %an repla%e the me ia as nee e . =. @ou %an store me ia N or re$eren%e me ia that the user has store hersel$ N that is on an #A %ar . 5here is likely more storage spa%e on

,($
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

>ne %aveat* you %annot simply %all start:. 5he prepare:. you nee to %all prepare:.t.. startUstopUpause playba%k. use the 2ri3$lavore version o$ ?. begins playba%k.nternet streaming seems to be someChat problemati% in this release o$ the An roi #AF. . >n%e the %lip is prepare . an stop:. but other appli%ations have a%%ess to the #A %ar as Cell. you %an $ee it an au io %lip.$ the %lip is a raC resour%e. start:. su%h as $et%hing the $irst $eC se%on s o$$ the $ile or stream. B. @ou %an. @ou have three Cays to set up a Media1layer an tell it Chat au io %lip to play* -.com Special Creative Commons BY-SA 3. 2. or prepareAsync:. stream me ia o$$ the . an you %an repla%e the me ia as nee e . Oust %reate a Media1layer using the e$ault %onstru%tor. N that may be a bug or may be the .Playing *edia the %ar than there is on the evi%e. metho is syn%hronousP as soon as it returns. pauses playba%k &Cith start:. *aking 5oise 5he %ru. metho is asyn%hronous N more on hoC to use this version later.0 License Edition .create:. an get noti$ie on key events. an provi e the resour%e .create:. bypassing any lo%al storage .$ you have a string path to the %lip. again on the Media1layer on%e you have %alle stop:. Cith the path to the %lip 0e. o$ playing ba%k au io %omes in the $orm o$ the Media1layer %lass. use Media1layer.$ you have a 2ri to the %lip. pause:. en s playba%k.nternet.A o$ the %lip Media1layer. the %lip is rea y to play. . /oth Cill set up the %lip to be rea y to play.(/ Subscribe to updates at http://commonsware. su%h as Chen the %lip is rea y to be playe or is one playing. 5he prepareAsync:. pi%king up playba%k Chere pause:. With it. then %all setDataSource:. in some %ases. pause '. .

5o see this in a%tion. take a look at the AudioDemo sample proOe%t.(0 Subscribe to updates at http://commonsware.android.0 License Edition . 5he layout is pretty trivial. pause.ma%e6utton android!id"#9Bid/play# android!src"#9drawable/play# android!layout*$ei%$t"#wrap*content# android!layout*widt$"#wrap*content# android!paddin%Ri%$t"#Npx# android!enabled"#false# /& <-ext7iew android!text"#1lay# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!%ravity"#center*vertical# android!layout*%ravity"#center*vertical# android!textAppearance"#>android!attr/textAppearance+ar%e# /& </+inear+ayout& <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!paddin%"#Npx# & <.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.Playing *edia inten e Media1layer behavior.com Special Creative Commons BY-SA 3. We7ll %over a Corkaroun a bit later in this se%tion.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!paddin%"#Npx# & <. an stop* <>xml version"#?. Cith three buttons an labels $or play.ma%e6utton android!id"#9Bid/pause# android!src"#9drawable/pause# android!layout*$ei%$t"#wrap*content# android!layout*widt$"#wrap*content# android!paddin%Ri%$t"#Npx# /& <-ext7iew android!text"#1ause# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!%ravity"#center*vertical# .

Menu5 android.ma%e6utton .7iew5 android.view. o$ %ourse. is Chere things get interesting* packa%e com.(3 Subscribe to updates at http://commonsware.wid%et.layout.content.ma%e6utton5 android..wid%et.commonsware.D " Menu.com Special Creative Commons BY-SA 3.S$ared1references5 android.ma%e6utton android!id"#9Bid/stop# android!src"#9drawable/stop# android!layout*$ei%$t"#wrap*content# android!layout*widt$"#wrap*content# android!paddin%Ri%$t"#Npx# /& <-ext7iew android!text"#Stop# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!%ravity"#center*vertical# android!layout*%ravity"#center*vertical# android!textAppearance"#>android!attr/textAppearance+ar%e# /& </+inear+ayout& </+inear+ayout& android!layout*%ravity"#center*vertical# android!textAppearance"#>android!attr/textAppearance+ar%e# 5he +ava.view.RS-BH5 private private private private .Context5 android.os.onCreate:icicle.app.6undle5 android.S)*.0 License Edition .verride public void onCreate:6undle icicle.android.5 .-oast5 public class AudioDemo extends Activity 8 private static final int C+.5 setContentView:R.content.Playing *edia /& </+inear+ayout& <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!paddin%"#Npx# & <.audio5 import import import import import import import import import android. 8 super.ma%e6utton .media.Activity5 android.main.ma%e6utton Media1layer play5 pause5 stop5 mp5 9.Media1layer5 android.E.

setOnClickListener:new 7iew.start:.OnClickListener:.5 mp.set+na!led:true.ma%e6utton. 8 stop:.5 play. .findViewById:R.set+na!led:true. 8 public void onClick:7iew view. 8 menu.5 -oast.S)*.id.OnClickListener:. 8 mp. 8 mp.5 try 8 mp"new 'edia&layer:. 8 public void on&repared:Media1layer mp.id.verride public boolean onCreateOptions'enu:Menu menu.setOnCompletionListener:new Media1layer.e:#AudioDemo#G #)xception playin% audio#G t.5 play.5 stop.5 < <.findViewById:R.5 < <.ma%e6utton.setOn&reparedListener:new Media1layer.pause.Playing *edia play":.5 pause.0 License Edition .5 < <.set+na!led:false.5 play.findViewById:R.id.com Special Creative Commons BY-SA 3.set#lpha!eticShortcut:ZcZ.5 setup:.5 mp.stop. 8 public void onClick:7iew view.add:@G C+.5 stop":. 8 stop:.ckW#G H@@@.set+na!led:true. 8 play.5 stop.setOnClickListener:new 7iew.eject.play.5 < <.ma%e6utton. 8 public void onCompletion:Media1layer mp.5 pause.OnClickListener:.util.5 pause":. 8 public void onClick:7iew view.set+na!led:false.makeText:t$isG #.+o%.setOnClickListener:new 7iew.5 pause.set+na!led:true.5 < catc$ :-$rowable t.. 8 android.pause:.(7 Subscribe to updates at http://commonsware.5 .OnCompletionListener:.5 stop.5 < < 9.set+na!led:true.show:.DG #Close#G R.On&reparedListener:.5 < <.drawable.

• to an .nCompletion+istener via N this %allba%k gets invoke Chen the %lip .n1repared+istener via set. is $inishe .prepare#sync:.verride public boolean onOptionsItemSelected:Menu.onOptionsItemSelected:item..mpI#.5 < private void setup:.n1repared+istener:.reset:.5 < private void stop:.util..5 < return:super.tem item. N this %allba%k gets invoke Chen prepareAsync:.set+na!led:false.set+na!led:false. 8 switc$ :item. Ce Cire up the three buttons to shi$t us betCeen the other states.0 License Edition . an in our %ase it enables the play button We hook it up set.5 Auring the preparation phase.getId:. 8 play. plus prep the Media1layer &mp instan%e variable'.show:. 8 mp.5 -oast.onCreateOptions'enu:menu.makeText:t$isG #.com Special Creative Commons BY-SA 3.5 try 8 mp.5 return:true..5 stop. #pe%i$i%ally* • • We use the empty %onstru%tor We hook it up to an .e:#AudioDemo#G #)xception playin% audio#G t. 8 case C+. 8 android.5 < catc$ :-$rowable t.S)*.Playing *edia < return:super.+o%.5 < < < mp.nCompletion+istener:..setDataSource:#/system/media/audio/rin%tones/rin%er.5 pause.5 setup:.D! finish:.set+na!led:false.5 9.(9 Subscribe to updates at http://commonsware.ckW#G H@@@..

at Chi%h point Ce %all stop:. 5he %lip possibly en s on its oCn.com Special Creative Commons BY-SA 3. 5he user %li%ks the play button an listens to the %lip =... We enable the play button ?. sets the %lip to be a built3in ringtone M!?. metho >ur stop:. Subscribe to updates at http://commonsware. metho simply resets the Media1layer an %alls setup:. 5he setup:. is nothing spe%ial... then %li%ks play again to resume B.%. We prep the Media1layer Cith the %lip 2. anyCay* . 5he user possibly stops playba%k. an %alls prepareAsync:. #o. but Ce7re more intereste in the au io in this sample. 5he ". 5he user possibly pauses playba%k. at Chi%h time the me ia player is %ompletely reset to its post3prep state 4. Oust as i$ the user ha %li%ke the #top button • We %all a setup:. the $loC is* -.Playing *edia rea%hes the en . metho N %alle uring initial preparation an a$ter the %lip is stoppe N isables the buttons.0 License Edition . at Chi%h time the me ia player is also reset 5he Chole reset3an 3re%on$igure pro%ess is hoC you %an get a Media1layer ba%k to being able to play again a$ter you %all stop:.

playba%k seems a bit ro%ky in the emulator. $ee it an M!= vi eo %lip. an you get playba%k: Right noC. #in%e 7ideo7iew is a Ci get. but that Cill likely %lear itsel$ up in $uture releases N 7ideo7iew Cas only ma e available in the #AF release prior to publi%ation o$ this book.emo sample application *oving Pictures .Playing *edia !igure 0$< The )udio.0 License Edition .i eoAemo sample proOe%t* <>xml version"#?. you %an put it in a layout.android.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <7ideo7iew android!id"#9Bid/video# android!layout*widt$"#IH@px# android!layout*$ei%$t"#HN@px# .@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas. su%h as this one $rom the .com Special Creative Commons BY-SA 3.%( Subscribe to updates at http://commonsware.i eo %lips get their oCn Ci get. !ut it in a layout. the 7ideo7iew.

video5 import import import import import import import android.5 video":7ideo7iew.1ixelEormat5 android.. 8 super.android. 8 public void onClick:7iew view.5 6utton s$ow":6utton.com Special Creative Commons BY-SA 3. an $ast3 $orCar buttons* packa%e com. reCin .video.id.n a ition to the 7ideo7iew.%rap$ics.setOnClickListener:new 7iew. Cill pop up the 7ideo7iew %ontrol panel.%% Subscribe to updates at http://commonsware.commonsware.verride public void onCreate:6undle icicle.5 ctlr"new 'ediaController:t$is.-RA/S+2C)/-.wid%et. 5his.5 s$ow.app.5 video.findViewById:R.wid%et. by e$ault.0 License Edition .onCreate:icicle. Chen pushe .5 .os.re-uest"ocus:.MediaController5 android.set'edia&layer:video.findViewById:R. plus o$$ers pause.s$ow.view.5 get*indow:.OnClickListener:.show:.5 ctlr.7ideo7iew5 public class 7ideoDemo extends Activity 8 private 7ideo7iew video5 private MediaController ctlr5 9.wid%et.set'ediaController:ctlr.5 video.set"ormat:1ixelEormat.5 video.layout.5 setContentView:R.7iew5 android.mpN#. knoCn as the MediaController.6undle5 android.Activity5 android.6utton5 android. Ce also put in a 6utton that.id.setVideo&ath:#/tmp/test.5 < <.main. 8 ctlr. overlays the bottom portion o$ the 7ideo7iew an shoCs your %urrent position in the vi eo %lip.Playing *edia /& <6utton android!id"#9Bid/s$ow# android!text"#S$ow ControllerW# android!layout*$ei%$t"#fill*parent# android!layout*widt$"#fill*parent# android!paddin%Ri%$t"#Npx# android!enabled"#false# /& </+inear+ayout& .

0 License Edition .AI' to %opy the M!= $ile into /tmp/test.mage Contest. Subscribe to updates at http://commonsware. Chi%h Cas use in the %reation o$ this book 2. While 7ideo7iew oes support some streaming vi eo. (in a %lip. su%h as Aaron Rosenberg7s %ocumentaries and &ou $rom Auke "niversity7s Center $or the #tu y o$ the !ubli% Aomain7s Moving . the re<uirements on the M!= $ile are $airly stringent.mpN >n%e there. .Playing *edia < < 5he biggest tri%k Cith 7ideo7iew is getting a vi eo %lip onto the evi%e.$ you Cant to be able to play a Ci er array o$ vi eo %lips. you nee to have them on the evi%e.emo sample application6 sho4ing a Creative Commons" licensed video clip . 5he %ru e 7ideoDemo %lass assumes there is an M!= $ile in /tmp/test. the $olloCing +ava %o e Cill give you a Corking vi eo player* !igure 0/< The Gideo. 5o make this a reality* -.com Special Creative Commons BY-SA 3.%.mpN on your emulator. either in the lo%al $ilesystem or on an #A %ar . "se the adb pus$ %omman &or the e<uivalent in your .

on the 7ideo7iew. an so you may nee to re3push the $ile i$ you inten to run this sample over an e. an stop1layback:.Playing *edia >AT.* the /tmp ire%tory is %leane out perio i%ally on the emulator.0 License Edition . 5he %lip Cill automati%ally start playing ba%k N you o not nee to %all play:. Chi%h isplays the %ontrol panel. on the MediaController. though that metho is available &as is pause:.%$ Subscribe to updates at http://commonsware. 5he button is set up to %all s$ow:. in %ase you nee your oCn %ontrol over playba%k in a ition to the MediaController7s %ontrol panel'.com Special Creative Commons BY-SA 3. ..ten e perio o$ time.

i$ not most.. an Cithout them having to keep those %onta%ts both in your appli%ation an in the phone7s %onta%ts appli%ation Maybe you are Criting a so%ial netCorking appli%ation.pe%ting to pla%e an re%eive %alls using An roi .g. you let people pla%e %alls ire%tly $rom your appli%ation Maybe you are %reating an alternative inter$a%e to the e.0 License Edition . An roi has A!. An roi evi%es Cill be phones.com Special Creative Commons BY-SA 3. As su%h. . the el erly'.s to let you manipulate the phone Oust like any other pie%e o$ the An roi system. sporting big buttons an the like to make it easier $or them to pla%e %alls • • Whatever the reason. so rather than try to Qsyn%Q the so%ial netCork %onta%ts Cith the phone7s %onta%t atabase.%/ Subscribe to updates at http://commonsware. an the roster o$ phone numbers that you %an a%%ess shi$ts %onstantly.isting %onta%ts system.%om' an you Cant to o$$er users the ability to %all prospe%ts Cith a single button %li%k. but you Cill have the opportunity to help them pla%e %alls.CHAPTER '' Dandling Telephone Calls Many. perhaps $or users Cith re u%e motor %ontrol &e. i$ you Cish. Why might you Cant toD • Maybe you are Criting an An roi inter$a%e to a sales management appli%ation &a la #ales$or%e. not only Cill users be e.

Stub. 5he i$$eren%e is in hoC you get that bin er* p$one".as. Qo$$ hookQ means the phone is in use. Chi%h takes a phone number an puts it on the An roi Aialer s%reen. -ou *ake the Call! .!C inter$a%e.1$one inter$a%e $rom An roi . so i$ is. there7s a more prosai% reason Chy you might not be able to use the phone N the user might alrea y be on a %all.com Special Creative Commons BY-SA 3.n:.Dandling Telephone Calls 5o6 5o6 5o M 5ot That 8Phone<<< 5o get at the phone A!. you %annot pla%e a %all. by %alling .getSer ice:#p$one#. Chi%h imme iately pla%es a %all. Chi%h terminates the %urrent %all .. 5he is. 5o ay. 2..' or as a means o$ silen%ing the phone uring meetings..1$one.asInterface:svcM%r. returns true. lest they a%%i entally toggle the phone on Chen they really shoul n7t.nterface:.ff$ook:.ff$ook:. on the . et%.5 WhatAs +ur Status: /ear in min that the phone %apability might not alCays be on.0 License Edition .. 5he phone might have the phone ra io turne o$$ in pla%es Chere either it isn7t alloCe &airplanes.%0 Subscribe to updates at http://commonsware. you nee to get an obOe%t implementing the .Stub. Cith a suitable bin er.ff:.n.s relate to %all han ling* -. metho N espite using the ar%hai% QhookQ terminology $rom a byegone era o$ phones N Cill tell i$ you i$ a %all is in progress.. )ere. >$ %ourse. @ou %an even %all to%%leRadio. that Corks mu%h like hoC you Coul a%%ess any other servi%e7s . hospitals. even i$ An roi is running.!hone also o$$ers three A!. to %hange the ra io7s status N though you really shoul make sure this is Chat the user Cants. aCaiting user %on$irmation to ial that number dial:. call:. endCall:.1$one. @ou %an etermine i$ the phone is rea y $or use by %alling isRadio.1$one inter$a%e. given a phone number ?.

.android. .ample.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# & <-ext7iew android!layout*widt$"#wrap*content# android!layout*$ei%$t"#wrap*content# android!text"#/umber to dial!# /& <)dit-ext android!id"#9Bid/number# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# android!cursor7isible"#true# android!editable"#true# android!sin%le+ine"#true# /& </+inear+ayout& <+inear+ayout android!orientation"#$ori'ontal# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# & <6utton android!id"#9Bid/dial# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!layout*wei%$t"#?# android!text"#Dial . make sure the user has %on$irme they truly Cant a %all.%3 Subscribe to updates at http://commonsware. or you may Cin up Cith a bun%h o$ unhappy users. (or e.0 License Edition .tW# . )ere7s the %ru e3 but3e$$e%tive layout* <>xml version"#?. >r.tW# /& <6utton android!id"#9Bid/call# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!layout*wei%$t"#?# android!text"#Call .Dandling Telephone Calls 8enerally speaking. you probably shoul use dial:. over call:. let7s look at the Dialer sample appli%ation. in %ase they mis3 %li%ke on something.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.com Special Creative Commons BY-SA 3. or call:.. alloCing users to %hoose Chether you Cin up using dial:.. o$$er a %on$iguration option. so the user gets %on$irmation that they7re a%tually pla%ing a %all.$ you $eel you Cant to use call:.

8 try 8 if :p$oneW"null.. an call:.os.5 < final )dit-ext number":)dit-ext.findViewById:R.1$one p$one"null5 9.util.Stub.5 < .makeText:DialerDemo. 8 public void onClick:7iew v.+o%.os.layout.5 dial.dial.5 6utton dial":6utton.ServiceMana%er svcM%r"ServiceMana%er/ative.e:#DialerDemo#G #)rror in dial:.getText:.1$one5 android. on the .getSer ice:#p$one#.setOnClickListener:new 6utton...wid%et.commonsware.android. plus buttons $or ialing an %alling sai number.Activity5 android.os.t$isG e..Dandling Telephone Calls /& </+inear+ayout& </+inear+ayout& We have a labele $iel $or typing in a phone number.main.app.6utton5 android.)dit-ext5 android.7iew5 android.view.toString:.com Special Creative Commons BY-SA 3.number.6undle5 android...Dead.wid%et.5 setContentView:R.findViewById:R.id. 8 android.dial:number.id.%7 Subscribe to updates at http://commonsware.bject)xception e..5 .getDefault:.-oast5 public class DialerDemo extends Activity 8 .ServiceMana%er/ative5 android.wid%et.0 License Edition .asInterface:svcM%r. 8 super.ServiceMana%er5 android.os.toString:.G H@@@. respe%tively.5 -oast.verride public void onCreate:6undle icicle. 8 p$one.dialer5 import import import import import import import import import import android.show:.5 try 8 p$one".OnClickListener:.5 finish:.#G e.1$one.1$one inter$a%e* packa%e com.telep$ony.bject)xception5 android. 5he +ava %o e Cires up those buttons to dial:.5 < catc$ :Dead.onCreate:icicle.

%9 Subscribe to updates at http://commonsware.bject)xception e.5 < < #ome notes about the %o e* • We keep the .setOnClickListener:new 6utton.makeText:DialerDemo. an inter$a%e to a servi%e. Ce Oust log an isplay an error message • 5he a%tivity7s oCn ".show:.show:.util.toString:. so Ce on7t keep having to %reate neC .5 6utton call":6utton.0 License Edition . in e$$e%t. Ce have to eal Cith the possible Dead.id.OnClickListener:...Dandling Telephone Calls < catc$ :Dead.call.e:#DialerDemo#G #)rror in dial:. 8 p$one. 8 try 8 if :p$oneW"null.5 -oast.t$isG e.5 < < <.call:number.getText:.e:#DialerDemo#G #)rror in dial:..1$one instan%es on every button push #in%e .5 -oast.makeText:DialerDemo. 8 android.+o%.findViewById:R.bject)xception e..5 call.5 < < catc$ :Dead.+o%. 8 public void onClick:7iew v. 8 android.1$one is.util. N aroun in an instan%e variable in the a%tivity.toString:.5 < < <.com Special Creative Commons BY-SA 3.#G e.G H@@@.1$one N %reate near the top o$ onCreate:.G H@@@.t$isG e.#G e.bject)xception i$ the servi%e %onne%tion %ollapse P here. is not that impressive* .toString:.

.ialer activity6 as launched from .emo .Dandling Telephone Calls !igure 00< The .emo sample application6 as initially launched )oCever. shoCing you the number you are about to ial* !igure 03< The )ndroid .ialer.0 License Edition . Subscribe to updates at http://commonsware. the ialer you get $rom %li%king the ial button is better.ialer..com Special Creative Commons BY-SA 3.

0 License Edition ..( Subscribe to updates at http://commonsware.ialer. you are taken straight to a %all* !igure 07< The )ndroid call activity6 as launched from . i$ you %li%k the %all button.emo .com Special Creative Commons BY-SA 3.Dandling Telephone Calls >r.

com Special Creative Commons BY-SA 3.0 License Edition .Subscribe to updates at http://commonsware.

s is likely. Subscribe to updates at http://commonsware.CHAPTER '( Searching 4ith Search*anager >ne o$ the $irms behin the >pen )an set Allian%e N 8oogle N has a teeny Ceeny Web sear%h servi%e. . #pe%i$i%ally. it7s not surprising that An roi has some amount o$ built3in sear%h %apabilities. an so some shi$ting in the A!. but over the air to .$ the user %li%ks the menu button $olloCe by the S key. then you automati%ally QinheritQ a hi en sear%h menu %hoi%e. by triggering sear%hes or perhaps by alloCing your appli%ation7s ata to be sear%he . one you might have hear o$ in passing. 8iven that. An roi has Qbake inQ the notion o$ sear%hing not only on the evi%e $or ata.$ your a%tivity has an options menu. @our appli%ations %an parti%ipate in the sear%h pro%ess. Dunting Season .nternet sour%es o$ ata. 0ote that this is $airly neC to the An roi plat$orm.0 License Edition .. #tay tune $or up ates to this %hapter.. it Cill isplay the sear%h popup* .com Special Creative Commons BY-SA 3.

like the built3in Conta%ts a%tivity.0 License Edition .$ the appli%ation you are sear%hing supports a live $iltere sear%h..Searching 4ith Search*anager !igure 09< The )ndroid search popup6 sho4ing a search for contacts (rom here.com Special Creative Commons BY-SA 3. you %an toggle betCeen appli%ations by %li%king the button on the le$t an enter in a sear%h string. . you %an %hoose $rom an entry mat%hing your sear%h string as it appears beloC the sear%h $iel * .$ Subscribe to updates at http://commonsware.

you %an %li%k the 8o button an be taken to an a%tivity that Cill pro%ess your sear%h an shoC the results. in your a%tivity &e./ Subscribe to updates at http://commonsware..'. there Cill be tCo $lavors o$ sear%h available via the An roi sear%h system* .g.Searching 4ith Search*anager !igure 3.$ your a%tivity oes not nee keyboar entry. su%h as D... in your a%tivity &e.< ) filtered search for contacts >r. 0ote that there are other options $or setDefaultMeyMode:. 5hat is simply a matter o$ %alling onSearc$ReJuested:.com Special Creative Commons BY-SA 3. su%h as a button. in onCreate:. Chi%h routes number keypresses to a neCly3laun%he Aialer a%tivity. $rom the button7s %allba%k metho '.A+)R*D)EA2+-*M)FS.g. you %an have keystrokes pull up the sear%h popup by %alling setDefaultMeyMode:S)ARC3*D)EA2+-*M)FS. Search -ourself >ver the long haul. . ..0 License Edition .$ your a%tivity oes not have an options menu. you Cill nee to trigger this manually by some other user inter$a%e element.

an . Calks. 5he sear%h a%tivity %an have any look you Cant.. to o the sear%h an isplay the results. .ntent:. let7s look at the +orem sample appli%ation. that might prove someChat %on$using to users.0 License Edition .0 Subscribe to updates at http://commonsware. an the a%tivity is responsible $or up ating a isplaye list o$ mat%hes #in%e the latter approa%h is un er heavy evelopment right noC by the An roi team. (or e. Chere the user7s sear%h string is passe to an a%tivity Chi%h is responsible $or %on u%ting the sear%h an isplaying the results 2. Huery3style sear%h. let7s $o%us on the $irst one. other than Cat%hing $or <ueries. then later Cith EML resour%es. a sear%h a%tivity looks. Cr .Searching 4ith Search*anager -. &via %et. 5his starts o$$ as a %lone o$ the list3o$3lorem3ipsum3Cor s appli%ation that Ce $irst built ba%k Chen shoCing o$$ the +ist7iew %ontainer.t the Se rch Activity 5he $irst thing you are going to Cant to o i$ you Cant to support <uery3style sear%h in your appli%ation is to %reate a sear%h a%tivity. i$ so.ample. 0oC.ntent:. Chere the user7s sear%h string is passe to an a%tivity on every keypress.' an on/ew. an talks like any other a%tivity in your system. having a separate a%tivity is %leaner.com Special Creative Commons BY-SA 3. 5he main a%tivity an the sear%h a%tivity both share a %ommon layout* a +ist7iew plus a -ext7iew shoCing the sele%te entry* . While it might be possible to have a single a%tivity be both opene $rom the laun%her an opene $rom a sear%h. to see i$ one is a sear%h. Ce up ate it to support sear%hing the list o$ Cor s $or ones %ontaining the sear%h string. (ilter3style sear%h. Certainly.n $a%t. All the sear%h a%tivity nee s to o i$$erently is %he%k the intents supplie to onCreate:. $or the purposes o$ learning the te%hni<ues.

Searching 4ith Search*anager

<>xml version"#?.@# encodin%"#utf(A#>& <+inear+ayout xmlns!android"#$ttp!//sc$emas.android.com/apk/res/android# android!orientation"#vertical# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# & <-ext7iew android!id"#9Bid/selection# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#wrap*content# /& <+ist7iew android!id"#9android!id/list# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#fill*parent# android!drawSelector,n-op"#false# /& </+inear+ayout&

.n terms o$ +ava %o e, most o$ the guts o$ the a%tivities are poure into an abstra%t +orem6ase %lass*
packa%e com.commonsware.android.searc$5 import import import import import import import import import import import import import import import import import android.app.Activity5 android.app.+istActivity5 android.app.Searc$Mana%er5 android.content..ntent5 android.os.6undle5 android.view.Menu5 android.view.7iew5 android.wid%et.Adapter7iew5 android.wid%et.ArrayAdapter5 android.wid%et.+istAdapter5 android.wid%et.+ist7iew5 android.wid%et.-ext7iew5 java.io..nputStream5 java.util.Array+ist5 java.util.+ist5 or%.xmlpull.v?.Uml1ull1arser5 or%.xmlpull.v?.Uml1ull1arser)xception5

abstract public class +orem6ase extends +istActivity 8 abstract +istAdapter make'e#n#dapter:.ntent intent;5 private static final int C+,S)*.D " Menu.E.RS-B?5 -ext7iew selection5 Array+ist<Strin%& items"new Array+ist<Strin%&:;5 9,verride public void onCreate:6undle icicle; 8 super.onCreate:icicle;5 setContentView:R.layout.main;5

,,3
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

selection":-ext7iew;findViewById:R.id.selection;5 try 8 Uml1ull1arser xpp"get$esources:;.get,ml:R.xml.words;5 w$ile :xpp.get+ entType:;W"Uml1ull1arser.)/D*D,C2M)/-; 8 if :xpp.get+ entType:;""Uml1ull1arser.S-AR-*-A0; 8 if :xpp.get%ame:;.e-uals:#word#;; 8 items.add:xpp.get#ttri!uteValue:@;;5 < < xpp.next:;5 < catc$ :-$rowable t; 8 show#lert:#)xceptionW#G @G t.toString:;G #Cancel#G true;5 < < on%ewIntent:getIntent:;;5 <

9,verride public void on%ewIntent:.ntent intent; 8 +istAdapter adapter"make'e#n#dapter:intent;5 if :adapter""null; 8 finish:;5 < else 8 setList#dapter:adapter;5 <

<

public void onListItemClick:+ist7iew parentG 7iew vG int positionG lon% id; 8 selection.setText:items.get:position;.toString:;;5 < 9,verride public boolean onCreateOptions'enu:Menu menu; 8 menu.add:@G C+,S)*.DG #Close#G R.drawable.eject; .set#lpha!eticShortcut:ZcZ;5 return:super.onCreateOptions'enu:menu;;5 < 9,verride public boolean onOptionsItemSelected:Menu..tem item; 8 switc$ :item.getId:;; 8 case C+,S)*.D! finish:;5 return:true;5 <

,,7
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

< <

return:super.onOptionsItemSelected:item;;5

5his a%tivity takes %are o$ everything relate to shoCing a list o$ Cor s, even loa ing the Cor s out o$ the EML resour%e. What it oes not o is %ome up Cith the +istAdapter to put into the +ist7iew N that is elegate to the sub%lasses. 5he main a%tivity N +oremDemo N Oust uses a +istAdapter $or the Chole Cor list*
packa%e com.commonsware.android.searc$5 import android.content..ntent5 import android.wid%et.ArrayAdapter5 import android.wid%et.+istAdapter5 public class +oremDemo extends +orem6ase 8 9,verride +istAdapter make'e#n#dapter:.ntent intent; 8 return:new ArrayAdapter<Strin%&:t$isG android.R.layout.simple*list*item*?G items;;5 < <

5he sear%h a%tivity, though, oes things a bit i$$erently. (irst, it inspe%ts the .ntent supplie to the abstra%t makeMeAnAdpater:; metho . 5hat .ntent %omes $rom either onCreate:; or on/ew.ntent:;. .$ the intent is a S)ARC3*AC-.,/, then Ce knoC this is a sear%h. We %an get the sear%h <uery an , in the %ase o$ this silly emo, spin through the loa e list o$ Cor s an $in only those %ontaining the sear%h string. 5hat list then gets Crappe in a +istAdapter an returne $or isplay*
packa%e com.commonsware.android.searc$5 import import import import import android.app.Searc$Mana%er5 android.content..ntent5 android.wid%et.ArrayAdapter5 android.wid%et.+istAdapter5 java.util.Array+ist5

,,9
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

import java.util.+ist5 public class +oremSearc$ extends +orem6ase 8 9,verride +istAdapter make'e#n#dapter:.ntent intent; 8 +istAdapter adapter"null5 if :intent.get#ction:;.e-uals:.ntent.S)ARC3*AC-.,/;; 8 Strin% Juery"intent.getString+xtra:Searc$Mana%er.T2)RF;5 +ist<Strin%& results"searchItems:Juery;5 adapter"new ArrayAdapter<Strin%&:t$isG android.R.layout.simple*list*item*?G results;5 setTitle:#+oremSearc$ for! #BJuery;5 < < return:adapter;5

private +ist<Strin%& searchItems:Strin% Juery; 8 +ist<Strin%& results"new Array+ist<Strin%&:;5 for :Strin% item ! items; 8 if :item.indexOf:Juery;&(?; 8 results.add:item;5 < < < < return:results;5

+pd te the % ni,est
While this implements sear%h, it oesn7t tie it into the An roi sear%h system. 5hat re<uires a $eC %hanges to the auto3generate AndroidManifest.xml $ile*
<manifest xmlns!android"#$ttp!//sc$emas.android.com/apk/res/android# packa%e"#com.commonsware.android.searc$#& <application& <activity android!name"#.+oremDemo# android!label"#+oremDemo#& <intent(filter& <action android!name"#android.intent.action.MA./# /& <cate%ory android!name"#android.intent.cate%ory.+A2/C3)R# /& </intent(filter& <meta(data android!name"#android.app.default*searc$able# android!value"#.+oremSearc$# /& </activity&

,$;
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

<activity android!name"#.+oremSearc$# android!label"#+oremSearc$# android!launc$Mode"#sin%le-op#& <intent(filter& <action android!name"#android.intent.action.S)ARC3# /& <cate%ory android!name"#android.intent.cate%ory.D)EA2+-# /& </intent(filter& <meta(data android!name"#android.app.searc$able# android!resource"#9xml/searc$able# /& </activity& </application& </manifest&

5he %hanges that are nee e are* -. 5he +oremDemo main a%tivity gets a meta(data element, Cith an android!name o$ android.app.default*searc$able an a android!value o$ the sear%h implementation %lass &.+oremSearc$'
+oremSearc$ a%tivity gets an intent $ilter android.intent.action.S)ARC3, so sear%h intents Cill be pi%ke up

2. 5he

$or

?. 5he +oremSearc$ a%tivity is set to have android!launc$Mode " #sin%le-op#, Chi%h means at most one instan%e o$ this a%tivity Cill be open at any time, so Ce on7t Cin up Cith a Chole bun%h o$ little sear%h a%tivities %luttering up the a%tivity sta%k =. 5he +oremSearc$ a%tivity gets a meta(data element, Cith an android!name o$ android.app.searc$able an a android!value o$ an EML resour%e %ontaining more in$ormation about the sear%h $a%ility o$$ere by this a%tivity &9xml/searc$able' 5hat EML resour%e provi es tCo bits o$ in$ormation to ay* -. What name shoul appear in the sear%h omain button to the le$t o$ the sear%h $iel , i enti$ying to the user Chere she is sear%hing

2. What hint te;t shoul appear in the sear%h $iel , to give the user a %lue as to Chat they shoul be typing in

,$(
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

Try It 0ut
8iven all that, sear%h is noC available N An roi knoCs your appli%ation is sear%hable, Chat sear%h omain to use Chen sear%hing $rom the main a%tivity, an the a%tivity knoCs hoC to o the sear%h. .$ you pop up the sear%h $rom the main a%tivity &MenuBS', you Cill see the Lorem .psum sear%h omain appear as your e$ault area to sear%h*

!igure 3(< The orem sample application6 sho4ing the search popup

5yping in a letter or tCo, then %li%king 8o, Cill bring up the sear%h a%tivity an the subset o$ Cor s %ontaining Chat you type , Cith your sear%h <uery in the a%tivity title bar*

,$%
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Searching 4ith Search*anager

!igure 3%< The results of searching for AcoA in the orem search sample

,$,
Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3.0 License Edition

Subscribe to updates at http://commonsware.com

Special Creative Commons BY-SA 3.0 License Edition

PART VII – Appendices Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

Subscribe to updates at http://commonsware.0 License Edition .com Special Creative Commons BY-SA 3.

nstalling the appli%ation itsel$ is straight$orCar * Cith the emulator running.n several %hapters o$ this book. is%usses the appli%ation as a Chole.APPE"DI? A The Tour8t Sample )pplication . Cith the tour starting at the Lehigh . 5he author o$ this book oes not live in #ili%on . he ha no goo Cay o$ eveloping a bi%y%le tour mat%hing that loop. 5our.alley. )oCever. . lo%ation provi er.elo rome.0 License Edition .t Cas more e.com Special Creative Commons BY-SA 3. Ce use 5our. As su%h. 8nstalling Tour8t . that has the evi%e moving through a loop aroun the 8oogle %ampus in Cali$ornia. An roi has a built3in $ake. . this one han ling a loop aroun the author7s home base in eastern !ennsylvania.pe ient to evelop another emo lo%ation provi er. Demo =oc tion Provider As mentione in the %hapter on lo%ations. an let Ant o the heavy li$ting.t as a sour%e o$ sample %o e $or $eatures ranging $rom %ontent provi ers to mapping an lo%ation servi%es. or emo.t proOe%t ire%tory.t has tCo other re<uirements N a emo lo%ation provi er an an #A %ar image N that are someChat more %ompli%ate to install.alley . 5his appen i. so you %an see all $a%ets o$ it $rom $ront to ba%k. $ire up ant install in the base o$ the 5our.$3 Subscribe to updates at http://commonsware.

. adb s$ell #mkdir /data/misc/location/velo#' 2. the long3term vision is $or a tour an its asso%iate me ia %lips to resi e on an #A %ar . $or 5our. on%e some stan ar players start shipping Cith the An roi #AF &versus the player %omponents es%ribe in an earlier %hapter'. that you Cill probably Cant to install this emo lo%ation provi er yoursel$.g. or similar means.. this tra%k Chi%h hol s the most3re%ent position o$ the evi%e along • properties. though. you Cill be able to use both the built3in $ake 8!# ata an this neC QveloQ set o$ $ake 8!# ata. Restart your emulator At this point. • Chi%h is the a%tual roster o$ time o$$sets $rom the starting time an the position the evi%e is in at that point. so the 5our.t Cill support multime ia %lips. has a loC poCer re<uirement' track.g. SD C rd Im !e #ith S mple Tour (uture e itions o$ 5our.$7 Subscribe to updates at http://commonsware. .com Special Creative Commons BY-SA 3. Chi%h es%ribes the %hara%teristi%s o$ this lo%ation provi er &e.0 License Edition . )en%e. e$ine as latitu e an longitu e 5o install this lo%ation provi er in your emulator. "se adb pus$ to push ea%h o$ those three $iles into your neCly %reate ire%tory ?. either oCnloa e there o$$ the . o the $olloCing* -.The Tour8t Sample )pplication 5his means.nternet. you Cill $in three $iles* • location.t appli%ation7s tour lines up Cith a lo%ation provi er.t an any other lo%ation3aCare appli%ation on your emulator. "se adb s$ell to %reate a velo/ ire%tory un er /data/misc/location/ &e. oesn7t support altitu e. . or trans$erre there via "#/ %ables. /luetooth.n the proOe%t7s location/velo/ ire%tory.

n this %ase. 2unning Tour8t Like most An roi laun%her* appli%ations. pass the (sdcard sCit%h Cith a path to the image $ile* emulator (sdcard pat$/to/sdcard.t proOe%t ire%tory Cith the sample %o e $or this book. though. use the mksdcard tool supplie by the An roi #AF. you Cill nee an #A %ar image you %an use Cith the An roi emulator an uploa a tour there. 5o use that %ar in the emulator. a small #A %ar image is supplie as sdcard. 5o %reate an #A %ar image.t appli%ation Cill be use$ul.t is available $rom the An roi !igure 3.com Special Creative Commons BY-SA 3. 5our. be$ore the 5our.t.< The )ndroid launcher6 sho4ing the Tour8t main activity .im% in the 5our.The Tour8t Sample )pplication (or the purposes o$ this early in%arnation o$ 5our.$9 Subscribe to updates at http://commonsware. .im% 5hat Cill mount the %ar un er /sdcard/ in the emulator7s $ilesystem.0 License Edition .

it the a%tivity* . Subscribe to updates at http://commonsware.com Special Creative Commons BY-SA 3. A Qhome pageQ shoCing version in$ormation an some navigation buttons 2.0 License Edition .The Tour8t Sample )pplication Cli%king on that i%on brings up the main 5our.t a%tivity./. % in Activity 5he main a%tivity provi es tCo istin%t s%reens* -. along Cith a Close menu %hoi%e to proa%tively e. A list o$ available tours loa e into the appli%ation !igure 3$< The Tour8t =home page= 5he three navigation buttons shoCn on the home page are upli%ate in the options menu.

5our.com Special Creative Commons BY-SA 3.$ your #A %ar image is mounte properly. so you shoul see* .t shoul automati%ally $in the sample tour Chen it laKy3%reates its atabase.$ you %li%k on the shoC3tours button.0 License Edition .The Tour8t Sample )pplication !igure 3/< The Tour8t =home page= 4ith option menu . ./( Subscribe to updates at http://commonsware. you Cill see a list o$ available tours.

it is a goo i ea to visit the %on$iguration a%tivity.com Special Creative Commons BY-SA 3.The Tour8t Sample )pplication !igure 30< The Tour8t list of tours Con. so Ce %an use the right sample lo%ation provi er Chen raCing the map./% Subscribe to updates at http://commonsware.0 License Edition .$ you %hoose the Q%on$igureQ button or option menu %hoi%e. .i!ur tion Activity )oCever. you Cill bring up that %on$iguration a%tivity* . be$ore looking at a tour.

The Tour8t Sample )pplication !igure 33< The Tour8t configuration activity As mentione .. using the supplie spinner.0 License Edition . an Chether it shoul o that on%e or %ontinuously Chile you are near the Caypoint • • . the QveloQ lo%ation provi er shoul be liste N %hoose it.com Special Creative Commons BY-SA 3.$ you uploa e the mo%k provi er es%ribe earlier in this appen i. Subscribe to updates at http://commonsware. or both. an i$ the map shoul s%roll to $olloC your lo%ation as you move What shoul happen Chen you near a Caypoint on a tour you are taking N play a soun . you %an %on$igure* • Whether 5our./. /eyon that. the most important setting to %hange is the lo%ation provi er. vibrate.t starts Cith the Qhome pageQ or the list o$ tours Chen you %li%k the i%on $rom the laun%her Whether your %urrent lo%ation shoul be shoCn on the map. .

The Tour8t Sample )pplication Cue Sheet Activity >$ %ourse. . the interesting part o$ 5our.$ you %hoose one o$ the Caypoints in the list. %alle a QCaypointQ. at Mosser.com Special Creative Commons BY-SA 3.ample. i$ you %hoose the QL. you Cill travel 0. >n the tours list.2 miles an make a le$t at the stop sign to turn onto Weilers R .t are the tours themselves. #ubse<uent Caypoints are given base on a ire%tion $rom the pre%e ing Caypoint N $or e.0 License Edition . a panel Cill appear toCar s the bottom shoCing more etails about that Caypoint* . . it Cill bring up the %ue sheet* !igure 37< ) tourAs cue sheet in Tour8t 5he starting point is the $irst entry. $rom )amilton /lv ./$ Subscribe to updates at http://commonsware.elo romeQ tour.

// Subscribe to updates at http://commonsware. means you Cant the evi%e to beep or buKK Chen you are near the Caypoint. or %he%k the QAnimate etailsQ %he%kbo. 5he other %he%kbo.0 License Edition . at the bottom. @ou Coul turn this on i$ you Cere a%tually taking the tour shoCn on this %ue sheet. at the bottom to have them s%roll by automati%ally. % p Activity 5he options menu $rom the %ue sheet a%tivity in%lu es one to spaCn a map shoCing your lo%ation an the lo%ation o$ the Caypoints on the tour* . QAlert near CaypointQ.The Tour8t Sample )pplication !igure 39< The Tour8t cue sheet 4ith 4aypoint details 5here are several bits o$ in$ormation that %an appear in this panel. "se the le$t an right buttons on the A3pa to rotate betCeen them.com Special Creative Commons BY-SA 3. to help let you knoC you are nearing a pla%e Chere you nee to turn or stop.

< The Tour8t map vie4 @our position is shoCn by the re ot &i$ you enable that in the %on$iguration'. 5he Caypoints are shoCn by numbere ots./0 Subscribe to updates at http://commonsware.0 License Edition . the map Cill shi$t to shoC your position no matter Chere you go on the map. starting Cith $or the $irst Caypoint. 5he options menu $or this a%tivity has a $eC istin%tive %hoi%es* .$ you turne on the $olloC3me $eature in the %on$iguration.com Special Creative Commons BY-SA 3. .The Tour8t Sample )pplication !igure 7.

0 License Edition . 0ote. )oCever. then publish the resulting up ate tour. hoCever. easily a ing an publishing tours'. to a%%ess mapping $eatures not available in 5our. uploa it to 5our. but .t7s oCn simpli$ie map vieC.t oes not alloC you to e$ine neC tours $rom s%rat%h insi e the appli%ation. you Coul use some e. . mostly be%ause there Coul be a $air amount o$ typing involve . 5here are a $eC pie%es missing in this version o$ 5our. i$ you are set Cith $olloC3me turne on..g.t to make this a reality &e. alloCing you to %hoose a Caypoint an Oump to that lo%ation.n theory. it oes alloC you to up ate the position in$ormation asso%iate Cith Caypoints.t.ternal program to e$ine a tour. it Cill then pop the map ba%k to your %urrent lo%ation. 5he Q(ull MapQ menu %hoi%e Cill laun%h the built3in An roi map a%tivity on your %urrent lo%ation.com Special Creative Commons BY-SA 3. then take the tour an up ate the Caypoints as you go. an that Coul be te ious on a phone./3 Subscribe to updates at http://commonsware.The Tour8t Sample )pplication !igure 7(< The Tour8t map vie46 4ith options menu displayed 5he Q#hoC !i%kerQ menu %hoi%e Cill bring up a spinner an button. Tour +pd te Activity 5our.

The Tour8t Sample )pplication the ability to up ate the lo%ation is provi e .t also provi es a very limite amount o$ online help. %hoose #ave $rom the option menu to save your %hanges ba%k out to the tour $or later reuse.0 License Edition . Choosing the )elp option menu %hoi%e $rom any a%tivity takes you to online help $or that a%tivity* . an &in theory' elevation o$ your position.n My Lo%ation:Q to up ate the latitu e. 5hen.plain hoC to use the appli%ation. Help Activity 5our. When one./7 Subscribe to updates at http://commonsware. you %an up ate the istan%e travelle along the %ourse $rom the pre%e ing Caypoint to here.com Special Creative Commons BY-SA 3.ia the spinner. an %li%k Q(ill . longitu e. to e. you %an %hoose a Caypoint. @ou %an get to this via the "p ate menu %hoi%e $rom the %ue sheet* !igure 7%< >pdating a cue sheet 4ithin Tour8t .

S-)D*01S# /& <uses(permission android!name"#android.ACC)SS*01S# /& <uses(permission android!name"#android.intent.ACC)SS*+.permission.action.cate%ory.permission.com Special Creative Commons BY-SA 3.xml $ile than the rest o$ the samples shoCn in this book* <manifest xmlns!android"#$ttp!//sc$emas.< ) Tour8t help page Tour8tAs *anifest 5our.The Tour8t Sample )pplication !igure 7.0 License Edition .+A2/C3)R# /& </intent(filter& </activity& <activity android!name"#.android.com/apk/res/android# packa%e"#com.intent./# /& <uses(permission android!name"#android.tourit#& <uses(permission android!name"#android.ACC)SS*ASS.-our7iewActivity#& <intent(filter& <action android!name"#android.tourit.MA.D)EA2+-# /& <data android!mime-ype"#vnd.permission.)C# /& <cate%ory android!name"#android.7.-our+istActivity# android!label"#-our./9 Subscribe to updates at http://commonsware.commonsware.cursor.commonsware.tour# /& .cate%ory.1rovider# android!aut$orities"#com.permission.item/vnd.intent.1rovider# /& <activity android!name"#..ACC)SS*C)++*.action./# /& <cate%ory android!name"#android.intent.D# /& <application android!icon"#9drawable/w$eel#& <provider android!name"#.t has a someChat more %ompli%ate AndroidManifest.tW#& <intent(filter& <action android!name"#android.commonsware.android.android.CA-.

(inally.3elpActivity# android!label"#-our. 5he rest are simply liste Cithout an intent $ilter.-# /& <cate%ory android!name"#android.intent. >ne N -our+istActivity N is set to appear in the appli%ation7s laun%h menu.tW ( 3elp#& </activity& </application& </manifest& 0e.The Tour8t Sample )pplication </intent(filter& </activity& <activity android!name"#. Waypoints an ire%tions ea%h have is%rete bits o$ ata. .android.cate%ory.action.com Special Creative Commons BY-SA 3. Subscribe to updates at http://commonsware. Later. either to shoC o$$ $eatures o$ a given lo%ation.commonsware. Ce es%ribe all the available a%tivities.tW ( Confi%uration#& </activity& <activity android!name"#. 5Co others N -our7iewActivity an -our)ditActivity N are available to be laun%he by intents looking to manipulate ata supplie by our %ontent provi er. 5ours are ma e up o$ Caypoints an ire%tions betCeen them. su%h as the %oor inates o$ Caypoint an the istan%e to travel $or a ire%tion.)D.tour# /& </intent(filter& </activity& <activity android!name"#.Confi%Activity# android!label"#-our.t7s %ontent is %omprise o$ tours.0 License Edition .-ourMapActivity#& </activity& <activity android!name"#.item/vnd.D)EA2+-# /& <data android!mime-ype"#vnd. so they %an only be a%%esse via their %lass names. Ce Cire in the %ontent provi er.cursor. supplying ata about the available tours to our a%tivities.-our)ditActivity#& <intent(filter& <action android!name"#android. or to help gui e travelers through tri%ky ire%tions. tours an their Caypoints Cill also have multime ia %lips.0. Tour8tAs Content 5our.intent.t.

plus the Caypoints an Directions that make up the guts o$ the tour itsel$. More importantly. An some An roi appli%ations use the Q umb mo elQ approa%h.'. %unningly name 1rovider. Iventually.g. 5he -our %lass knoCs hoC to rea an Crite the +#>0 ata stru%ture an turn that into tour in$ormation. 5his eliminates the nee to s%an the #A %ar Oust to populate the list o$ available tours.0 License Edition . loa e o$$ the #A %ar .t7s $irst step on the roa to a %leaner M. Right noC.g. an sin%e %lips %oul be big. Cith a tours table. Later.pan e to en%ompass other tables. %odel Cl sses An roi appli%ations ten not to map all that %leanly to the mo el3vieC3 %ontroller &M.isten%e o$ an #A %ar %ontaining the tours.t assumes the e. et%. shoul that prove ne%essary. the provi er might be e. evelopment. it makes $or a better sample appli%ation $or this book. 5here is also a #HLite atabase. ea%h tour gets its oCn ire%tory on the %ar . putting business logi% in the a%tivity an using the %ontent provi er as Oust a ata store. 5our. %ontaining a +#>0 ata stru%ture &tour. Content Provider 5he #HLite atabase is manage by an An roi %ontent provi er. to hol the master roster o$ available tours. Right noC.com Special Creative Commons BY-SA 3. . An a%tivity ten s to blen both elements o$ the vieC &e.js' Cith the tour etails &e.The Tour8t Sample )pplication D t Stor !e 8iven that 5our. button %li%ks..C implementation are the mo el %lasses* -our. Caypoints'. setting up an managing Ci gets' an %ontroller &han ling menu %hoi%es. an given that An roi 7s approa%h is to store su%h %lips in the $ile system.t Cill eventually have multime ia %lips. it only eals Cith a single table N tours N Chi%h %ontains the roster o$ all available tours.0( Subscribe to updates at http://commonsware.C' ar%hite%ture popular in 8". those ire%tories Cill also hol the me ia %lips asso%iate Cith that tour. 5our.. Caypoint. an Direction.

5o o this.t hoC Confi%Activity alloCs you to set various options $or %ustomiKing 5our.0% Subscribe to updates at http://commonsware. it uses 7iewElipper N think o$ it as the guts o$ a -abActivity. Ia%h %hil element o$ the 7iewElipper represents a separate QpageQ to be $lippe . but instea Cill highlight a $eC interesting bits that shoC o$$ various An roi $eatures.t breaks its user inter$a%e up into a series o$ a%tivities. base on An roi 7s reporte lo%ation -our)ditActivity 3elpActivity • • is the gateCay to online help $or using 5our.The Tour8t Sample )pplication >ver time. plus &optionally' your lo%ation • alloCs you to up ate lo%ation in$ormation $or a tour. more an more logi% Cill move into the mo els.xml'. leaving the %ontent provi er still as a umb store. this shoCs hoC you %an buil an arbitrarily %omple. a%tivity instea o$ treating ea%h in ivi ual a%tivity as a separate %onstru%t. ea%h %overing a i$$erent $a%et o$ Corking Cith tours* • • • -our+istActivity is the home page plus the list o$ installe tours tour -our7iewActivity shoCs the %ue sheet $or a sele%te -ourMapActivity shoCs the Caypoints $or the tour.t Corks $or you 5his se%tion isn7t going to go through these a%tivities line3by3line. Tour8tAs )ctivities 5our. but trying to make the a%tivity more o$ a thin %ontroller. -our+istActivity . Tour=istActivity han les both the home page an the list o$ installe tours.com Special Creative Commons BY-SA 3.n the layout &res/layout/main. 8iven a 7iewElipper an the appropriate means to get $rom vieC to vieC.0 License Edition . minus the tabs. Ce e%lare a 7iewElipper.

tem3ei%$t# android!textAppearance"#>android!attr/textAppearance+ar%e.drawable.5 flipMenu.5 if :flipMenuW"null. )ere are a $eC o$ the interesting $a%ets o$ this %lass. Subscribe to updates at http://commonsware.setIcon:R.@# encodin%"#utf(A#>& <-ext7iew xmlns!android"#$ttp!//sc$emas.tW ( -ours#.android.t han les isplaying the %ue sheet plus noti$ying users Chen they approa%h a Caypoint.0. #o.0 License Edition .t. -our7iewActivity is $ar an aCay the most %ompli%ate %lass in all o$ 5our.$ome. . as illustrate in s$ow+ist:..The Tour8t Sample )pplication betCeen.xml'* <>xml version"#?. ba%ke by a SimpleCursorAdapter. in turn ba%ke by the %ontent provi er. )oCever.com Special Creative Commons BY-SA 3. 8 flipMenu.setDisplayedChild:@. .com/apk/res/android# android!id"#9android!id/text?# android!layout*widt$"#fill*parent# android!layout*$ei%$t"#>android!attr/list1referred.t7s su$$i%iently %ompli%ate that even Oust provi ing a %ustom layout Coul not han le the nee .5 setTitle:#-our.5 < < 5he tour list itsel$ is a simple +ist7iew. 8 flipper. Ce o tailor the look o$ the in ivi ual list entries. by re$eren%ing our oCn layout &res/layout/tourlist*item. @ou $lip betCeen them via the %hil 7s @3base in e..setTitle:#0o 3ome#.nverse# android!%ravity"#center*vertical# android!paddin%+eft"#Ldip# /& Tour@ie#Activity At B00V lines o$ %o e. -our7iewActivity has a private . besi es the lo%ation servi%es o%umente in a previous %hapter* Custo) !ist Contents 5he in ivi ual items in the %ue sheet N the Caypoint title plus the ire%tion o$ hoC to get there N is a tri$le more %ompli%ate than the sto%k list $ormats supplie by An roi . Chi%h toggles the vieC to the list o$ available tours* private void showList:.

findViewById:R.inflate:R.getViewInflate:.get$oute:..id.inflate:R. han &res/layout/tourview*std. tra$$i% alert' that %alls $or a tCo3line isplay 5our.5 turn. buil s the list item 5he problem is that there are several $lavors o$ vieC that goes into the list* • • • 5he typi%al ire%tion plus Caypoint title 5he $irst entry. Ce have the three s%enarios liste above &versus having a $ourth.nflate inflater"context.setText:distanceEormat.tourview*stdG nullG null.W"null..view.t makes a simpli$ying assumption* the $irst Caypoint has no note.0 License Edition .getViewInflate:.getCumulati eDistance:. Chi%h is Oust the starting Caypoint Cith no ire%tion Intries Chere the Caypoint has a note &e.layout.* RouteAdapterD%etStandard7iew:. 8iven that. RouteAdapter.nflate inflater"context.findViewById:R.getTurn:..5 han les the typi%al s%enario.format:pt.view.ma%e7iew.0$ Subscribe to updates at http://commonsware.ma%e7iew. et%.5 7iew view"inflater.5 if :pt. Chere the $irst entry is a tCo3line variant'.get"romDirection:.id..5 distance. in$lating a layout populating it* private 7iew get"irstView:7iew convert7iew.. 8 7iew.xml' an les the $irst entry.waypoint. 8 .5 .marker.view.view.turn.The Tour8t Sample )pplication %lass.5 .layout.5 -ext7iew label":-ext7iew. private 7iew getStandardView:Caypoint ptG boolean stripeG 7iew convert7iew. that sub%lasses ArrayAdapter an vieCs as nee e ..view.distance.5 label..get"romDirection:.. 8 7iew.findViewById:R. signs.waypoint.ma%e7iew marker":.com Special Creative Commons BY-SA 3.g.id. RouteAdapterD%etEirst7iew:..getTitle:.id.get'arker:.5 -ext7iew waypoint":-ext7iew.5 7iew view"inflater.setImage$esource:get$esource"orTurn:pt.5 -ext7iew distance":-ext7iew.findViewById:R. in%lu ing %onverting %o es in the tour7s +#>0 into resour%es to isplay turn arroCs.tourview*stdG nullG null.findViewById:R.ma%e7iew turn":.id.5 < return:view.setText:tour..get:@.

. in$lates a tCo3line layout an populates it as Cell* private 7iew getTwoLineView:Caypoint ptG boolean stripeG 7iew convert7iew.5 distance.get"romDirection:.findViewById:R.6+).5 -ext7iew waypoint":-ext7iew.. *etails Panel 5he etails panel N the bla%k panel that is isplaye Chen you sele%t an entry in the %ue sheet N is a 7iewElipper.. 5hen.set7isibility:7.n the layout &res/layout/view.distance. RouteAdapterD%et-wo+ine7iew:.inflate:R.5 < Clearly.5 -ext7iew distance":-ext7iew.com Special Creative Commons BY-SA 3.5 -ext7iew $int":-ext7iew.getTitle:.get"romDirection:.view. .ma%e7iew marker":.0 License Edition ..The Tour8t Sample )pplication marker.id.5 $int.get"romDirection:.id.view.setImage$esource:get$esource"or'arker:pt..S.id. or eventually $or the author. .. metho .5 turn...5 < waypoint.5 return:view.get'arker:.5 < (inally.setImage$esource:get$esource"or'arker:pt.5 return:view.getViewInflate:.ma%e7iew.get(int:..5 < waypoint.5 . it is set to be invisible &android!visibility " #invisible#'.setText:distanceEormat.$int. 8 marker. it is ma e visible again &details1anel.setImage$esource:get$esource"orTurn:pt.turn. Chi%h is Chy it oes not shoC up at $irst.marker.findViewById:R.findViewById:R.get"romDirection:.temSelected:.er%ise $or the rea er.setText:pt..layout. some re$a%toring is %alle $or here to re u%e %o e upli%ation.getTitle:.findViewById:R..nflate inflater"context.get"romDirection:.5 . 8 7iew.format:pt.id. 5his is le$t as an e. in the on.ma%e7iew turn":.view.ma%e7iew.get'arker :.' an is $ille in Cith the etails $or that CaypointU ire%tion pair..setText:pt.setText:pt...get'arker :..view.tourview*HlineG nullG null.view..0/ Subscribe to updates at http://commonsware.xml'.id.W"null.getCumulati eDistance:.5 7iew view"inflater.getTurn:.findViewById:R.waypoint.5 if :pt. Chen you sele%t an item.

8 details1anel.getChildCount:.pus$*left*in.getDisplayedChild:.on1ey)p:keyCodeG event.anim.setOut#nimation:Animation2tils.load#nimation:t$isG R.5 < else 8 details1anel...5 details1anel.00 Subscribe to updates at http://commonsware.5 if :details1anel.. %ourtesy o$ the $lipping $eatures built into 7iewElipper* private void start#nimation:.setDisplayedChild:details1anel.5 if :keyCode""Mey)vent..show%ext:.The Tour8t Sample )pplication 5o manually $lipping the -our7iewActivity implements onMey2p:.0 License Edition .5 < return:super.(?.load#nimation:t$isG R.M)FC.""@. 8 details1anel.5 isElippin%"true5 < private void stop#nimation:.pus$*left*out. public boolean on1ey)p:int keyCodeG Mey)vent event.anim. 8 stop#nimation:. 8 details1anel.M)FC. 8 details1anel.setDisplayedChild:details1anel.setIn#nimation:Animation2tils.pus$*ri%$t*in.pus$*ri%$t*out..5 < < < < else 8 details1anel.start"lipping:.5 details1anel. the %he%kbo.stop"lipping:.anim.com Special Creative Commons BY-SA 3.load#nimation:t$isG R.D)*D1AD*+)E.5 details1anel.M)FC.VV keyCode""Mey)vent.load#nimation:t$isG R.setOut#nimation:Animation2tils.* support pages o$ the etails panel.getDisplayedChild:.5 isElippin%"false5 < .anim. %an toggle automati% animation.D)*D1AD*R. 8 if :keyCode""Mey)vent.5 >r.(?.setIn#nimation:Animation2tils.D)*D1AD*+)E-.03-.

TourEditActivity /y an large. Chi%h is re$eren%e in %o e as file!///android*assets.5 < < Also.5 browser..n My Lo%ation:Q button is %li%ke . as is es%ribe in the %hapter on lo%ation servi%es.nputMet$od %lass. longitu e.tensively in the %hapter on mapping servi%es an are not repeate here $or brevity.verride public void onCreate:6undle icicle.5 browser":Ceb7iew.#5 protected c$arOP get#cceptedChars:. that %onstrains input to be positive or negative $loating3point numbers* class Eloat.03 Subscribe to updates at http://commonsware.set*e!ViewClient:new Call!ack:.findViewById:R.onCreate:icicle.setDefault"ontSi2e:browser.5 browser. 8 return:C3ARS.nputMet$od 8 private static final Strin% C3ARS"#@?HINLS]AR(.getSettings:. Ce use a %ustom Eloat.browser. $or the istan%e travele $iel .BN.getDefault"ontS i2e:.$elp. 8 super.nputMet$od extends /umber..com Special Creative Commons BY-SA 3. . -our)ditActivity is Oust a $orm $or the user to $ill in Caypoint etails.5 setContentView:R.t loa s stati% )5ML out o$ the proOe%t7s assets/ ire%tory. Ce o Oust that N $in the %urrent lo%ation an $ill in the latitu e. Chen the Q(ill .0 License Edition .. 5Co things are interesting here.id.. as shoCn beloC* 9. (irst.5 . HelpActivity 5he 3elpActivity is a thin shell aroun the WebFit broCser.The Tour8t Sample )pplication Tour% pActivity 5he guts o$ -ourMapActivity are %overe e.getSettings:. an elevation $iel s a%%or ingly.layout.toChar#rray:.

load)rl:url. hoCever.5 < < /y e$ault.com Special Creative Commons BY-SA 3. the a%tivity Cas starte by another a%tivity that passe in a spe%i$i% page to vieC. up ates the layout7s Ci gets to mat%h. . 8 browser.The Tour8t Sample )pplication Strin% pa%e"getIntent:.g.. it Cill loa the home page.i!Activity 5he Confi%Activity %lass mostly loa s ata out o$ pre$eren%es. Chen the user %li%ks Close $rom the options menu'. it simply loa s in the re<ueste page* 3elpActivity private class Callback extends Ceb7iewClient 8 public boolean shouldO erride)rlLoading:Ceb7iew viewG Strin% url.5 if :pa%e""null. hooks into the WebFit broCser to ete%t %li%ks on links.$tml#.. it loa s that page instea .07 Subscribe to updates at http://commonsware.5 < else 8 browser. #in%e the only links in the help are to other help pages.$tml#.getString+xtra:1A0).$.5 Con.load)rl:#file!///android*asset/index. 5he most interesting thing here is the spinner o$ lo%ation provi ers N this is %overe in etail in the %hapter on lo%ation servi%es. .0 License Edition .load)rl:#file!///android*asset/#Bpa%eB#. then reverses the pro%ess Chen the a%tivity is pause &e.5 < < return:true. 8 view.

....................................220 A apter.........................2B2 /o......?=... -=4...............................................ieC.......--8.............................................................................88 ArrayA apter........ 22?.....................................8.........t...............t.......... ?22 Calen ar........=- /o..... ?2............................... 22B A%tivity.........-??.. --8............ -2=...... --2............................... --1 /un le.... 281........-0AlertAialog..........09 Subscribe to updates at http://commonsware...-=4 Au ioAemo...0 License Edition ................................. -?=.............................44...........................2B=..............................44... 2?1..... 2-0.................................. 2?8....... -?2... 222 /utton.............com Special Creative Commons BY-SA 3..................20 A%tivity........-2?..14 A%tionIvent................. -2=........... 220 A%tivityManager........................... -?2..... 2BB Content!rovi er........ 48.................................... 2=? ContentResolver................................. 2?1..............48.......................248 Che%k/o.....22=.................. -0-........ -B1..... 220.................................................. 2B= Content...2?2........?2 Con%urrentLinke Hueue...... 22......?08.??............................. 22B.... -22.......... 2?2..............................................-2B...... -=2.. ........................... -=2.........@ey4ord 8ndex Class AbsoluteLayout...... ?42.................................................... ?48 ContentManager..........84 Canvas.............8= Clo%ks.....?-4 AutoComplete..... 24=.... -2=.................................................... 2?= ........ 21-.......%onA apter..........282..... ?4= ArrayList... -28.................. 202 A%tivityA apter.... 41...........alues.48........... -2?.....2?..............................ieC........ 2?8.280 Content>bserver. 42.................................. -BB............ 28380 /aseColumns........................................................................... 2=1..................................88 Component0ame....... --1 AnalogClo%k......................... --8...................... -24.................-2? A apter..................... 2B? Conte................ 2B328. ?0....... 20-....... ?-............................................ 2=2....20 A%tionListener........--8..... 204..24B Con$igA%tivity....... 281..................................................................... ?0B.............................. 22B Compoun /utton...Layout........ ?01 Char#e<uen%e........... -?2.. -2?............. ?1 Chrono............................................=/uil er.21 AutoComplete5e.................................

................................................................mage..210........@ey4ord 8ndex Conte......................................................mage/utton.............?24.................. ?4Ao%ument.........0 License Edition ........... ?04 Critieria..................tMenu........................................................................mages........44 +Combo/o. -B8............ -21....14 (iel ...................... 212321B.......................... -B8........................%eption.......................82. 41.................................!hone.....44 Label...............com Special Creative Commons BY-SA 3...-2?..............?0 Laun%h............... 22?322B.3.....................?2 ......................nput#tream............-883-10 )ttpMetho ............/in er.........?22 Aialog............................................... ---...... Subscribe to updates at http://commonsware....48.................................................................... B8.................1-31? 8allery.. 212.....?42 (loCLayout............ 220................. 21B................=2 (ol er............................20 +Label......... 2+Che%k/o...44 +List.. 1? List............................................... 2?1..... ?2.........................210......... -02.....................-B8 .............................. 2?-................ 2??32?2.............................................. ?21 .....n$o.............................................................. 22?.....244.........................44 +5abbe !ane. 2=0...........-0Criteria.......................... 82 )an ler........................................ -80 AatabaseContent!rovi er.................2?2......................... 28I it........................................................ -10 8ri ........... 2B2 Aatabase)elper............... 28............ ?-=..............................=-3=4........ 2?I............224......................................201.. 8?......201 AraCable....................... 2=?........... 248.............tMenu................................?-...............10............................................................................................. 28-...............?-.....................2=........ -??.10 +5able....................ieC............. ?28.......... 22B...................-28 AigitalClo%k.... 2=2.................. -=4...........nputMetho ... 22B... ?42.................. ?21 Aialer....2== Aate(ormat...88 Aire%tion... -B1 ...........-1B (ore%ast...48.pan ableList..... --2.........ieC...............................2-0 Linear............... 82 8etMetho ................nput#treamRea er....... 21......................................ntentRe%eiver...... ?42.......... 2==................................terator.....=B LinearLayout.2=?..8? Aate!i%kerAialog.......................................................... 281 ListA%tivity........?2 (loat.................................................. -80.... ?0B...... 211 ....................... 212 Cursor.............8?..........................................................................................-2?3-28.................................... 2B? CursorA apter...................................-88 .......... 22B ...............ieC................20...84 Aate!i%ker.......................... -=2..................................................................................................... -1.....................................2B 8ri ................-88.....................................................?-........ ??1 ....................... 1?.-=4 Aouble.................. -88.....................-00............... -0Conte..................................................................... 2=4........................................................................................... 204 ...........................................42 Cursor(a%tory........................... 214 )elpA%tivity................................................20B....................-=2 .................................................................. ?-= ..........-=?...........-1(rameLayout.. ?48 )ttpClient..............................nputMetho ............................................................. -B8..........ntent................................................... 84 Aea >bOe%tI......................................2?B +/utton.4B.......... 12..................42....................... 222........................................................ 2B..........ieC...........................

..........2-4.........-=2 >utput#treamWriter.............................?=Mail/uKK........ 2??............. =8................. 212................elCal%ulator............................................... -22 MessageCountListener........-?1 !rogress/ar..................................... 210 Lo%ation......... 242 MailClient.................. ?2= Me ia!layer.. 2?=................................ 2->nCompletionListener..................................................... 2B8 !i%kAemo.-=2 >verlay.........................................................................??4 Lorem/ase................. 22= Mail/uKK#ervi%e................................ ?-0 >verlayController.....-=2 ................. -2-......-0-.....................2883210.......................2113?0= Me iaController.........?0-............................. =0......tMenuListener... ?4? Lo%ation............................................ -2B.................................280................ -2=............................................?=.......??2 LoremAemo.22B !ar%elable...............................?01 !oint... 22?..3( Subscribe to updates at http://commonsware...........281 !ro.... 84.......tem....................................?04 Lo%ationManager....................................8=..?08 !a%kageManager. =8............ 84 >n... -24...........................imity........... ?013?-!ostMetho ............ -00............................... ?B..........?-1 >nAate#etListener.... 214.............-0>nChe%ke ChangeListener...................................tem#ele%te Listener......................-1= Map...........18.....248 !i%k.....-1= MyA%tivity................................... 280oC..............................?22........... =1 Rea Write...................-8B.............@ey4ord 8ndex ListA apter................ 212 Lorem.... =4............. 2==.........................8=........... 2?2..20............................ 24=.......... -0? >n!repare Listener...................................................... 84 >utput#tream.. ?4!rovi erWrapper.........0 License Edition ..................................ieC....... ??1.... ?8...............................113-0-...................................................-81.............-02 Message...................................22 >n!opulateConte.......... ?0B Map......... ?20 Menu................................................................................... -=0.................. 24?.................-0= List............................ieC.............................. 21?.....................2??...44 ListAemo..................... 248 MapA%tivity....................... ?=Lorem#ear%h... -24.............?-B.......22 >bOe%t................................................ 24B..............................................2113?0MapController..........................................2883210........................-1...........................-88 !re$s.............................. 280...................?083?-0 !i.................................................................. 22? Menu................... 20..... -?2.......................................24?................................ 220......................................................com Special Creative Commons BY-SA 3.. 211...........?-1 >n5ime#etListener................................................................?02... .-?=... ??4............................ ??1 ListCellRen erer.........14...........................?08.... 220........ 280oti$i%ationManager....................ntentRe%eiver........................2B8 !i......................22= 0oti$i%ation.. 22..............................--1............................. ?-4........... 82.. ?0?................................. ?-1............... -21 !rovi er............24?...... .......ntentRe%eiver...................................?23=-........................... -88............... 22B Menus... -2B.. -02.48.... =-.............................elConverter...... =4 Ra io8roup................21= Ra io/utton..................... 28 0oCRe u...................... -=0 >nCli%kListener....?2...........10........ ?0B Lo%ation!rovi er.... 2=232B2..........................................??1................ 212.. -1?................................... 2-....................................... ?02...........

21=.40 #%roll......................B43B8 5ab#pe%.....1-31? 5e........................................................ ?44 "................................................................................... 40.... ?4B.....@ey4ord 8ndex Re%t(........................................ 2?4............................................. --8....2?....... 2??..........ieC.... 2-0....................ieC................. ?42.........?00.... -2?... 2B=............. 213?-..................-243-28.--= Web........ 2?2........... 2?=............... -B8............. 20?320B.-==........ ?40........ ?-Runnable....... 21?..?08.............. 2??........................................................................... ?45ourI itA%tivity..24=.......... 2-...............--2.......-88......................2B8 #ervi%e......................2?2.. ?42 5ourMapA%tivity.................... 2BB..............i eo........ -B=... 22=.................... 21-............. 8= 5ime!i%kerAialog.............--2............ -B= #pinner.................... B=.-2?3-2B #HLiteHuery/uil er..... 280.................24. 82................. -B4.............................. 84................ 2=2 #tati%.............................. 2=4.2?2..... ?1. 8=......-2?...................................... 202.... B-... 20-........ 2--.............. -22......=-.........?-...................... ?-=......... 1=............................2=2 #e%urityI.................... ?01... -?2.......-10 WebFit.......3% Subscribe to updates at http://commonsware....... ---3--B Web.. -10 Web#ettings.12 5abA%tivity.....8?..... 22132?2...........................................................................................................B1 5ableLayout........... 84 5imer5ask........... 2?-........................................ ?08.. 2=4................................................................................?42...........-4-........1-31= 5able...... 28?............................ B43B1 5ableRoC....... 201......-B?............................. ........................22=3224 #ession..... ?42 5our...................................... 2?232=?.......tWat%her... ?42 5our...... 282..................................... -0-.........-?8 #impleA apter...... -22.........0 License Edition .........5hrea "tilities........... 220................... -88...............?2-3?2= .. ?2...... -2=................................... 2=432B2.... ??4 5e....... B0..?-Relative........2?8............ 22.... ?0=................................ -28....... -28 .ieCA%tivity..........-1B #hare !re$eren%es. ?40...... 42...............................-B= 5ab......................... 248 #trings....................................... ?4Weather..... BB......=-............ --8..........................................................................................42 #impleCursorA apter... -2?....................................... --? Eml!ull!arser... -28 #%roll.............. ?=..................i eoAemo....................................... B1 Resour%es............. ?42..... 2?? #HLiteAatabase....................... ?02...........-023-01.1?............com Special Creative Commons BY-SA 3.......244 5oast............. 42...................11................. --1...... -4RouteA apter............... 28...................................... 2?=.... 241 #ervi%eConne%tion..........................ieC.... ?-5our............... ?40.....................................................................t......=-.....%eption................................B? RelativeLayout....ieC(lipper................... ?44 Waypoint........ 22.......................................?4= Route>verlay.?00 5ourListA%tivity.....................2?2.ieCClient.............20............... ....................................... -28 "ri...........t. -2-.......... ?42 5ab)ost............................ ?42................... -4#tore..21............ ?-B ..... -42 .................................ieC............. 42 #e%rets!rovi er..8?...................... ?4?...........................-1B #tring11.................................................................. 220..2??32?B...... 80 5ime!i%ker......... -10........ B8... ?4? #panne ............ --8.12. 12............-=?.. -00...........ieC.......... ?0B... 2-B32-2............-88 WeatherAemo.............?2? ......... 1= 5abWi get.....2?2....... 24........................... 200........

......288 ACCI##W8!#.....20A..........>0.............................IA......A.........................................20/............................................................@ey4ord 8ndex Command a b pull.................0#IR5WAC5....3..........8..............................CFWAC5..............202........ 202 MA5C)WAI(A"L5W>0L@....com Special Creative Commons BY-SA 3.2?!IRM......................................................--8 MA...............................-8-..-22 LAR8IR...........................................................R#5.......................................24!IRM......0AWA"5>WCRIA5I......288 ACCI##W!>#..................20(.....................................................................................................................5WAC5.........IWCA5I8>R@.....M>05AL....................................... 2=? !..............>0............>0...........................................>0......-4- ....-88 8I5WC>05I05WAC5.>0W8RA05IA.#5IAW8!#...... 1 ant install.............-88 ................................##....20-...................................>0..........202 )>R.......................................................................288 ACCI##WCILLW...5..........................................05I8IR.................................>0WAI0......--8 LI085)W#)>R5.................................. ?=8 a b shell.............................................................202.... 20= LA"0C)IRWCA5I8>R@........................................... 2?1 AILI5IWAC5.......................-1B ................................................-4(AC5>R@W5I#5WAC5...............................................................................11 8AA8I5WCA5I8>R@.................. 2?-...20..202 LI085)WL>08...............................................202 CALLWAC5.......................... ?=8 ant.... -2B.........202 0"LL................................................................20)>MIWCA5I8>R@............................##........................... 2-2 !>LL............................-2= Constant ACCI##WA##...................20C>05I05W"R.2B= AI(A"L5........20-....288 AL5IR0A5IWCA5I8>R@...................................-2B >RAIR /@.............??B IA.......................................-8a b push...0/>E.........................................................22B MIA...................=2 .22B /R>W#A/LIWCA5I8>R@.........-2B........0 License Edition ...................... -24......>0...........>0...........................................2003202................................... ?2?........................ 22= A0#WIRWAC5..................>0............................................................... -24 ...................................................ALWAC5.......................>0..................................................................................................................A......................................0#IR5......20A................................... 2-0...0.............24!....I......................................................>0..................................................................244............. 241 !>#5....................ALIRWAI(A"L5WFI@#...AWM>"05IAWAC5.................... -84 s<lite?......................20-.........................20-.....-80........20AI(A"L5WCA5I8>R@.....................................................................................................?=2 e........ 2-4.-80 I0AW5A8.............-22...................................................................202 8I5.............................................................>0.......--B LA"0C)IR......................2003202 I0AWA>C"MI05.....................................0WAC5..................-8B...................................20= MA...........5@WAC5............. Subscribe to updates at http://commonsware........................................ 22B AILI5I.................>0......................... 22= AL5IR0A5...................22? AL5IR0A5..CFWAC5......>0............

.................... ?8 %he%kA%%ount&'................................... 11 ...................................................................................... 2=132Ba a a a a a a a &'.............................--- ................242 RI#"L5WCA0CILLIA..............-28 apply(ormat&'................--%an8o(orCar &'................................ 2?1...-00.............................................................--B #5AR5W5A8......................................>0................................200.................................ntent#erialiKe &'...... -28.........................................................................1= appen Where&'.3$ Subscribe to updates at http://commonsware.........imityAlert&'................................... &'..................................... 2?8 ................... 202............-45................................................................... 201...........tChange &'...................=2 ................................--%an8o/a%k>r(orCar &'...................................................202 5IE5.................................202 5A8WAC5............................................>0..............................................R#5W"#IR...............................................-00 #ubMenu&'....................... 2-2......................................................280........................................................................................2?= "!AA5I....21? #eparator&'......................... 28%an8o/a%k&'.....................................2?2 R..........................................ntent>ptions&'.... -42 #"0AA@...........2?0 ................2-0................. 22?322B Menu&'.............202 W)IRI....-?8 &ethod %learCa%he&'......241.......................................20#IARC)WAC5..........com Special Creative Commons BY-SA 3............2-0 RI#"L5W>F.............. 2=4..........................@ey4ord 8ndex !RI(IRI0CIWCA5I8>R@.............................................-10 buil Huery&'.IW#M#...................................IR5...................................................... 2?2...............18. 24-...................................202 5A/WCA5I8>R@.................................8= #@0CWAC5...................24%lear&'.........-28 bulk.....................................--%enterMap5o&'............................ 2-2 R"0WAC5.............mpl&'........................22? 5I#5WCA5I8>R@...............................................-2B3-28........................................................................>0.................IWCA5I8>R@..................2B8 RICI................... 242 broa %ast.................................................................................. 2?-...............20#I0A5>WAC5.5LI...............-22........................22B............................22 RIAAWC>05AC5#............................2?8 %all&'........................................?02 %he%k&'................2-0.......................................-00 !ro..80 bin #ervi%e&'.............>0..........nsert&'..-B4 applyMenuChoi%e&'...............................-0= be$ore5e.>0.....................................202 !R>+IC5....>0.................. -21 #ILIC5IAWAL5IR0A5.....................................>0......... 2-4............................................................................................>0...........?2............. ?-= WI/W#IARC)WAC5...................................... 2?8..........................2-0 buil (ore%asts&'..................20-.......ntent&'.>0.............2-0 RI#"L5W(..............................................................................-00 5ab&'..................-2B..............................................?243?28 %an%el&'..202 #I0AWAC5........... -24.................-4-...............0 License Edition ..........CAL....................................... ??1 #ILIC5. 224 broa %ast.....................IWWAC5..................... 220 %he%kA%%ount.......20#MALLI#5................................................. -24..................................................................220 %he%kCalling!ermission&'...............................

..............................?1 get!arent>$5ype&'.............................................. 222 enable!oll&'.............. -=1 $irst&'.................................-81 getLongitu e&'.?2 getColle%tion5ype&'.....-1get&'........................210 get(loat&'....................nteger&'............................................... 2?1................................2?2......................................................................................................-80 ial&'..........220 en Call&'.................................................?08........................... 2?B generate!age&'................................-80.................................................................................281 get>utput#tream&'..MA!Message........?0? getMapController&'..............?01 raC5e........................-2B.......................2BgetColumn.............22B get!arent&'..........................................................................??4 getLastFnoCn!osition&'.................................................................................................-2B getAs#tring&'....................-?8 getChe%ke Ra io/utton................?243?28 raC&'...nput#tream&'....................2B2 eleteRoC&'.............. s&'...............-81 getLo%ation&'.-2B getAttributeCount&'......................................................... 28...............................2?1 get!a%kageManager&'..................................... 2?4 get...........................................2?4 get...............n e................ -=?.... &'.................................... 2B= getCurrentLo%ation&'..................................................................-21 getContent!rovi er&'........................................................com Special Creative Commons BY-SA 3...............210 get/oolean&'.........-2?............. ?0$inish&'......?01 e it&'...................?24 e<uery&'...........................@ey4ord 8ndex %learChe%k&'....?2 %lear)istory&'......................................... -8elete&'..............................................................nt&'.............-21........................................................................................ 2B0.................&'..........-42 get/earing&'.................................................................... =0.......................-=2......3/ Subscribe to updates at http://commonsware........................................................................................................... -2=.................................................. 1=............-21 getColumn0ames&'.......... -2B $in ..............-21 e.................................................................................................................................................-=0...-?8 %ommit"p ates&'........................................................................................................................................................................2?8 getContentResolver&'.......... 2B2 eleteAatabase&'..........................................................................-1B get0ame&'..-1B get................................210 getLatitu e&'..........................................................................-2B getAltitu e&'........................ntent&'......................................................................... -80 %ommit&'.......................................................... &'.....................-?8 enable&'....................................e%#HL&'.........t&'.................................248..................... -24.......................................................... -21.................................................-2= elete.nternal&'.-21 %reate&'................. s&'..............?0getMessage..............?01 ...................................................................................................................-42 getAttribute0ame&'..........2?1 get...................210 get/est!rovi er&'.............................ieC/y.....210 getAs....-2=.........................................................-21......................=0 get!ointE@&'......................................................... 2?2 %ount&'.............................--%lose&'........................22...................... ?01 raCCir%le&'..............................................................................--1 %reateAatabase&'.........0 License Edition ...-81 getMapCenter&'.

..................................................................................?24 is#atellite&'...............................................................................2B2 isA$terLast&'.....2=8.......................210 has#pee &'................2Bget#pee &'.... --0 loa 5ime&'..................................................--go/a%k>r(orCar &'................................... 22.......--= get#hare !re$eren%es&'.-01........................ 2-4 on/in &'....................?0= is#treet...2=1 getResour%es&'........ 2?4 get#tringArray&'................................244.......................?0= is5ra$$i%&'...............t&'..................................................2?-32?= move&'............................................. =8............................. -21.........................................................................42....................................210 in%rement!rogress/y&'.................... 224 is(irst&'............2?B loa Aata&'.-4-...........................................................................................................................................-4go/a%k&'...................................................................................................-=? getRoot.............. -21.......?1...............................................1?.......-21..............................................................................................................................................................................................................2?4 is>$$hook&'.................................................................................................... 2B0 isInable &'.-083--0 makeMeAnA pater&'.........................210 get#tring&'...........-?2........................................2?4 isChe%ke &'........................................................................-80 neC5ab#pe%&'............2B=.....................................................................-2B........... 2=8....................................................................................10 get!rovi ers&'...........com Special Creative Commons BY-SA 3........................................-B?..220 get!>!?Message..................................................................................................................................t&'.......................@ey4ord 8ndex get!oll#tate&'...........2?4 move5o&'.......................................... 241 onChe%ke Change &'.............................................. ?2 isColle%tion"ri&'.......??1 make5e............................. 2?8.....-2= onA%tivityResult&'...................-?2........................2?4 is(o%use &'.... 2BB obtainMessage&'.........................................?0= is"... -?8 get!rogress&'......?1 isLast&'..............................5hrea &'............. 1= ne.......................................... -=2 ..............................................30 Subscribe to updates at http://commonsware............210 has/earing&'...............2-0.. s&'.........................................................................2?4 is0ull&'.................................... -B4.............--8 manage Huery&'..................................................................... 2B? insert.......................ieC&'...........ieC&'.............-1B get!re$eren%es&'........ 2=B............ 2?4 noti$y&'.........................................................--go(orCar &'......281 getRe<uire Columns&'.............................................ieC&'.................................... -?8 get#ingle5ype&'....................................--? loa "rl&'................ 28noti$yChange&'... 2B2............................nternal&'.........................................-4B get5itle&'.. 2?B getEml&'..........................................-2=................................ 2?4 is/e$ore(irst&'.......................2B-..........................................................................................2?2 get5ype&'.. 2=1........................................................................-28 last&'.... -24 hasAltitu e&'................................ 2B2 get............................................?=....10 insert&'................................=0 get#ettings&'.........?B......................................2?4 neCCursor&'......................................................................280..............................--han leMessage&'....................0 License Edition ...............

.....................................ntentA%tivity>ptions&'.............................................-28 .... ?0B run>n"................................... 2B? <uery....................22B.......2?4 put......-22 prepare&'...............tem#ele%te &'...............................-=2..............-??........ -?= onConte........................... -0-.............22B <uery.......-?8 remove!ro............... -=0.?1 re<uest"p ates&'........... 24.................. -=1..... 18...............................-0?.............. 2==......................... ?21.................................................. -?=................................. 21-..........ntent&'............22B............ ??1 onCreate>ptionsMenu&'.......... -?= on...... 2=2.....................33 Subscribe to updates at http://commonsware........?4B onFey"p&'....... -08................. -80 registerContent>bserver&'..................... -??........... -81................. -=4.......................... 2=4........................................................18.............................2=1 populateMenu&'...................@ey4ord 8ndex onCli%k&'..-??........... ?20 prev&'...................................ntent&'.........................??4..............-80................................. 24= on!opulateConte.............................................. -=0........................................-?=......................... 2B2......80 on5ooManyRe ire%ts&'....................................... =8.................?-B.............................20..............-??. 204................2?4 post&'...... 2?=.. -0?..-24........... -=0.................................... 244 on(reeKe&'.. -28 postAelaye &'....................... 24=...... ?8........--2 on!ause&'............ 2?2 re<uest(o%us&'.................113-0-.....................2B= register.........................-0onRe%eive )ttpAuthRe<uest&'...-??.... ?-1........................-?= onResume&' -??....... -=1.........?-B.................................................5hrea &'..--remove&'.....................-243-28..................................... -?=. 24=........................................0 License Edition ................ -=0........................?-B prepareAsyn%&'................nput&'.......................................................?44 onList................... ?0?............. -0= onCreate&' 20.......... ?-0...................................................... 222 on#top&'..................tem#ele%te &'....................................-=? pause&'............ 24=3244...............41 on0eC..-24.............................................. ?2= play&'.....--2 openAatabase&'.........--2 onRe%eive.........21? remove"p ates&'......?-0...................... -B4......... 24=............................................................?2= populateAe$ault. 224 on#ervi%eAis%onne%te &'........ ??4..................................... -10.....2B2 raCHuery&'.............. -0= onCreate!anelMenu&'........................-00 onAestroy&'....... ?-on5e..................... 22....... -=1 open(ile>utput&'.................... -22............ 224 on#tart&'.tMenu&'.....................212 re<uery&'....??B on#ervi%eConne%te &'..........t....... ??B...........................................................................imityAlert&'....nt&'........................................2?2 put#tring&'.......................................................temCli%k&'. ??1 on>ptions...-0-........204 releaseConne%tion&'................................... -?=...........................................................................................nternal&'........... 204 onRestart&'... -=0 on5ap&'............... -0= on!age#tarte &'...............tem#ele%te &'.......-88 reloa &'.......... -00. -?23-?=...........ntent&'......... 2onComplete5haC&'..... ?0B on#ear%hRe<ueste &'... -=1 openRaCResour%e&'.........................................................alues&'.............................2?2 <uery&'...............................-22...................212...com Special Creative Commons BY-SA 3............................ 2-.................. 2B2..........20B.................. -0= position&'................-=2................................................ 204......-2? open(ile....... -80........tChange &'..

...........?1 set(antasy(ont(amily&'...11 set>nCli%kListener&'......................................................................................................ieC&'........................B1 setColumn#hrinkable&'............................. -=1 set>nCompletionListener&'.@ey4ord 8ndex sen Message&'.........com Special Creative Commons BY-SA 3....................48............................................................................20............................................--1 set0umeri%#hort%ut&'...................--= set(olloCMyLo%ation&'........................................................... 2B..................tem#ele%te Listener&'.....18..............................................................................................................................2= setup&'...............................................................................................--1 set0eutral/utton&'........................................................................................................................ 224 setColumnCollapse &'...............................................................24B............................................................. 11 set)ea er&'.........B1 setContent&'..............................%on&'.......................................2set5e.................................................1?..............1=..........................210 setA apter&'............................................................--B setAe$aultFeyMo e&'...................................--B setLayout......................................mage"R..........?0B set8ravity&'........ 1= setContent..............-28 setHCertyMo e&'..?set..............................-0set>n!repare Listener&'......11 setAltitu eRe<uire &'......??B setAropAoCn.................................................B1 setColumn#tret%hable&'..........t&'..............1= setAata#our%e&'..... ?20 setup5imer&'.......................11 setResult&'...................................... 2B set>n!opulateConte.....................=2 set!a ing&'................== set8roupChe%kable&'.............................................210 setCellRen erer&'........?=.............-2= sen MessageAt5ime&'...................................--1 set5ype$a%e&'..............ieC&'..........20 setAuration&'....24 setListA apter&'.. 1= set.-2= sen MessageAt(ront>$Hueue&'......................... --B set+ava#%riptInable &'.......................................................................................................................................................................210 setCurrent5ab&'.............== set!ositive/utton&'............................................. ?8..............37 Subscribe to updates at http://commonsware....................................................................................-2= setA%%ura%y&'..--1 set.20................11 set+ava#%riptCan>penWin oCsAutomati%ally&'...--1 set0egative/utton&'....................................................--8 ..?-1 set>n..............................44 setChe%ke &'................................................................................-2= sen MessageAelaye &'.............--B set5itle&'...................................10 set!roOe%tionMap&'............................. 20..............................2-0 set5e....... =0 setCostAlloCe &'....48............................... 244.................................................................................................................................................t#iKe&'..............?-B setAe$ault(ont#iKe&'...0 License Edition ........-00 set........--1 set!rogress&'..... -=2..............1?................................n i%ator&'............................................ 220 set"seAesktop"serAgent&'............................... 20..................--8 setInable &'...............................................................ieCResour%e&'.....--B set..............tMenuListener&'..........temChe%kable&'...................................................................................................41 setMessage&'...&'...............................................?-1 set>rientation&'................... 28 setAlphabeti%#hort%ut&'..ieC&'.........................................................................

..............................................................................?0= toggle#treet.....-2B..................................................B2 ...............................................................................................................................39 Subscribe to updates at http://commonsware......-? an roi *layoutWabove............................................................. B-. 2=132B? up ate...................................................................................................................................................... ?20 stop!layba%k&'................................................................ -2-................................................. 220 start#ervi%e&'...........ieC&'....................... 2B= an roi *auto5e................................................--2.............................?-B................2B2 up ateLabel&'.............................. BB an roi *layoutWalignRight..............B2 an roi *layoutWalign!arent/ottom.....................................................................0 License Edition ................................................................ieC&'.... 24...................................................ntent&'....t.?=...........?2 an roi *label........2-0................................................ 2-4 stop&'.............................. ?2= shoCList&'..............................2B.......................................................................................................B2 an roi *layoutWalignLe$t......... 2-0.........?an roi *ba%kgroun ....-80 up ate5ime&'...........................222 support"p ates&'......nt&'..................B2 an roi *layoutWalign/aseline.................................Ban roi *layoutWalign!arentLe$t.com Special Creative Commons BY-SA 3.... ?2 toggleI geMooming&'.20 up ate............................................................................................28 an roi * igits................ 2?8.....?0= to#tring&'.2= an roi *i ... --? shoC&'..............................?24 toggle#atellite&'..................?an roi * raC#ele%tor>n5op.........nternal&'..........?-B startA%tivity&'........................................................-00 toggle&'..........................--8................... 1-31? an roi *in eterminate............................................................ -24..............@ey4ord 8ndex setWeb...?24 start&'.... 82 an roi *horiKontal#pa%ing.....................................?0- Property an roi *authorities.................................Ban roi *layoutWalign!arentRight...................Ban roi *layoutWalign!arent5op...................224 unregisterContent>bserver&'..........?02 upgra eAatabases&'.........2-...................................................................................................................?1 an roi *%apitaliKe..........44..........................204 up ate&'.......................................... 2?2..................................................-21 sCit%h&'............................................ieCClient&'...............................B-....................................................................B2 an roi *layoutWalign/ottom.................... ?2...................................84 up ate#tring&'..............................?02 toggleRa io>n>$$&'........?an roi *%ollapseColumns..............................................2= an roi *%ompletion5hreshol .222 start#ubA%tivity&'...................B1 an roi *%olumnWi th........................................................................................................282 sRa io>n&'............... 281 unbin #ervi%e&'..................................................--2 shoul >verri e"rlLoa ing&'..................................................... --1........?4? shoC0oti$i%ation&'.....?2= stop#ervi%e&'.........2BB unregister................201..................10 an roi *in eterminate/ehavior...............2B2 Koom5o&'.......10 an roi *inputMetho .........................................................................?0= toggle5ra$$i%&'.......2B?.................-80 up ate..................

......2B........................82 an roi *sr%...........2B......................2= an roi *visibility....10......................B2 an roi *layoutWCeight.......2B................=2 an roi *pa an roi *pa an roi *pa an roi *pa an roi *pa ing......?an roi *permission.......................................................B8 an roi *stret%hMo e......................................Ban roi *layoutW%olumn.......................................................................................?an roi *stret%hColumns................Ban roi *layoutW%enter......t(o%usLe$t...............................................t(o%usAoCn.......................=B ingRight...........?1 an roi *numColumns..........21......... B? an roi *mani$est...........................................................................................................................................................................t........................... 21 an roi *te.......................................B8 an roi *singleLine.................................................................@ey4ord 8ndex an roi *layoutWalign5op....... 220.........................?2 an roi *progress................ Subscribe to updates at http://commonsware........... -2B an roi *name.......?=an roi *verti%al#pa%ing...... 2B8............?0..... B?............................................................B2 an roi *layoutWgravity.............==......?1 an roi *ne.............................................?-.............................................................=B ingLe$t.................B2 an roi *layoutWtoRight.........................21 an roi *value.....................................................................................?1 an roi *ne...............................................2= an roi *numeri%........=? an roi *layoutWCi th...........2= an roi *te.... 22an roi *phone0umber..................10 an roi *shrinkColumns....................................t(o%us"p....0 License Edition ......................... 2B?..................................t(o%usRight........................ =?.................=B....tColor........ =B ing/ottom................t#tyle...............................................................................................-2 an roi *ma............................. B? an roi *layoutWbeloC.....240.............n!arent......-?.................=B ing5op.== an roi *layoutWheight.................................................?1 an roi *ne.?1 ........com Special Creative Commons BY-SA 3........... ?= an roi *te.erti%al.........................................................................................?an roi *orientation....B2 an roi *layoutWtoLe$t....................82 an roi *spinner#ele%tor......B2...... 12 an roi *passCor .................................................................. 12 an roi *layoutWspan.................................................. ?2 an roi *spa%ing. ?=an roi *ne......Ban roi *layoutW%enter............................................................... =2..........................7........................................................... =?. ?an roi *type$a%e..............................B2 an roi *layoutW%enter)oriKontal..................................