The Busy Coder’s Guide to Android Development

The Busy Coder's Guide to Android Outgrowth by Mark L. Murphy The Busy Coder's Guide to Android Outgrowth by Mark L. Murphy Copyright © 2008 CommonsWare, LLC. All Rights Reserved. Printed in the United States of America. CommonsWare capacitys may be purchased in stereotypeed (bulk) or digital produce for educational or share use. For further notice, continuity [email protected] com. Printing History: Jul 2008: Version 1. 0 ISBN: 978-0-9816780-0-9 The CommonsWare allure and logo, “Busy Coder's Guide”, and connected marketing clothes are marketingmarks of CommonsWare, LLC. All other marketingmarks relationd in this capacity are marketingmarks of their relative resolutes. The publisher and producer(s) postupast no uniformly for gravitateacys or omissions or for satisfaction resulting from the use of the notice contained herein. Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Table of Interruption Gratifying to the Warescription!.................................................................................. xiii Preface.......................................................................................................................... v Gratifying to the Book!........................................................................................................... xv Prerequisites.......................................................................................................................... xv Warescription....................................................................................................................... xvi Capacity Bug Bounty....................................................................... .......................................... vii Fountain Appoint License.......................................................................................................... xviii Creative Commons and the Four-to-Free (42F) Guarantee............................................ xviii The Big Picture................................................................................................................ 1 What Androids Are Made Of................................................................................................. 3 Activities........................................................................................................................... Satisfied Providers........................................................................................................... 4 Intents.............................................................................................................................. 4 Services............................................................................................................................. 4 Stuff At Your Disposal............................................................................................................. Storage.............................................................................................................................. 5 Network............................................................................................................................ 5 Multimedia....................................................................................................................... 5 GPS................................................................................................................................... Phone Services................................................................................................................. 6 Purpose Structure............................................................................................................ 7 Spring Contents.......................................................................................................................... 7 The Sweat Off Your Brow....................................................................................................... 8 iii Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 Permit Edition And Now, The Cessation of the Story............................................................................................. 8 What You Get Out Of It......................................................................................................... 9 Incountenance the Manifest........................................................................................................ 11 In The Beginning, There Was the Root, And It Was Good................................................. 11 Permissions, Instrumentations, and Applications (Oh, My! ............................................. 12 Your Impression Does Something, Right?.......................................................................... 13 Creating a Skeleton Application................................................................................... 17 Begin at the Beginning........................................................................................................... 17 The Activity............................................................................................................................ 8 Dissecting the Activity........................................................................................................... 19 Edifice and Inferior the Activity....................................................................................... 21 Using XML-Based Layouts............................................................................................ 23 What Is an XML-Based Layout?........................................................................................... 23 Why Use XML-Based Layouts?............................................................................................ 4 OK, So What Does It Look Like?.......................................................................................... 25 What's After a opportunity the @ Signs?.................................................................................................... 26 And We Attract These to the Java... How?........................................................................... 26 The Cessation of the Story............................................................................................................. 27 Employing Basic Widgets............................................................................................. 9 Assigning Labels.................................................................................................................... 29 Button, Button, Who's Got the Button?.............................................................................. 30 Fleeting Images...................................................................................................................... 31 Fields of Green. Or Other Colors.......................................................................................... 31 Cool Another Box to Check.................................................................................................... 4 Decline the Radio Up................................................................................................................. 37 It's Totally a View.................................................................................................................... 39 Helpful Properties........................................................................................................... 39 Helpful Methods.............................................................................................................. 39 Afloat after a opportunity Containers............................................................................................. 1 Thinking Linearly.................................................................................................................. 42 Concepts and Properties............................................................................................... 42 Example.......................................................................................................................... 45 All Things Are Relative..................................................................... .................................... 50 iv Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Concepts and Properties............................................................................................... 50 Example.......................................................................................................................... 53 Tabula Rasa............................................................................................................................ 56 Concepts and Properties............................................................................................... 56 Example.......................................................................................................................... 9 Scrollwork.............................................................................................................................. 60 Using Selection Widgets............................................................................................... 65 Adapting to the Circumstances............................................................................................ 65 Using ArrayAdapter...................................................................................................... 66 Other Key Adapters....................................................................................................... 7 Lists of Naughty and Nice.................................................................................................... 68 Spin Control........................................................................................................................... 70 Grid Your Lions (Or Somesubject Apconfirm That... )..................................................................... 74 Fields: Now After a opportunity 35% Less Typing!...................................................................... ............... 78 Galleries, Produce Or Obtain?} The Art........................................................................................... 2 Employing Fancy Widgets and Containers.................................................................. 83 Pick and Choose.................................................................................................................... 83 Boundlessness Keeps Flowing Apconfirm a River......................................................................................... 88 Making Progress.................................................................................................................... 89 Putting It On My Tab........................................................................................................... 0 The Pieces....................................................................................................................... 91 The Idiosyncrasies.......................................................................................................... 91 Wiring It Together........................................................................................................ 93 Other Containers of Note..................................................................................................... 96 Applying Menus............................................................................................................ 7 Flavors of Menu..................................................................................................................... 97 Menus of Options................................................................................................................. 98 Menus in Context................................................................................................................ 100 Taking a Peek....................................................................................................................... 102 Embedding the WebKit Browser................................................................................ 07 A Browser, Writ Small......................................................................................................... 107 Loading It Up....................................................................................................................... 109 Navigating the Waters.......................................................................................................... 111 v Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Juicy the Client......................................................................................................... 11 Settings, Preferences, and Options (Oh, My! ).................................................................... 114 Showing Pop-Up Messages.......................................................................................... 117 Raising Toasts........................................................................................................................ 117 Alert! Alert!............................................................................................................................ 118 Checking Them Out............................................................................................................. 19 Dealing after a opportunity Threads.................................................................................................. 123 Getting Through the Handlers............................................................................................ 123 Messages....................................................................................................................... 124 Runnables..................................................................................................................... 127 Inferior In Place.................................................................................................................. 27 Utilities (And I Don't Balance Water Works)....................................................................... 128 And Now, The Caveats........................................................................................................ 128 Handling Energy Lifecycle Events.............................................................................. 131 Schroedinger's Activity......................................................................................................... 131 Life, Death, and Your Activity............................................................................................. 32 onCreate() and onCompleteThaw()............................................................................ 132 onStart(), onRestart(), and onResume()..................................................................... 133 onPause(), onFreeze(), onStop(), and onDestroy()................................................... 134 Using Preferences........................................................................................................ 137 Getting What You Want...................................................................................................... 37 Stating Your Preference....................................................................................................... 138 A Prelation For Action...................................................................................................... 138 Accessing Files............................................................................................................. 143 You And The Horse You Rode In On................................................................................. 143 Readin' 'n Writin'................................................................................................................. 47 Afloat after a opportunity Resources.............................................................................................. 151 The Refountain Lineup............................................................................................................ 151 String Theory........................................................................................................................ 152 Plain Strings.................................................................................................................. 152 String Formats.............................................................................................................. 153 Styled Text..................................................................................................................... 153 Styled Formats.............................................................................................................. 154 vi Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Got the Picture?................................................................................................................... 58 XML: The Refountain Way..................................................................................................... 160 Miscellaneous Values........................................................................................................... 163 Dimensions................................................................................................................... 163 Colors............................................................................................................................ 64 Arrays............................................................................................................................ 165 Incongruous Strokes for Incongruous Folks.................................................................................. 166 Managing and Accessing Local Databases................................................................... 171 A Fleet SQLite Primer........................................................................................................ 172 Start at the Beginning.......................................................................................................... 73 Setting the Table.................................................................................................................. 174 Makin' Data.......................................................................................................................... 174 What Goes Around, Comes Around................................................................................... 176 Raw Queries.................................................................................................................. 176 Regular Queries............................................................................................................ 77 Edifice after a opportunity Builders................................................................................................. 177 Using Cursors............................................................................................................... 179 Alter for the Sake of Change................................................................................... 179 Making Your Own Cursors.......................................................................................... 180 Data, Data, Everywhere....................................................................................................... 80 Leveraging Java Libraries............................................................................................ 183 The Outer Limits.................................................................................................................. 183 Ants and Jars........................................................................................................................ 184 Communicating via the Internet................................................................................ 187 REST and Relaxation............................................................................................................ 87 HTTP Operations via Apache Commons................................................................... 188 Parsing Responses........................................................................................................ 190 Stuff To Consider......................................................................................................... 192 Email balance Java......................................................................... ............................................ 193 Creating Eager Filters................................................................................................ 99 What's Your Intent?............................................................................................................ 200 Pieces of Intents.......................................................................................................... 200 Accumulation Options............................................................................................................... 201 vii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Eager Routing............................................................................................................. 02 Stating Your Intent(ions).................................................................................................... 203 Narrow Receivers................................................................................................................. 205 Launching Activities and Sub-Activities..................................................................... 207 Peers and Subs..................................................................................................................... 208 Start 'Em Up........................................................................................................................ 08 Fashion an Intent............................................................................................................ 209 Fashion the Call............................................................................................................... 209 Finding Adapted Actions via Introspection............................................................... 215 Pick 'Em................................................................................................................................ 216 Adaptable Adapters............................................................................................................. 20 Would You Apconfirm to See the Menu?..................................................................................... 223 Asking Around..................................................................................................................... 225 Using a Satisfied Provider........................................................................................... 229 Pieces of Me......................................................................................................................... 229 Getting a Handle................................................................................................................. 30 Makin' Queries..................................................................................................................... 231 Adapting to the Circumstances.......................................................................................... 233 Doing It By Hand................................................................................................................. 235 Position......................................................................................................................... 35 Getting Properties....................................................................................................... 236 Setting Properties........................................................................................................ 237 Produce and Take...................................................................................................................... 238 Beware of the BLOB!........................................................................................................... 239 Edifice a Satisfied Provider....................................................................................... 41 First, Some Dissection......................................................................................................... 241 Next, Some Typing.............................................................................................................. 242 Step #1: Fashion a Provider Class........................................................................ .................. 243 ContentProvider.......................................................................................................... 243 DatabaseContentProvider........................................................................................... 52 Step #2: Minister a Uri........................................................................................................... 252 Step #3: Defend the Properties.......................................................................................... 252 Step #4: Upbound the Manifest............................................................................................. 253 viii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Notify-On-Change Support................................................................................................ 54 Requesting and Requiring Permissions..................................................................... 257 Mother, May I?.................................................................................................................... 258 Halt! Who Goes There?....................................................................................................... 259 Enforcing Permissions via the Manifest.................................................................... 260 Enforcing Permissions Elsewhere............................................................................... 61 May I See Your Documents?............................................................................................... 262 Creating a Service........................................................................................................ 263 Getting Buzzed.................................................................................................................... 264 Employment after a opportunity Class................................................................................................................ 64 When IPC Attacks!.............................................................................................................. 266 Transcribe the AIDL............................................................................................................ 267 Instrument the Interface............................................................................................. 268 Notorious Destiny................................................................................................................. 270 Where's the Remote?........................................................................................................... 71 Invoking a Service....................................................................................................... 273 Bound for Success............................................................................................................... 274 Request for Service.............................................................................................................. 276 Prometheus Unbound......................................................................................................... 276 Manual Transmission.......................................................................................................... 76 Alerting Users Via Notifications................................................................................. 279 Types of Pestering............................................................................................................... 279 Hardware Notifications.............................................................................................. 280 Icons.............................................................................................................................. 281 Letting Your Presence Be Felt............................................................................................. 81 Accessing Location-Based Services............................................................................. 287 Colonization Providers: They Apprehend Where You're Hiding.................................................... 288 Finding Yourself.................................................................................................................. 288 On the Move........................................................................................................................ 292 Are We There Yet? Are We There Yet? Are We There Yet?............................................ 292 Testing... Testing.................................................................................................................. 296 Mapping after a opportunity MapView and MapActivity.................................................................. 299 The Bare Bones.................................................................................................................... 299 ix Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Exercising Your Control....................................................................................................... 01 Zoom............................................................................................................................. 301 Center........................................................................................................................... 302 Reticle........................................................................................................................... 303 Traffic and Terrain............................................................................................................... 03 Ensue You, Ensue Me........................................................................................................ 305 Layers Upon Layers............................................................................................................. 307 Overlay Classes............................................................................................................ 308 Drawing the Overlay................................................................................................... 308 Handling Screen Taps.................................................................................................. 10 Detached Media.............................................................................................................. 313 Get Your Media On.............................................................................................................. 314 Making Noise........................................................................................................................ 315 Moving Pictures.................................................................................................................... 21 Handling Telephone Calls.......................................................................................... 325 No, No, No – Not That IPhone........................................................................................... 326 What's Our Status?.............................................................................................................. 326 You Fashion the Call!.............................................................................................................. 326 Searching after a opportunity SearchManager................................................................................... 33 Hunting Season.................................................................................................................... 333 Search Yourself..................................................................................................................... 335 Craft the Search Activity............................................................................................. 336 Upbound the Manifest.................................................................................................... 340 Try It Out..................................................................................................................... 42 The TourIt Scantling Application.................................................................................. 347 Installing TourIt....................................................................... ........................................... 347 Demo Colonization Provider............................................................................................. 347 SD Card Image after a opportunity Scantling Tour.............................................................................. 348 Inferior TourIt.................................................................................................................... 49 Deep Activity................................................................................................................ 350 Configuration Activity................................................................................................. 352 Cue Sheet Activity....................................................................................................... 354 Map Activity................................................................................................................. 355 x Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Tour Upbound Activity................................................................................................... 357 Aid Activity................................................................................................................ 358 TourIt's Manifest................................................................................................................. 359 TourIt's Content.................................................................................................................. 360 Axioms Storage................................................................................................................. 61 Satisfied Provider.......................................................................................................... 361 Type Classes............................................................................................................... 361 TourIt's Activities................................................................................................................ 362 TourListActivity........................................................................................................... 362 TourViewActivity......................................................................................................... 63 TourMapActivity.......................................................................................................... 367 TourEditActivity.......................................................................................................... 367 HelpActivity................................................................................................................. 367 ConfigActivity.............................................................................................................. 368 xi Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. Permit Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Gratifying to the Warescription! We vision you possess this ecapacity and its updates – sustain tabs on the Warescription pamper off the CommonsWare locality to gather when new editions of this capacity, or other capacitys in your Warescription, are adapted. All editions of CommonsWare denominations, stereotype and ebook, ensue a softwarestyle computeing rule. Elder looses (1. 0, 2. 0, etc. ) are adapted in twain stereotype and ebook; inferior looses (0. 1, 0. 9, etc. ) are adapted in ecapacity produce for Warescription subscribers barely. Releases bound in . 9 are "loose candidates" for the present elder loose, lacking possibly an condemnation but incongruously nature accomplished. Each Warescription ecapacity is permitd for the scientific use of its subscriber and is tagged after a opportunity the subscribers allure. We ask that you not sustain-apart these capacitys. If you exertion for a resolute and covet-for to possess separate employees possess entrance, achievement Warescriptions are adapted. Cool continuity us at [email protected] com. Also, endure in soul that nevertheless this edition of this denomination obtain be loosed subordinate a Creative Commons permit – further on this in the proem. Remember that the CommonsWare Web locality has errata and media (e. g. , fountain appoint) for each of our denominations. Cool endowigate the Web page for the capacity you are zealous in and ensue the joins. Some notes for Kindle users: xiii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition • • You may covet-for to droop your font extent to smooth 2 for easier lection Fountain appoint listings are incorporated as graphics so as to cessationrain the monointerroom font, though this media the fountain appoint listings do not reverence alters in Kindle font extent xiv Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 Permit Edition Proem Gratifying to the Book! Thanks! Endowment for your share in developing impressions for Android! Increasingly, inhabitants obtain entrance Internet-domiciled employments using so-denominated "non-traditional" media, such as ductile purposes. The further we do in that interinterroom now, the further that inhabitants obtain aid endow in that interinterroom to fashion it easier to set-up further potent ductile impressions in the coming. Android is new – at the boundlessness of this adaptation, there are no shipping Android-powered purposes – but it approvely obtain rapidly dipast in significance due to the extent and eagerion of the Unreserved Handset Alliance. And, most of all, endowment for your share in this capacity! I cordially vision you dissecure it succorful and at balanceest casually juicy. Prerequisites If you are zealous in programming for Android, you obtain deficiency at balanceest basic subordinatestanding of how to program in Java. Android programming is performed using Java syntax, plus a assort library that resembles a subset of the Java SE library (plus Android-favoring extensions). If you possess not programmed in Java anteriorly, you probably should fleet gather how that exertions anteriorly attempting to precipitate into programming for Android. v Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The capacity does not cbalance in any particular how to download or induct the Android outgrowth tools, either the Eclipse IDE odor or the standalone odor. The Android Web locality secures this totally nicely. The representative in the capacity should be apt whether you use the IDE or not. You should download, induct, and experiment out the Android outgrowth tools from the Android Web locality anteriorly up-hill any of the scantlings listed in this capacity. Some paragraphs may relation representative in foregoing paragraphs, though usually after a opportunity a join end to the produceer exception of junction. Warescription This capacity obtain be published twain in stereotype and in digital (ebook) produce. The ecapacity versions of all CommonsWare denominations are adapted via an annual reinforcement – the Warescription. The Warescription entitles you, for the continuance of your reinforcement, to ecapacity produces of all CommonsWare denominations, not cool the one you are lection. Presently, CommonsWare offers PDF and Kindle; other ecapacity produceats obtain be acquired domiciled on share and the honesty of the produceat. Each subscriber gets specialalized editions of all editions of each denomination: twain those mirroring stereotypeed editions and in-between updates that are barely adapted in ecapacity produce. That way, your ebooks are never out of bound for crave, and you can obtain?} practice of new representative as it is made adapted instead of having to confide for a integral new stereotype edition. For scantling, when new looses of the Android SDK are made adapted, this capacity obtain be fleetly updated to be considerate after a opportunity alters in the APIs. From boundlessness to boundlessness, subscribers obtain as-well-mannered follow entrance to subscriber-barely online representative, twain condensed articles and not-yet-published new denominations. Also, if you own a stereotype delineation of a CommonsWare capacity, and it is in cheerful unclogged predicament after a opportunity no marks or adhereers, you can exalter that delineation for a discount off the Warescription value. If you are zealous in a Warescription, endowigate the Warescription exception of the CommonsWare Web locality. xvi Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Capacity Bug Gift Dissecure a amount in one of our capacitys? Let us apprehend! Be the primeval to repute a sole embodied amount, and we'll produce you a coupon for a six-month Warescription as a gift for aiding us concede a rectify consequence. You can use that coupon to get a new Warescription, furbish an massive Warescription, or produce the coupon to a confidant, coadjutor, or some unpremeditated special you as on the subway. By "concrete" amount, we balance subjects approve: • • Typographical gravitateacys Scantling impressions that do not exertion as advertised, in the environment descriptive in the capacity Fexpress gravitateacys that cannot be unreserved to definition • By "unique", we balance ones not yet reputeed. Each capacity has an errata page on the CommonsWare Web locality; most disclosed amounts obtain be listed there. We esteem hearkening environing "softer" issues as well-behaved-mannered, such as: • Places where you imagine we are in gravitateacy, but where we move our definition is cool Places where you imagine we could add scantling impressions, or dipast upon the massive representative Samples that do not exertion due to "shifting sands" of the subordinatelying environment (e. g. , modifiable APIs after a opportunity new looses of an SDK) • • However, those "softer" issues do not adapt for the produceal gift program. Questions environing the bug gift, or amounts you covet-for to repute for gift subsidy, should be sent to [email protected] com. xvii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Source Appoint Permit The fountain appoint scantlings demonstrationn in this capacity are adapted for download from the CommonsWare Web locality. All of the Android purposes are permitd subordinate the Apache 2. 0 License, in subject you possess the covet-for to reuse any of it. Creative Commons and the Four-to-Free (42F) Insure Each CommonsWare capacity edition obtain be adapted for use subordinate the Creative Commons Attribution-Noncommercial-Share Aapconfirm 3. 0 permit as of the foul-mouthedth anniversary of its divulgation bound, or when 4,000 copies of the edition possess been sold, whichever comes primeval. That media that, uniformly foul-mouthed years possess spent (possibly precedent! , you can use this prose for noncommercial purposes. That is our Four-to-Free Insure to our decipherers and the broader aggregation. For the purposes of this insure, new Warescriptions and furbishals obtain be counted as sales of this edition, starting from the boundlessness the edition is published. This edition of this capacity obtain be adapted subordinate the aforementioned Creative Commons permit on July 1, 2012. Of way, wake the CommonsWare Web locality, as this edition faculty be relicensed precedent domiciled on sales. For further particulars on the Creative Commons Attribution-NoncommercialShare Aapconfirm 3. 0 permit, endowigate the Creative Commons Web locality. Note that coming editions of this capacity obtain behove bountiful on forthcoming bounds, each foul-mouthed years from the divulgation of that edition or domiciled on sales of that favoring edition. Releasing one edition subordinate the Creative Commons permit does not automatically loose all editions subordinate that permit. xviii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition PART I – Core Concepts Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. Permit Edition CHAPTER 1 The Big Picture Android purposes, by and great, obtain be ductile phones. Opportunity the Android technology is nature discussed for use in other areas (e. g. , car dashboard "PCs"), for the most part, you can imagine of Android as nature used on phones. For developers, this has benefits and drawbacks. On the plus countenance, circa 2008, Android-style smartphones are sexy. Oblation Internet employments balance ductile purposes bounds end to the mid-1990's and the Handheld Purpose Markup Vernacular (HDML). However, barely in novel years possess phones worthy of Internet entrance obtain?}n off. Now, endowment to trends apconfirm citation messaging and to consequences apconfirm Apple's iPhone, phones that can forward as Internet entrance purposes are rapidly gaining relishdity. So, exertioning on Android impressions produces you habit after a opportunity an shareing technology (Android) in a fast-moving defend section (Internet-enabled phones), which is constantly a cheerful subject. The amount comes when you substantially possess to program the darn subjects. Anyone after a opportunity habit in programming for PDAs or phones has felt the abstinence of phones barely nature delicate in all sorts of body: • Screens are delicate (you won't get comments approve, "is that a 24-inch LCD in your filch, or...? ) Keyboards, if they depend, are delicate 1 • Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The Big Picture • Pointing purposes, if they depend, are tiresome (as anyone who has obsolete their stylus obtain count you) or unfair (great fingers and "multi-touch" LCDs are not a cheerful mix) CPU accelerate and remembrance are fast compared to desktops and forwardrs you may be used to You can possess any programming vernacular and outgrowth frameexertion you omission, so crave as it was what the purpose creator chose and burned into the phone's silicon And so on • • • Moreover, impressions inferior on a phone possess to market after a opportunity the smootht that they're on a phone. Inhabitants after a opportunity ductile phones conduce to get very grudging when those phones don't exertion, which is why the "can you hearkenken me now? " ad war from Verizon Wireless has been relishd for the spent few years. Similarly, those selfselfcorresponding inhabitants obtain get grudging at you if your program "breaks" their phone: • • ... by tying up the CPU such that allures can't be followd ... by not exertioning unexceptionably after a opportunity the cessation of the phone's OS, such that your impression doesn't quietly vanish to the endground when a allure comes in or deficiencys to be establishd ... y din the phone's unconditional rule, such as by leaking remembrance apconfirm a sieve • Hence, developing programs for a phone is a incongruous habit than developing desktop impressions, Web localitys, or end-end forwardr processes. You curve up after a opportunity incongruous-looking tools, incongruous-behaving frameworks, and "incongruous than you're used to" limitations on what you can do after a opportunity your program. What Android tries to do is as you halfway: • You get a arrangementatically-used programming vernacular (Java) after a opportunity some commbarely used libraries (e. g. , some Apache Commons APIs), after a opportunity influence for tools you may be used to (Eclipse) 2 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The Big Picture • You get a fairly staunch and unusual frameexertion in which your programs deficiency to run so they can be "cheerful citizens" on the phone and not clash after a opportunity other programs or the exercise of the phone itself As you faculty forecast, ample of this capacity markets after a opportunity that frameexertion and how you transcribe programs that exertion after a opportunityin its outskirts and obtain?} practice of its capabilities. What Androids Are Made Of When you transcribe a desktop impression, you are "master of your own domain". You embark your deep curveow and any branch curveows – apconfirm dialog boxes – that are deficiencyed. From your rendezvous, you are your own cosmos-people, leveraging features influenceed by the unconditional rule, but greatly uninformed of any other program that may be inferior on the computer at the selfselfcorresponding boundlessness. If you do interact after a opportunity other programs, it is inferiorly through an API, such as using JDBC (or frameworks atop it) to defend after a opportunity MySQL or another axiomsbase. Android has homogeneous concepts, but parceld incongruously, and compositiond to fashion phones further crash-resistant. Activities The set-uping stop of the user intercountenance is the energy. You can imagine of an energy as nature the Android analogue for the curveow or dialog in a desktop impression. Opportunity it is practicable for activities to not possess a user interface, most approvely your "headless" appoint obtain be parceld in the produce of satisfied procurers or employments, descriptive adown. 3 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The Big Picture Satisfied Providers Satisfied procurers procure a smooth of pocketing for any axioms stored on the purpose that is entranceible by multiple impressions. The Android outgrowth type encourages you to fashion your own axioms adapted to other impressions, as well-behaved-mannered-mannered as your own – set-uping a satisfied procurer lets you do that, opportunity deeptaining accomplished coerce balance how your axioms gets entranceed. Intents Intents are rule notices, inferior about the incountenance of the purpose, notifying impressions of manifold smoothts, from hardware specify alters (e. g. , an SD card was inserted), to incoming axioms (e. g. , an SMS notice arrived), to impression smoothts (e. g. , your energy was embarked from the purpose's deep menu). Not barely can you meet to eagers, but you can fashion your own, to embark other activities, or to let you apprehend when favoring situations appoint (e. g. , train such-and-so eager when the user gets after a opportunityin 100 meters of this-and-such colonization). Services Activities, satisfied procurers, and eager followrs are all condensed-lived and can be condelicate down at any boundlessness. Services, on the other index, are purposed to sustain inferior, if deficiencyed, refractory of any energy. You faculty use a employment for checking for updates to an RSS pamper, or to embody end still n ess smooth if the coerceling energy is no craveer unconditional. 4 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The Big Picture Stuff At Your Disposal Storage You can parcel axioms refines after a opportunity your impression, for subjects that do not alter, such as icons or aid refines. You as-well-mannered can levigate out a delicate bit of interinterroom on the purpose itself, for axiomsbases or refines containing user-entered or retrieved axioms deficiencyed by your impression. And, if the user preparation integrity storage, apconfirm an SD card, you can decipher and transcribe refines on there as deficiencyed. Netexertion Android purposes obtain generally-knownly be Internet-ready, through one communications medium or another. You can obtain?} practice of the Internet entrance at any smooth you covet-for, from raw Java sockets all the way up to a built-in WebKit-domiciled Web browser widget you can embed in your impression. Multimedia Android purposes possess the ability to embody end and chronicles audio and video. Opportunity the favorings may differ from purpose to purpose, you can interrogation the purpose to gather its capabilities and then obtain?} practice of the multimedia capabilities as you see fit, whether that is to embody end still n ess, obtain?} pictures after a opportunity the camera, or use the microphone for audio note-taking. GPS Android purposes obtain regularly possess entrance to colonization procurers, such as GPS, that can count your impressions where the purpose is on the countenance of the Earth. In decline, you can disembody maps or incongruously obtain?} practice of the colonization axioms, such as tracking a purpose's movements if the purpose has been stolen. 5 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition The Big Picture Phone Services And, of way, Android purposes are inferiorly phones, authorizeing your software to inaugurate allures, cast and follow SMS notices, and everysubject else you forecast from a existent bit of telephony technology. Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition CHAPTER 2 Purpose Composition The Android set-up rule is unconfused about a favoring directory tree composition for your Android purpose, ample apconfirm any other Java purpose. The favorings, though, are fairly sole to Android and what it all does to appoint the express impression that obtain run on the purpose or adversary. Here's a fleet primer on the purpose composition, to aid you fashion sentiment of it all, distinctly for the scantling appoint relationd in this capacity. Root Interruption When you fashion a new Android purpose (e. g. , via energyCreator. py), you get five key items in the purpose's spring directory: • AndroidManifest. xml, which is an XML redelicate describing the impression nature built and what components – activities, employments, etc. – are nature yieldd by that impression set-up. xml, • which is an Ant script for compiling the impression and inducting it on the purpose bin/, which confides the impression uniformly it is transcribed src/, which confides the Java fountain appoint for the impression res/, • • • hich confides "resources", such as icons, GUI layouts, and the approve, that get parceld after a opportunity the transcribed Java in the impression which confide other static refines you covet-for parceld after a opportunity the impression for deployment onto the purpose 7 • assets/, Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Purpose Composition The Sweat Off Your Brow When you fashiond the purpose (e. g. , via energyCreator. py), you yieldd the fully-qualified assort allure of the "main" energy for the impression (e. g. , com. commonsware. android. SomeDemo). You obtain then dissecure that your purpose's src/ tree alopportune has the allureinterroom directory tree in establish, plus a stub Energy subassort representing your deep energy (e. g. , src/com/commonsware/ android/SomeDemo. java). You are gratifying to dissimipast this redelicate and add others to the src/ tree as deficiencyed to instrument your impression. The primeval boundlessness you transcribe the purpose (e. g. , via ant), out in the "main" energy's allureinterroom directory, the Android set-up compact obtain fashion R. java. This contains a compute of constants tied to the manifold media you establishd out in the res/ directory tree. You should not dissimipast R. java yourself, letting the Android tools indexle it for you. You obtain see throughout sundry of the scantlings where we relation subjects in R. java (e. g. , relatering to a layout's identifier via R. layout. deep). And Now, The Cessation of the Story You obtain as-well-mannered dissecure that your purpose has a res/ directory tree. This confides "resources" – static refines that are parceld acrave after a opportunity your impression, either in their ancient produce or, casually, in a preprocessed produce. Some of the subdirectories you obtain dissecure or fashion subordinate res/ include: • • • res/drawable/ res/layout/ or images (PNG, JPEG, etc. ) for XML-domiciled UI layout favoringations res/raw/ for generally-known-purpose refines (e. g,. a CSV redelicate of representation notice) res/values/ • • for strings, body, and the apconfirm res/xml/ for other generally-known-purpose XML refines you covet-for to ship We obtain cbalance all of these, and further, in forthcoming paragraphs of this capacity. 8 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Purpose Composition What You Get Out Of It When you transcribe your purpose (via ant or the IDE), bin/ directory subordinate your purpose spring. Specifically: • • bin/classes/ he results go into the confides the transcribed Java assortes confides the executable fashiond from those transcribed bin/classes. dex Java assortes • bin/yourapp. apk is the express Android impression (where yourapp is the allure of your impression) The . apk redelicate is a ZIP archive containing the . dex refine, the transcribed edition of your media (resources. arsc), any un-compiled media (such as what you put in res/raw/) and the AndroidManifest. xml refine. 9 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 Permit Edition CHAPTER 3 Incountenance the Notorious The base for any Android impression is the notorious refine: AndroidManifest. xml in the spring of your purpose. Here is where you defend what all is incountenance your impression – the activities, the employments, and so on. You as-well-mannered demonstration how these fractions attract themselves to the balanceall Android rule; for scantling, you demonstration which energy (or activities) should demonstration on the purpose's deep menu (a. k. a. , embarker). When you fashion your impression, you obtain get a starter notorious generated for you. For a lowly impression, oblation a uncompounded energy and nosubject else, the auto-generated notorious obtain probably exertion out delicate, or possibly insist-upon a few inferior modifications. On the other end of the spectrum, the notorious redelicate for the Android API demo tail is balance 1,000 lines crave. Your consequenceion Android impressions obtain probably gravitate somewhere in the average. Most of the shareing bits of the notorious obtain be descriptive in elder particular in the paragraphs on their associated Android features. For scantling, the employment component obtain be descriptive in elder particular in the paragraph on creating employments. For now, we cool deficiency to subordinatestand what the role of the notorious is and its generally-known balanceall light. In The Beginning, There Was the Root, And It Was Cheerful The spring of all notorious refines is, not surprisingly, a notorious component: 11 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Incountenance the Notorious ... Note the allureinterroom assertion. Curiously, the generated notoriouss barely apportion it on the marks, not the components (e. g. , it's notorious, not android:manifest). However, that shape exertions, so consistent Android alters, adhere after a opportunity their shape. The biggest fraction of notice you deficiency to minister on the notorious component is the parcel mark (as-well-mannered curiously not-namespaced). Here, you can procure the allure of the Java parcel that obtain be considered the "base" of your impression. Then, everywhere else in the notorious redelicate that deficiencys a assort allure, you can cool replace a leading dot as condensedindex for the parcel. For scantling, if you deficiencyed to repast to com. commonsware. android. Snicklefritz in this notorious demonstrationn aloft, you could cool use . Snicklefritz, gone com. commonsware. android is defined as the impression's parcel. Permissions, Instrumentations, and Applications (Oh, My! Underneath the notorious component, you obtain discover: • components, to demonstration what libertys your impression obtain deficiency in appoint to discharge unexceptionably – see the paragraph on libertys for further particulars uses-liberty • components, to defend libertys that activities or employments faculty insist-upon other impressions confide in appoint to use your impression's axioms or logic – anew, further particulars are aftercited in the paragraph on libertys liberty • components, to demonstration appoint that should be invoked on key rule smoothts, such as starting up activities, for the purposes of logging or monitoring instrumentation • n impression component, defining the guts of the impression that the notorious recounts 12 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Incountenance the Notorious ... In the produceer scantling, the notorious has uses-liberty components to demonstration some purpose capabilities the impression obtain deficiency – in this subject, libertys to authorize the impression to particularize its general colonization. And, there is the impression component, whose satisfieds obtain recount the activities, employments, and whatnot that fashion up the integrity of the impression itself. Your Impression Does Something, Right? The developed wood of the notorious redelicate are the branchren of the impression component. By omission, when you fashion a new Android purpose, you get a uncompounded energy component: This component preparation android:allure for the assort instrumenting the energy, android:label for the disembody allure of the energy, and (frequently) an eager-filter branch component describing subordinate what predicaments this energy 13 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Incountenance the Notorious obtain be unfolded. The accumulation energy component sets up your energy to demonstration in the embarker, so users can cull to run it. As we'll see forthcoming in this capacity, you can possess separate activities in one purpose, if you so cull. You may as-well-mannered possess one or further followr components, indicating non-activities that should be triggered subordinate true predicaments, such as when an SMS notice comes in. These are allureed eager followrs and are descriptive midway through the capacity. You may possess one or further procurer components, indicating satisfied procurers – components that minister axioms to your activities and, after a opportunity your liberty, other activities in other impressions on the purpose. These clothe up axiomsbases or other axioms stores into a uncompounded API that any impression can use. Later, we'll see how to fashion satisfied procurers and how to use satisfied procurers that you or others fashion. Finally, you may possess one or further employment components, describing employments – crave-inferior fractions of appoint that can act refractory of any energy. The quintessential scantling is the MP3 embodyer, where you omission the still n ess to sustain embodying smooth if the user pops unreserved other activities and the MP3 embodyer's user intercountenance is "misplaced". Two paragraphs past in the capacity cbalance how to fashion and use employments. 14 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition PART II – Activities Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition CHAPTER 4 Creating a Skeleton Impression Every programming vernacular or environment capacity starts off after a opportunity the everliked "Hello, World! " demonstration: cool sufficient of a program to confirm you can set-up subjects, not so ample that you cannot subordinatestand what is going on. However, the inferior "Hello, World! " program has no interenergy (e. g. , cool dumps the control to a assuage), and so is developedly boring. This paragraph demonstrates a lowly purpose, but one using Advanced PushButton Technology™ and the general boundlessness, to demonstration you how a lowly Android energy exertions. Begin at the Beginning To exertion after a opportunity anysubject in Android, you deficiency a purpose. After a opportunity inferior Java, if you omissioned, you could cool transcribe a program as a uncompounded refine, transcribe it after a opportunity javac, and run it after a opportunity java, after a opportunityout any other influence compositions. Android is further intricate, but to aid sustain it tractable, Google has yieldd tools to aid fashion the purpose. If you are using an Android-enabled IDE, such as Eclipse after a opportunity the Android plugin, you can fashion a purpose incountenance of the IDE (e. . , chosen Redelicate ; New ; Project, then cull Android ; Android Project). If you are using tools that are not Android-enabled, you can use the energyCreator. py script, rest in the tools/ directory in your SDK inductation. Cool by energyCreator. py the parcel allure of the energy 17 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 Permit Edition Creating a Skeleton Impression you omission to fashion and a --out switch indicating where the purpose refines should be generated. For scantling: . /activityCreator. py --out /path/to/my/project/dir com. ommonsware. android. Now You obtain curve up after a opportunity a indexful of pre-generated refines, as descriptive in a foregoing paragraph. For the purposes of the scantlings demonstrationn in this capacity, you can download their purpose directories in a ZIP redelicate on the CommonsWare Web locality. These purposes are deciphery for use; you do not deficiency to run energyCreator. py on those unpacked scantlings. The Energy Your purpose's src/ directory contains the test Java-style tree of directories domiciled upon the Java parcel you chose when you fashiond the purpose (e. g. , com. commonsware. android results in src/com/commonsware/android/). Incountenance the innermost directory you should dissecure a pre-generated fountain redelicate allured Now. java, which where your primeval energy obtain go. Unreserved Now. java in your editor and spente in the ensueing appoint: parcel com. commonsware. android. skeleton; drift drift drift drift drift android. app. Activity; android. os. Bundle; android. light. View; android. widget. Button; java. util. Date; generally-known assort Now extends Energy instruments View. OnClickListener { Button btn; @Override generally-known destitute onCreate(Bundle icicle) { super. onCreate(icicle); btn = new Button(this); btn. setOnClickList