The Busy Coder’s Guide to Android Development

Last Updated: 27 Jul 2020
Pages: 21 Views: 427

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 Reserved. Printed in the United States of America. CommonsWare books may be purchased in printed (bulk) or digital form for educational or business use. For more information, contact direct@commonsware. com. Printing History: Jul 2008: Version 1. 0 ISBN: 978-0-9816780-0-9 The CommonsWare name and logo, “Busy Coder's Guide”, and related trade dress are trademarks of CommonsWare, LLC.

All other trademarks referenced in this book are trademarks of their respective firms. The publisher and author(s) assume no responsibility for errors or omissions or for damages resulting from the use of the information contained herein. Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Table of Contents Welcome to the Warescription!.................................................................................. xiii Preface.......................................................................................................................... v Welcome to the Book!........................................................................................................... xv Prerequisites.......................................................................................................................... xv Warescription....................................................................................................................... xvi Book Bug Bounty....................................................................... .......................................... vii Source Code License.......................................................................................................... xviii Creative Commons and the Four-to-Free (42F) Guarantee............................................ xviii The Big Picture................................................................................................................ 1 What Androids Are Made Of................................................................................................. 3 Activities........................................................................................................................... Content Providers........................................................................................................... 4 Intents.............................................................................................................................. 4 Services............................................................................................................................. 4 Stuff At Your Disposal............................................................................................................. Storage.............................................................................................................................. 5 Network............................................................................................................................ 5 Multimedia....................................................................................................................... 5 GPS................................................................................................................................... Phone Services................................................................................................................. 6 Project Structure............................................................................................................ 7 Root Contents.......................................................................................................................... 7 The Sweat Off Your Brow....................................................................................................... 8 iii Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 License Edition And Now, The Rest of the Story............................................................................................. 8 What You Get Out Of It......................................................................................................... 9 Inside the Manifest........................................................................................................ 11 In The Beginning, There Was the Root, And It Was Good................................................. 11 Permissions, Instrumentations, and Applications (Oh, My! ............................................. 12 Your Application Does Something, Right?.......................................................................... 13 Creating a Skeleton Application................................................................................... 17 Begin at the Beginning........................................................................................................... 17 The Activity............................................................................................................................ 8 Dissecting the Activity........................................................................................................... 19 Building and Running 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 With the @ Signs?.................................................................................................... 26 And We Attach These to the Java... How?........................................................................... 26 The Rest 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 Just Another Box to Check.................................................................................................... 4 Turn the Radio Up................................................................................................................. 37 It's Quite a View.................................................................................................................... 39 Useful Properties........................................................................................................... 39 Useful Methods.............................................................................................................. 39 Working with 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 License 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 Something Like That... )..................................................................... 74 Fields: Now With 35% Less Typing!...................................................................... ............... 78 Galleries, Give Or Take The Art........................................................................................... 2 Employing Fancy Widgets and Containers.................................................................. 83 Pick and Choose.................................................................................................................... 83 Time Keeps Flowing Like 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 License Edition Entertaining 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 with Threads.................................................................................................. 123 Getting Through the Handlers............................................................................................ 123 Messages....................................................................................................................... 124 Runnables..................................................................................................................... 127 Running In Place.................................................................................................................. 27 Utilities (And I Don't Mean Water Works)....................................................................... 128 And Now, The Caveats........................................................................................................ 128 Handling Activity 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 Preference For Action...................................................................................................... 138 Accessing Files............................................................................................................. 143 You And The Horse You Rode In On................................................................................. 143 Readin' 'n Writin'................................................................................................................. 47 Working with Resources.............................................................................................. 151 The Resource Lineup............................................................................................................ 151 String Theory........................................................................................................................ 152 Plain Strings.................................................................................................................. 152 String

Order custom essay The Busy Coder’s Guide to Android Development with free plagiarism report

feat icon 450+ experts on 30 subjects feat icon Starting from 3 hours delivery
Get Essay Help

Formats.............................................................................................................. 153 Styled Text..................................................................................................................... 153 Styled Formats.............................................................................................................. 154 vi Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Got the Picture?................................................................................................................... 58 XML: The Resource Way..................................................................................................... 160 Miscellaneous Values........................................................................................................... 163 Dimensions................................................................................................................... 163 Colors............................................................................................................................ 64 Arrays............................................................................................................................ 165 Different Strokes for Different Folks.................................................................................. 166 Managing and Accessing Local Databases................................................................... 171 A Quick 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 Building with Builders................................................................................................. 177 Using Cursors............................................................................................................... 179 Change 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 over Java......................................................................... ............................................ 193 Creating Intent Filters................................................................................................ 99 What's Your Intent?............................................................................................................ 200 Pieces of Intents.......................................................................................................... 200 Stock Options............................................................................................................... 201 vii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Intent Routing............................................................................................................. 02 Stating Your Intent(ions).................................................................................................... 203 Narrow Receivers................................................................................................................. 205 Launching Activities and Sub-Activities..................................................................... 207 Peers and Subs..................................................................................................................... 208 Start 'Em Up........................................................................................................................ 08 Make an Intent............................................................................................................ 209 Make the Call............................................................................................................... 209 Finding Available Actions via Introspection............................................................... 215 Pick 'Em................................................................................................................................ 216 Adaptable Adapters............................................................................................................. 20 Would You Like to See the Menu?..................................................................................... 223 Asking Around..................................................................................................................... 225 Using a Content 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 Give and Take...................................................................................................................... 238 Beware of the BLOB!........................................................................................................... 239 Building a Content Provider....................................................................................... 41 First, Some Dissection......................................................................................................... 241 Next, Some Typing.............................................................................................................. 242 Step #1: Create a Provider Class........................................................................ .................. 243 ContentProvider.......................................................................................................... 243 DatabaseContentProvider........................................................................................... 52 Step #2: Supply a Uri........................................................................................................... 252 Step #3: Declare the Properties.......................................................................................... 252 Step #4: Update the Manifest............................................................................................. 253 viii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License 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 Service with Class................................................................................................................ 64 When IPC Attacks!.............................................................................................................. 266 Write the AIDL............................................................................................................ 267 Implement the Interface............................................................................................. 268 Manifest 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 Location Providers: They Know 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 with MapView and MapActivity.................................................................. 299 The Bare Bones.................................................................................................................... 299 ix Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Exercising Your Control....................................................................................................... 01 Zoom............................................................................................................................. 301 Center........................................................................................................................... 302 Reticle........................................................................................................................... 303 Traffic and Terrain............................................................................................................... 03 Follow You, Follow Me........................................................................................................ 305 Layers Upon Layers............................................................................................................. 307 Overlay Classes............................................................................................................ 308 Drawing the Overlay................................................................................................... 308 Handling Screen Taps.................................................................................................. 10 Playing 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 Make the Call!.............................................................................................................. 326 Searching with SearchManager................................................................................... 33 Hunting Season.................................................................................................................... 333 Search Yourself..................................................................................................................... 335 Craft the Search Activity............................................................................................. 336 Update the Manifest.................................................................................................... 340 Try It Out..................................................................................................................... 42 The TourIt Sample Application.................................................................................. 347 Installing TourIt....................................................................... ........................................... 347 Demo Location Provider............................................................................................. 347 SD Card Image with Sample Tour.............................................................................. 348 Running TourIt.................................................................................................................... 49 Main 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 License Edition

Tour Update Activity................................................................................................... 357 Help Activity................................................................................................................ 358 TourIt's Manifest................................................................................................................. 359 TourIt's Content.................................................................................................................. 360 Data Storage................................................................................................................. 61 Content Provider.......................................................................................................... 361 Model 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. License Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Welcome to the Warescription! We hope you enjoy this ebook and its updates – keep tabs on the Warescription feed off the CommonsWare site to learn when new editions of this book, or other books in your Warescription, are available. All editions of CommonsWare titles, print and ebook, follow a softwarestyle numbering system. Major releases (1. 0, 2. 0, etc. ) are available in both print and ebook; minor releases (0. 1, 0. 9, etc. ) are available in ebook form for Warescription subscribers only.

Releases ending in . 9 are "release candidates" for the next major release, lacking perhaps an index but otherwise being complete. Each Warescription ebook is licensed for the exclusive use of its subscriber and is tagged with the subscribers name. We ask that you not distribute these books. If you work for a firm and wish to have several employees have access, enterprise Warescriptions are available. Just contact us at enterprise@commonsware. com. Also, bear in mind that eventually this edition of this title will be released under a Creative Commons license – more on this in the preface.

Remember that the CommonsWare Web site has errata and resources (e. g. , source code) for each of our titles. Just visit the Web page for the book you are interested in and follow the links. Some notes for Kindle users: xiii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition • • You may wish to drop your font size to level 2 for easier reading Source code listings are incorporated as graphics so as to retain the monospace font, though this means the source code listings do not honor changes in Kindle font size xiv Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 License Edition Preface Welcome to the Book! Thanks! Thanks for your interest in developing applications for Android! Increasingly, people will access Internet-based services using so-called "non-traditional" means, such as mobile devices. The more we do in that space now, the more that people will help invest in that space to make it easier to build more powerful mobile applications in the future. Android is new – at the time of this writing, there are no shipping Android-powered devices – but it likely will rapidly grow in importance due to the size and scope of the Open Handset Alliance.

And, most of all, thanks for your interest in this book! I sincerely hope you find it useful and at least occasionally entertaining. Prerequisites If you are interested in programming for Android, you will need at least basic understanding of how to program in Java. Android programming is done using Java syntax, plus a class library that resembles a subset of the Java SE library (plus Android-specific extensions). If you have not programmed in Java before, you probably should quick learn how that works before attempting to dive into programming for Android. v Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The book does not cover in any detail how to download or install the Android development tools, either the Eclipse IDE flavor or the standalone flavor. The Android Web site covers this quite nicely. The material in the book should be relevant whether you use the IDE or not. You should download, install, and test out the Android development tools from the Android Web site before trying any of the examples listed in this book.

Some chapters may reference material in previous chapters, though usually with a link back to the preceding section of relevance. Warescription This book will be published both in print and in digital (ebook) form. The ebook versions of all CommonsWare titles are available via an annual subscription – the Warescription. The Warescription entitles you, for the duration of your subscription, to ebook forms of all CommonsWare titles, not just the one you are reading. Presently, CommonsWare offers PDF and Kindle; other ebook formats will be added based on interest and the openness of the format.

Each subscriber gets personalized editions of all editions of each title: both those mirroring printed editions and in-between updates that are only available in ebook form. That way, your ebooks are never out of date for long, and you can take advantage of new material as it is made available instead of having to wait for a whole new print edition. For example, when new releases of the Android SDK are made available, this book will be quickly updated to be accurate with changes in the APIs. From time to time, subscribers will also receive access to subscriber-only online material, both short articles and not-yet-published new titles.

Also, if you own a print copy of a CommonsWare book, and it is in good clean condition with no marks or stickers, you can exchange that copy for a discount off the Warescription price. If you are interested in a Warescription, visit the Warescription section of the CommonsWare Web site. xvi Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Book Bug Bounty Find a problem in one of our books? Let us know! Be the first to report a unique concrete problem, and we'll give you a coupon for a six-month Warescription as a bounty for helping us deliver a better product.

You can use that coupon to get a new Warescription, renew an existing Warescription, or give the coupon to a friend, colleague, or some random person you meet on the subway. By "concrete" problem, we mean things like: • • Typographical errors Sample applications that do not work as advertised, in the environment described in the book Factual errors that cannot be open to interpretation • By "unique", we mean ones not yet reported. Each book has an errata page on the CommonsWare Web site; most known problems will be listed there. We appreciate hearing about "softer" issues as well, such as: •

Places where you think we are in error, but where we feel our interpretation is reasonable Places where you think we could add sample applications, or expand upon the existing material Samples that do not work due to "shifting sands" of the underlying environment (e. g. , changed APIs with new releases of an SDK) • • However, those "softer" issues do not qualify for the formal bounty program. Questions about the bug bounty, or problems you wish to report for bounty consideration, should be sent to bounty@commonsware. com. xvii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition

Source Code License The source code samples shown in this book are available for download from the CommonsWare Web site. All of the Android projects are licensed under the Apache 2. 0 License, in case you have the desire to reuse any of it. Creative Commons and the Four-to-Free (42F) Guarantee Each CommonsWare book edition will be available for use under the Creative Commons Attribution-Noncommercial-Share Alike 3. 0 license as of the fourth anniversary of its publication date, or when 4,000 copies of the edition have been sold, whichever comes first. That means that, once four years have elapsed (perhaps sooner! , you can use this prose for noncommercial purposes. That is our Four-to-Free Guarantee to our readers and the broader community. For the purposes of this guarantee, new Warescriptions and renewals will be counted as sales of this edition, starting from the time the edition is published. This edition of this book will be available under the aforementioned Creative Commons license on July 1, 2012. Of course, watch the CommonsWare Web site, as this edition might be relicensed sooner based on sales. For more details on the Creative Commons Attribution-NoncommercialShare Alike 3. 0 license, visit the Creative Commons Web site.

Note that future editions of this book will become free on later dates, each four years from the publication of that edition or based on sales of that specific edition. Releasing one edition under the Creative Commons license does not automatically release all editions under that license. xviii Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition PART I – Core Concepts Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. License Edition CHAPTER 1 The Big Picture Android devices, by and large, will be mobile phones. While the Android technology is being discussed for use in other areas (e. g. , car dashboard "PCs"), for the most part, you can think of Android as being used on phones. For developers, this has benefits and drawbacks. On the plus side, circa 2008, Android-style smartphones are sexy. Offering Internet services over mobile devices dates back to the mid-1990's and the Handheld Device Markup Language (HDML). However, only in recent years have phones capable of Internet access taken off.

Now, thanks to trends like text messaging and to products like Apple's iPhone, phones that can serve as Internet access devices are rapidly gaining popularity. So, working on Android applications gives you experience with an interesting technology (Android) in a fast-moving market segment (Internet-enabled phones), which is always a good thing. The problem comes when you actually have to program the darn things. Anyone with experience in programming for PDAs or phones has felt the pain of phones simply being small in all sorts of dimensions: • Screens are small (you won't get comments like, "is that a 24-inch LCD in your pocket, or...? ) Keyboards, if they exist, are small 1 • Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The Big Picture • Pointing devices, if they exist, are annoying (as anyone who has lost their stylus will tell you) or inexact (large fingers and "multi-touch" LCDs are not a good mix) CPU speed and memory are tight compared to desktops and servers you may be used to You can have any programming language and development framework you want, so long as it was what the device manufacturer chose and burned into the phone's silicon And so on • • •

Moreover, applications running on a phone have to deal with the fact that they're on a phone. People with mobile phones tend to get very irritated when those phones don't work, which is why the "can you hear me now? " ad campaign from Verizon Wireless has been popular for the past few years. Similarly, those same people will get irritated at you if your program "breaks" their phone: • • ... by tying up the CPU such that calls can't be received ... by not working properly with the rest of the phone's OS, such that your application doesn't quietly fade to the background when a call comes in or needs to be placed ... y crashing the phone's operating system, such as by leaking memory like a sieve • Hence, developing programs for a phone is a different experience than developing desktop applications, Web sites, or back-end server processes. You wind up with different-looking tools, different-behaving frameworks, and "different than you're used to" limitations on what you can do with your program. What Android tries to do is meet you halfway: • You get a commonly-used programming language (Java) with some commonly used libraries (e. g. , some Apache Commons APIs), with support for tools you may be used to (Eclipse) 2

Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The Big Picture • You get a fairly rigid and uncommon framework in which your programs need to run so they can be "good citizens" on the phone and not interfere with other programs or the operation of the phone itself As you might expect, much of this book deals with that framework and how you write programs that work within its confines and take advantage of its capabilities. What Androids Are Made Of When you write a desktop application, you are "master of your own domain".

You launch your main window and any child windows – like dialog boxes – that are needed. From your standpoint, you are your own world, leveraging features supported by the operating system, but largely ignorant of any other program that may be running on the computer at the same time. If you do interact with other programs, it is typically through an API, such as using JDBC (or frameworks atop it) to communicate with MySQL or another database. Android has similar concepts, but packaged differently, and structured to make phones more crash-resistant. Activities

The building block of the user interface is the activity. You can think of an activity as being the Android analogue for the window or dialog in a desktop application. While it is possible for activities to not have a user interface, most likely your "headless" code will be packaged in the form of content providers or services, described below. 3 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The Big Picture Content Providers Content providers provide a level of abstraction for any data stored on the device that is accessible by multiple applications.

The Android development model encourages you to make your own data available to other applications, as well as your own – building a content provider lets you do that, while maintaining complete control over how your data gets accessed. Intents Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e. g. , an SD card was inserted), to incoming data (e. g. , an SMS message arrived), to application events (e. g. , your activity was launched from the device's main menu).

Not only can you respond to intents, but you can create your own, to launch other activities, or to let you know when specific situations arise (e. g. , raise such-and-so intent when the user gets within 100 meters of this-and-such location). Services Activities, content providers, and intent receivers are all short-lived and can be shut down at any time. Services, on the other hand, are designed to keep running, if needed, independent of any activity. You might use a service for checking for updates to an RSS feed, or to play back music even if the controlling activity is no longer operating. 4

Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The Big Picture Stuff At Your Disposal Storage You can package data files with your application, for things that do not change, such as icons or help files. You also can carve out a small bit of space on the device itself, for databases or files containing user-entered or retrieved data needed by your application. And, if the user supplies bulk storage, like an SD card, you can read and write files on there as needed. Network Android devices will generally be Internet-ready, through one communications medium or another.

You can take advantage of the Internet access at any level you wish, from raw Java sockets all the way up to a built-in WebKit-based Web browser widget you can embed in your application. Multimedia Android devices have the ability to play back and record audio and video. While the specifics may vary from device to device, you can query the device to learn its capabilities and then take advantage of the multimedia capabilities as you see fit, whether that is to play back music, take pictures with the camera, or use the microphone for audio note-taking. GPS

Android devices will frequently have access to location providers, such as GPS, that can tell your applications where the device is on the face of the Earth. In turn, you can display maps or otherwise take advantage of the location data, such as tracking a device's movements if the device has been stolen. 5 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition The Big Picture Phone Services And, of course, Android devices are typically phones, allowing your software to initiate calls, send and receive SMS messages, and everything else you expect from a modern bit of telephony technology. Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition CHAPTER 2 Project Structure The Android build system is organized around a specific directory tree structure for your Android project, much like any other Java project. The specifics, though, are fairly unique to Android and what it all does to prepare the actual application that will run on the device or emulator. Here's a quick primer on the project structure, to help you make sense of it all, particularly for the sample code referenced in this book.

Root Contents When you create a new Android project (e. g. , via activityCreator. py), you get five key items in the project's root directory: • AndroidManifest. xml, which is an XML file describing the application being built and what components – activities, services, etc. – are being supplied by that application build. xml, • which is an Ant script for compiling the application and installing it on the device bin/, which holds the application once it is compiled src/, which holds the Java source code for the application res/, • • • hich holds "resources", such as icons, GUI layouts, and the like, that get packaged with the compiled Java in the application which hold other static files you wish packaged with the application for deployment onto the device 7 • assets/, Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Project Structure The Sweat Off Your Brow When you created the project (e. g. , via activityCreator. py), you supplied the fully-qualified class name of the "main" activity for the application (e. g. , com. commonsware. android. SomeDemo).

You will then find that your project's src/ tree already has the namespace directory tree in place, plus a stub Activity subclass representing your main activity (e. g. , src/com/commonsware/ android/SomeDemo. java). You are welcome to modify this file and add others to the src/ tree as needed to implement your application. The first time you compile the project (e. g. , via ant), out in the "main" activity's namespace directory, the Android build chain will create R. java. This contains a number of constants tied to the various resources you placed out in the res/ directory tree.

You should not modify R. java yourself, letting the Android tools handle it for you. You will see throughout many of the samples where we reference things in R. java (e. g. , referring to a layout's identifier via R. layout. main). And Now, The Rest of the Story You will also find that your project has a res/ directory tree. This holds "resources" – static files that are packaged along with your application, either in their original form or, occasionally, in a preprocessed form. Some of the subdirectories you will find or create under res/ include: • • • res/drawable/ res/layout/ or images (PNG, JPEG, etc. ) for XML-based UI layout specifications res/raw/ for general-purpose files (e. g,. a CSV file of account information) res/values/ • • for strings, dimensions, and the like res/xml/ for other general-purpose XML files you wish to ship We will cover all of these, and more, in later chapters of this book. 8 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Project Structure What You Get Out Of It When you compile your project (via ant or the IDE), bin/ directory under your project root. Specifically: • • bin/classes/ he results go into the holds the compiled Java classes holds the executable created from those compiled bin/classes. dex Java classes • bin/yourapp. apk is the actual Android application (where yourapp is the name of your application) The . apk file is a ZIP archive containing the . dex file, the compiled edition of your resources (resources. arsc), any un-compiled resources (such as what you put in res/raw/) and the AndroidManifest. xml file. 9 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Subscribe to updates at http://commonsware. om Special Creative Commons BY-NC-SA 3. 0 License Edition CHAPTER 3 Inside the Manifest The foundation for any Android application is the manifest file: AndroidManifest. xml in the root of your project. Here is where you declare what all is inside your application – the activities, the services, and so on. You also indicate how these pieces attach themselves to the overall Android system; for example, you indicate which activity (or activities) should appear on the device's main menu (a. k. a. , launcher). When you create your application, you will get a starter manifest generated for you.

For a simple application, offering a single activity and nothing else, the auto-generated manifest will probably work out fine, or perhaps require a few minor modifications. On the other end of the spectrum, the manifest file for the Android API demo suite is over 1,000 lines long. Your production Android applications will probably fall somewhere in the middle. Most of the interesting bits of the manifest will be described in greater detail in the chapters on their associated Android features. For example, the service element will be described in greater detail in the chapter on creating services.

For now, we just need to understand what the role of the manifest is and its general overall construction. In The Beginning, There Was the Root, And It Was Good The root of all manifest files is, not surprisingly, a manifest element: 11 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Inside the Manifest ... Note the namespace declaration. Curiously, the generated manifests only apply it on the attributes, not the elements (e. g. , it's manifest, not android:manifest). However, that pattern works, so unless Android changes, stick with their pattern.

The biggest piece of information you need to supply on the manifest element is the package attribute (also curiously not-namespaced). Here, you can provide the name of the Java package that will be considered the "base" of your application. Then, everywhere else in the manifest file that needs a class name, you can just substitute a leading dot as shorthand for the package. For example, if you needed to refer to com. commonsware. android. Snicklefritz in this manifest shown above, you could just use . Snicklefritz, since com. commonsware. android is defined as the application's package. Permissions, Instrumentations, and Applications (Oh, My! Underneath the manifest element, you will find: • elements, to indicate what permissions your application will need in order to function properly – see the chapter on permissions for more details uses-permission • elements, to declare permissions that activities or services might require other applications hold in order to use your application's data or logic – again, more details are forthcoming in the chapter on permissions permission • elements, to indicate code that should be invoked on key system events, such as starting up activities, for the purposes of logging or monitoring instrumentation • n application element, defining the guts of the application that the manifest describes 12 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Inside the Manifest ... In the preceding example, the manifest has uses-permission elements to indicate some device capabilities the application will need – in this case, permissions to allow the application to determine its current location. And, there is the application element, whose contents will describe the activities, services, and whatnot that make up the bulk of the application itself. Your Application Does Something, Right?

The real meat of the manifest file are the children of the application element. By default, when you create a new Android project, you get a single activity element: This element supplies android:name for the class implementing the activity, android:label for the display name of the activity, and (frequently) an intent-filter child element describing under what conditions this activity 13 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Inside the Manifest will be displayed. The stock activity element sets up your activity to appear in the launcher, so users can choose to run it.

As we'll see later in this book, you can have several activities in one project, if you so choose. You may also have one or more receiver elements, indicating non-activities that should be triggered under certain conditions, such as when an SMS message comes in. These are called intent receivers and are described midway through the book. You may have one or more provider elements, indicating content providers – components that supply data to your activities and, with your permission, other activities in other applications on the device. These wrap up databases or other data stores into a single API that any application can use.

Later, we'll see how to create content providers and how to use content providers that you or others create. Finally, you may have one or more service elements, describing services – long-running pieces of code that can operate independent of any activity. The quintessential example is the MP3 player, where you want the music to keep playing even if the user pops open other activities and the MP3 player's user interface is "misplaced". Two chapters late in the book cover how to create and use services. 14 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition

PART II – Activities Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition CHAPTER 4 Creating a Skeleton Application Every programming language or environment book starts off with the everpopular "Hello, World! " demonstration: just enough of a program to prove you can build things, not so much that you cannot understand what is going on. However, the typical "Hello, World! " program has no interactivity (e. g. , just dumps the words to a console), and so is really boring.

This chapter demonstrates a simple project, but one using Advanced PushButton Technology™ and the current time, to show you how a simple Android activity works. Begin at the Beginning To work with anything in Android, you need a project. With ordinary Java, if you wanted, you could just write a program as a single file, compile it with javac, and run it with java, without any other support structures. Android is more complex, but to help keep it manageable, Google has supplied tools to help create the project. If you are using an Android-enabled IDE, such as Eclipse with the Android plugin, you can create a project inside of the IDE (e. . , select File ; New ; Project, then choose Android ; Android Project). If you are using tools that are not Android-enabled, you can use the activityCreator. py script, found in the tools/ directory in your SDK installation. Just pass activityCreator. py the package name of the activity 17 Subscribe to updates at http://commonsware. com Special Creative Commons BY-NC-SA 3. 0 License Edition Creating a Skeleton Application you want to create and a --out switch indicating where the project files should be generated. For example: . /activityCreator. py --out /path/to/my/project/dir com. ommonsware. android. Now You will wind up with a handful of pre-generated files, as described in a previous chapter. For the purposes of the samples shown in this book, you can download their project directories in a ZIP file on the CommonsWare Web site. These projects are ready for use; you do not need to run activityCreator. py on those unpacked samples. The Activity Your project's src/ directory contains the standard Java-style tree of directories based upon the Java package you chose when you created the project (e. g. , com. commonsware. android results in src/com/commonsware/android/).

Inside the innermost directory you should find a pre-generated source file named Now. java, which where your first activity will go. Open Now. java in your editor and paste in the following code: package com. commonsware. android. skeleton; import import import import import android. app. Activity; android. os. Bundle; android. view. View; android. widget. Button; java. util. Date; public class Now extends Activity implements View. OnClickListener { Button btn; @Override public void onCreate(Bundle icicle) { super. onCreate(icicle); btn = new Button(this); btn. setOnClickList

Cite this Page

The Busy Coder’s Guide to Android Development. (2017, Dec 12). Retrieved from https://phdessay.com/the-busy-coders-guide-to-android-development/

Don't let plagiarism ruin your grade

Run a free check or have your essay done for you

plagiarism ruin image

We use cookies to give you the best experience possible. By continuing we’ll assume you’re on board with our cookie policy

Save time and let our verified experts help you.

Hire writer