Android Application Development For Dummies, 2nd Edition

www.it-ebooks.info www.it-ebooks.info Android ™ Application Development FOR DUMmIES ‰ 2ND EDITION www.it-ebooks.info www.it-ebooks.info by Michael Bur...

78 downloads 760 Views 40MB Size

www.it-ebooks.info

www.it-ebooks.info

Android



Application Development FOR

DUMmIES



2ND

www.it-ebooks.info

EDITION

www.it-ebooks.info

Android



Application Development FOR

DUMmIES



2ND

EDITION

by Michael Burton and Donn Felker

www.it-ebooks.info

AndroidTM Application Development For Dummies®, 2nd Edition Published by John Wiley & Sons, Inc. 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2012 by John Wiley & Sons, Inc., Hoboken, New Jersey Published by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 6468600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Trademarks: Wiley, the Wiley logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Android is a trademark of Google, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2012948923 ISBN: 978-1-118-38710-8 (pbk); ISBN 978-1-118-41745-4 (ebk); ISBN 978-1-118-42190-1 (ebk); ISBN 978-1-118-43327-0 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1

www.it-ebooks.info

About the Authors Michael Burton is the Lead Android Engineer at Groupon. He wrote the Groupon, Digg, TripIt, and OpenTable Android apps, among others. He’s flown a project on the Space Shuttle. He’s spoken on Android application development at conferences in London, Boston, Silicon Valley, Rio de Janeiro, and elsewhere. He’s also the author of RoboGuice, the open-source dependency injection framework used by Google, Facebook, and others. Follow Michael on Twitter (@roboguice) or check out RoboGuice at http:// roboguice.org. Donn Felker is a recognized leader in the development and consultation of state-of-the-art, cutting-edge software in the mobile and web fields. He is an independent consultant with over 10 years of professional experience in various markets that include entertainment, health, retail, insurance, financial, and real estate. He is a mobile junkie, serial entrepreneur, and creative innovator in all things mobile and web. He is the founder of Agilevent, an innovative creative development firm that has done work for small startups as well as Fortune 500 companies. He is a Microsoft ASP Insider, an MCTS for .NET Framework 2.0 and 3.5 Web Applications, and a certified ScrumMaster. He’s a national speaker on topics that include Android, .NET, and software architecture. He is the author of the TekPub.com Introduction to Android video series. He is a writer, presenter, and consultant on various topics ranging from architecture to development in general, agile practices, and patterns and practices. Follow Donn on Twitter (@donnfelker) or read his blog at http:// blog.donnfelker.com.

www.it-ebooks.info

www.it-ebooks.info

Dedication To BugDroid.

Author’s Acknowledgments Thanks to Donn Felker for writing the initial version of this book and tossing the project my way. Here’s hoping we work on many successful projects in the future! A big thank you to the extended Android open source community, including Carlos Sessa, Manfred Moser, Donn, and Jake Wharton among others, who contributed their code, expertise, and reviews of this book. Thank you to my great team at Groupon, Chris, Alex, Robyn, Eric, Aubrey, and David, who have pushed me to understand the Android platform deeper than I would have on my own. And finally, thank you to my friends and family who have supported me through the evenings I spent working on this project. The loaner puppy and the per-chapter treats were all I needed to push through those long weekends!

www.it-ebooks.info

Publisher’s Acknowledgments We’re proud of this book; please send us your comments at http://dummies.custhelp.com. For other comments, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. Some of the people who helped bring this book to market include the following: Acquisitions and Editorial

Composition Services

Project Editor: Rebecca Senninger

Project Coordinator: Patrick Redmond

Acquisitions Editor: Kyle Looper

Layout and Graphics: Jennifer Creasey, Corrie Niehaus

Copy Editor: Rebecca Whitney

Proofreader: Lisa Young Stiers

Technical Editor: Krista Dombroviak

Indexer: Sharon Stock

Editorial Manager: Leah Michael Editorial Assistant: Leslie Saxman Sr. Editorial Assistant: Cherie Case Cover Photo: © istockphoto.com/Palto Cartoons: Rich Tennant (www.the5thwave.com) Publishing and Editorial for Technology Dummies

Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Acquisitions Director Mary C. Corder, Editorial Director Publishing for Consumer Dummies Kathleen Nebenhaus, Vice President and Executive Publisher Composition Services Debbie Stailey, Director of Composition Services

www.it-ebooks.info

Contents at a Glance Introduction................................................................. 1 Part I: The Nuts and Bolts of Android............................. 7 Chapter 1: Developing Spectacular Android Applications............................................ 9 Chapter 2: Prepping Your Development Headquarters............................................... 27

Part II: Building and Publishing Your First Android Application..................................... 53 Chapter 3: Your First Android Project........................................................................... 55 Chapter 4: Designing the User Interface........................................................................ 91 Chapter 5: Coding Your Application............................................................................ 115 Chapter 6: Understanding Android Resources........................................................... 153 Chapter 7: Turning Your Application into a Home Screen Widget.......................... 161 Chapter 8: Publishing Your App to the Google Play Store........................................ 183

Part III: Creating a Feature-Rich Application............. 203 Chapter 9: Designing the Task Reminder Application............................................... 205 Chapter 10: Going a la Carte with Your Menu............................................................. 229 Chapter 11: Handling User Input................................................................................... 237 Chapter 12: Getting Persistent with Data Storage...................................................... 259 Chapter 13: Reminding the User with AlarmManager................................................ 287 Chapter 14: Updating the Android Status Bar............................................................. 301 Chapter 15: Working with Android’s Preferences Framework................................. 311

Part IV: Tablets........................................................ 325 Chapter 16: Developing for Tablets.............................................................................. 327 Chapter 17: Porting Your App to Android Tablets..................................................... 335 Chapter 18: Moving beyond Google............................................................................. 349

Part V: The Part of Tens............................................ 359 Chapter 19: Ten Free Sample Applications and SDKs................................................ 361 Chapter 20: Ten Tools to Simplify Your Development Life....................................... 365

Index....................................................................... 369

www.it-ebooks.info

www.it-ebooks.info

Table of Contents Introduction.................................................................. 1 About This Book............................................................................................... 1 Conventions Used in This Book...................................................................... 2 Foolish Assumptions........................................................................................ 2 How This Book Is Organized........................................................................... 3 Part I: The Nuts and Bolts of Android.................................................. 3 Part II: Building and Publishing Your First Android Application...... 3 Part III: Creating a Feature-Rich Application....................................... 4 Part IV: Tablets........................................................................................ 4 Part V: The Part of Tens......................................................................... 4 Icons Used in This Book.................................................................................. 4 Where to Go from Here.................................................................................... 5

Part I: The Nuts and Bolts of Android.............................. 7 Chapter 1: Developing Spectacular Android Applications . . . . . . . . . . 9 Why Develop for Android?.............................................................................. 9 Market share.......................................................................................... 10 Time to market...................................................................................... 10 Open platform....................................................................................... 10 Cross-compatibility.............................................................................. 11 Mashup capability................................................................................ 11 Android Development Basics........................................................................ 12 Java: Your Android programming language...................................... 13 Activities................................................................................................ 13 Intents.................................................................................................... 13 Cursorless controls.............................................................................. 15 Views...................................................................................................... 15 Asynchronous calls.............................................................................. 15 Background services............................................................................ 16 Honeycomb, Ice Cream Sandwich, and Jelly Bean Features..................... 17 Fragments.............................................................................................. 17 Loaders.................................................................................................. 18 Android support library....................................................................... 18 Action bar.............................................................................................. 18 Holo........................................................................................................ 20 Widgets, notifications, performance.................................................. 21 Hardware Tools.............................................................................................. 21 Touchscreen.......................................................................................... 22 GPS.......................................................................................................... 23 Accelerometer....................................................................................... 23 SD card................................................................................................... 23

www.it-ebooks.info

xii

Android Application Development For Dummies, 2nd Edition Software Tools................................................................................................ 24 Internet................................................................................................... 24 Audio and video support..................................................................... 24 Contacts................................................................................................. 25 Security.................................................................................................. 25 Google APIs............................................................................................ 25

Chapter 2: Prepping Your Development Headquarters . . . . . . . . . . . . 27 Developing the Android Developer Inside You.......................................... 27 Assembling Your Toolkit............................................................................... 28 Linux 2.6 kernel..................................................................................... 28 Android framework.............................................................................. 29 Application framework......................................................................... 30 Open Handset Alliance libraries......................................................... 31 Java knowledge..................................................................................... 32 Tuning Up Your Hardware............................................................................ 33 Operating system.................................................................................. 33 Computer hardware............................................................................. 34 Installing and Configuring Your Support Tools.......................................... 34 Getting the Java Development Kit................................................................ 35 Acquiring the Android SDK........................................................................... 36 Downloading the Android SDK............................................................ 36 Following and setting your tools path............................................... 38 Getting the Total Eclipse............................................................................... 40 Installing Eclipse................................................................................... 40 Configuring Eclipse............................................................................... 43 Navigating the Android SDK.......................................................................... 46 Targeting Android Platforms........................................................................ 47 Using SDK Tools for Everyday Development.............................................. 48 Saying hello to the emulator............................................................... 48 Getting physical with a real Android device..................................... 49 Debugging your work........................................................................... 51 Trying out the API and SDK samples.................................................. 51 Giving the API demos a spin................................................................ 51

Part II: Building and Publishing Your First Android Application............................................. 53 Chapter 3: Your First Android Project . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Starting a New Project in Eclipse.................................................................. 55 Deconstructing Your Project........................................................................ 60 Responding to error messages........................................................... 60 Understanding the Build Target and Min SDK Version settings..... 62 Setting Up an Emulator.................................................................................. 63 Creating Launch Configurations................................................................... 66

www.it-ebooks.info

Table of Contents Running the Hello Android App.................................................................... 70 Running the app in the emulator........................................................ 70 Checking deployment status............................................................... 76 Understanding Project Structure................................................................. 77 Navigating the app’s folders................................................................ 77 Viewing the application’s manifest file.............................................. 86 Viewing the project.properties file..................................................... 88 Closing Your Project...................................................................................... 89

Chapter 4: Designing the User Interface . . . . . . . . . . . . . . . . . . . . . . . . . 91 Creating the Silent Mode Toggle Application............................................. 92 Laying Out the Application........................................................................... 93 Using the XML layout file..................................................................... 94 Using the Android SDK layout tools................................................... 96 Using the visual designer..................................................................... 97 Developing the User Interface..................................................................... 100 Viewing XML layout attributes.......................................................... 101 Working with views............................................................................ 101 Adding an Image to Your Application........................................................ 102 Placing an image onscreen................................................................ 102 Adding the image to the layout......................................................... 105 Creating a Launcher Icon for the Application........................................... 107 Designing a custom launcher icon.................................................... 108 Adding a custom launcher icon........................................................ 109 Adding a Toggle Button View...................................................................... 109 Previewing the Application in the Visual Designer.................................. 111

Chapter 5: Coding Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Understanding Activities............................................................................. 115 Working with methods, stacks, and states...................................... 116 Tracking an activity’s life cycle......................................................... 117 Creating Your First Activity........................................................................ 120 Starting with onCreate....................................................................... 120 Telling Android to display the user interface................................. 121 Handling user input............................................................................ 121 Writing your first event handler....................................................... 122 Working with the Android Framework Classes........................................ 125 Getting good service........................................................................... 126 Toggling Silent mode with AudioManager....................................... 127 Installing Your Application.......................................................................... 131 Running your app in an emulator..................................................... 131 Installing on a physical Android device........................................... 133 Uh-Oh! (Responding to Errors)................................................................... 136 Using the Dalvik Debug Monitor Server........................................... 136 Using the Eclipse debugger............................................................... 141 Thinking Beyond the Application Boundaries.......................................... 149 Interacting with your application..................................................... 150 Testing whether your application works......................................... 151

www.it-ebooks.info

xiii

xiv

Android Application Development For Dummies, 2nd Edition Chapter 6: Understanding Android Resources . . . . . . . . . . . . . . . . . . . 153 Understanding Resources........................................................................... 153 Dimensions.......................................................................................... 154 Styles.................................................................................................... 155 Themes................................................................................................. 155 Values................................................................................................... 155 Menus................................................................................................... 156 Colors................................................................................................... 156 Working with Resources.............................................................................. 156 Moving strings into resources.......................................................... 156 Wrestling the image beast................................................................. 158 Making your apps global with resources......................................... 159

Chapter 7: Turning Your Application into a Home Screen Widget . . . 161 Working with App Widgets in Android...................................................... 162 Working with remote views............................................................... 163 Using AppWidgetProviders............................................................... 164 Working with Pending Intents..................................................................... 165 Understanding the Android intent system...................................... 165 Understanding intent data................................................................. 166 Evaluating intents............................................................................... 168 Using pending intents......................................................................... 168 Creating the Home Screen Widget.............................................................. 170 Implementing the AppWidgetProvider............................................ 170 Communicating with the app widget............................................... 171 Building the app widget’s layout...................................................... 173 Doing work inside an AppWidgetProvider...................................... 174 Working with the app widget’s metadata........................................ 178 Registering your new components with the manifest................... 180 Placing Your Widget on the Home Screen................................................. 181

Chapter 8: Publishing Your App to the Google Play Store . . . . . . . . . 183 Creating a Distributable File........................................................................ 184 Revisiting the manifest file................................................................ 184 Choosing your tools........................................................................... 185 Digitally signing your application..................................................... 185 Creating the APK file........................................................................... 187 Creating a Google Play Developer Profile.................................................. 190 Pricing Your Application............................................................................. 193 Choosing the paid model................................................................... 194 Choosing the free model.................................................................... 194 Getting Screen Shots for Your Application............................................... 195 Uploading Your Application to the Google Play Store............................. 196 Watching the Number of Installs Soar....................................................... 200

www.it-ebooks.info

Table of Contents

Part III: Creating a Feature-Rich Application.............. 203 Chapter 9: Designing the Task Reminder Application . . . . . . . . . . . . 205 Reviewing the Basic Requirements............................................................ 205 Scheduling a reminder script (That’s alarming!)............................ 206 Storing data......................................................................................... 206 Distracting the user (nicely)............................................................. 206 Creating the Application’s Screens............................................................ 207 Starting the new project.................................................................... 208 Creating the ReminderListActivity................................................... 209 Creating the ReminderListFragment................................................ 210 Using an activity to create and edit reminders............................... 212 Adding a fragment to the activity..................................................... 215 Creating the adding/editing fragment layout.................................. 217 Completing Your List Fragment.................................................................. 220 Getting stubby with fake data........................................................... 221 Handling user click events................................................................. 223 Identifying Your Intent................................................................................. 225 Starting new activities with intents.................................................. 225 Creating a chooser.............................................................................. 226

Chapter 10: Going a la Carte with Your Menu . . . . . . . . . . . . . . . . . . . 229 Understanding Options and Context Menus............................................. 230 Creating Your First Menu............................................................................ 231 Defining the XML file.......................................................................... 231 Handling user actions......................................................................... 233 Creating a reminder task................................................................... 233 Creating a Context Menu............................................................................. 234 Creating the menu XML file............................................................... 234 Loading the menu............................................................................... 235 Handling user selections.................................................................... 235

Chapter 11: Handling User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Creating the User Input Interface............................................................... 237 Creating an EditText view.................................................................. 237 Displaying an onscreen keyboard.................................................... 239 Getting Choosy with Dates and Times....................................................... 240 Creating picker buttons..................................................................... 240 Creating the date picker.................................................................... 241 Creating the time picker.................................................................... 245 Creating an Alert Dialog Box....................................................................... 250 Seeing why you should work with dialog boxes............................. 251 Choosing the appropriate dialog box for a task............................. 252 Creating your own alert dialog box.................................................. 253

www.it-ebooks.info

xv

xvi

Android Application Development For Dummies, 2nd Edition Validating Input............................................................................................ 255 Toasting the user................................................................................ 256 Using other validation techniques................................................... 257

Chapter 12: Getting Persistent with Data Storage . . . . . . . . . . . . . . . 259 Finding Places to Put Data........................................................................... 259 Viewing your storage options........................................................... 260 Choosing a storage option................................................................. 261 Creating Your Application’s SQLite ContentProvider............................. 262 Understanding how the SQLite ContentProvider works............... 262 Creating a ContentProvider to hold the database code................ 262 Defining the key elements of a database......................................... 263 Visualizing the SQL table................................................................... 264 Creating the database table............................................................... 265 Resolving ContentProvider URLs............................................................... 267 Creating and Editing Tasks with SQLite.................................................... 270 Inserting a task entry.......................................................................... 270 Loaders................................................................................................ 280 Returning all the tasks with a cursor............................................... 281 Understanding the SimpleCursorAdapter....................................... 285 Deleting a task..................................................................................... 285

Chapter 13: Reminding the User with AlarmManager . . . . . . . . . . . . 287 Seeing Why You Need AlarmManager....................................................... 287 Asking the User for Permission.................................................................. 288 Seeing how permissions affect the user experience...................... 288 Setting requested permissions in the AndroidManifest.xml file..... 289 Waking Up a Process with AlarmManager................................................ 290 Creating the ReminderManager class.............................................. 291 Creating the OnAlarmReceiver class................................................ 292 Creating the WakeReminderIntentService class............................. 294 Creating the ReminderService class................................................. 296 Rebooting Devices........................................................................................ 297 Creating a boot receiver.................................................................... 297 Checking the boot receiver............................................................... 300

Chapter 14: Updating the Android Status Bar . . . . . . . . . . . . . . . . . . . 301 Deconstructing the Status Bar.................................................................... 301 Using the Notification Manager.................................................................. 305 Creating a notification........................................................................ 305 Viewing the workflow......................................................................... 308 Adding string resources..................................................................... 308 Updating a Notification................................................................................ 309 Clearing a Notification................................................................................. 309

www.it-ebooks.info

Table of Contents Chapter 15: Working with Android’s Preferences Framework . . . . . 311 Understanding the Android Preferences Framework.............................. 312 Understanding the PreferenceActivity Class............................................ 313 Persisting preference values............................................................. 314 Laying out preferences...................................................................... 314 Creating Your Preferences Screen............................................................. 315 Building the preferences file............................................................. 316 Adding string resources..................................................................... 317 Working with the PreferenceActivity Class............................................... 318 Opening the PreferenceActivity class.............................................. 320 Handling menu selections.................................................................. 320 Working with Preferences in Your Activities at Runtime........................ 321 Retrieving preference values............................................................. 321 Setting preference values.................................................................. 323

Part IV: Tablets......................................................... 325 Chapter 16: Developing for Tablets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 Considering the Difference Between Phones and Tablets...................... 327 Tweaking the Task Reminder App for Tablets......................................... 328 Anticipating screen size with a flowing layout................................ 328 Adding more fragments..................................................................... 330 Creating different layouts for different devices.............................. 331 Using the action bar........................................................................... 332 Using the Support Library and ActionBarSherlock........................ 334

Chapter 17: Porting Your App to Android Tablets . . . . . . . . . . . . . . . . 335 Configuring a Tablet Emulator.................................................................... 335 Updating the AndroidManifest File............................................................ 337 Programming Activities for Tablets........................................................... 337 Creating the ReminderListAndEditorActivity................................. 337 Choosing the right activity................................................................ 338 Creating the activity layout............................................................... 340 Working with Fragments on Tablet Applications..................................... 341 Communicating between fragments................................................. 342 Adding fragment transactions........................................................... 347

Chapter 18: Moving beyond Google . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 Working Around Google Features.............................................................. 349 Setting Up Your Kindle Fire or Emulator................................................... 350 Creating Kindle-like emulator............................................................ 351 Configuring ADB (Mac)...................................................................... 354 Configuring ADB (Windows).............................................................. 354 Publishing to Amazon Appstore for Android............................................ 355

www.it-ebooks.info

xvii

xviii

Android Application Development For Dummies, 2nd Edition

Part V: The Part of Tens............................................. 359 Chapter 19: Ten Free Sample Applications and SDKs . . . . . . . . . . . . 361 The Google I/O 2012 App............................................................................. 361 LOLcat Builder.............................................................................................. 362 Amazed.......................................................................................................... 362 API Demos..................................................................................................... 362 HoneycombGallery....................................................................................... 363 K-9 Mail.......................................................................................................... 363 Agit................................................................................................................. 363 Facebook SDK for Android.......................................................................... 363 Replica Island................................................................................................ 364 Notepad Tutorial.......................................................................................... 364

Chapter 20: Ten Tools to Simplify Your Development Life . . . . . . . . 365 droid-fu and ignition..................................................................................... 365 RoboGuice..................................................................................................... 365 Translator Toolkit........................................................................................ 366 Draw 9-patch................................................................................................. 366 Hierarchy Viewer.......................................................................................... 366 UI/Application Exerciser Monkey............................................................... 367 zipalign........................................................................................................... 367 layoutopt....................................................................................................... 367 Git................................................................................................................... 368 Paint.NET and GIMP..................................................................................... 368

Index........................................................................ 369

www.it-ebooks.info

Introduction

W

elcome to Android Application Development For Dummies!

When Android was acquired by Google in 2005 (yes, Android was a start-up company at one point), a lot of people didn’t have much interest in it because Google hadn’t yet entered the mobile space. Fast-forward to a few years later, when Google announced its first Android phone: the G1. It was the start of something huge. The G1 was the first publicly released Android device. It didn’t match the rich feature set of the iPhone at the time, but a lot of people believed in the platform. As soon as Donut (Android 1.6) was released, it was evident that Google was putting some effort into the product. Immediately after version 1.6 was released, talk of 2.0 was already on the horizon. Today, we’re on version 4.1 of the Android platform, with no signs that things are slowing down. Without doubt, this is an exciting time in Android development.

About This Book Android Application Development For Dummies is a beginner’s guide to developing Android applications. You don’t need any Android application development experience under your belt to get started. You can approach this material as a blank slate because the Android platform accomplishes various mechanisms by using different paradigms that most programmers aren’t used to using — or developing with — on a day-to-day basis. The Android platform is a device-independent platform, which means that you can develop applications for various devices. These devices include, but aren’t limited to phones, e-book readers, netbooks, televisions, and GPS devices. Finding out how to develop for the Android platform opens a large variety of development options for you. This book distills hundreds, if not thousands, of pages of Android documentation, tips, tricks, and tutorials into a short, digestible format that allows you to springboard into your future as an

www.it-ebooks.info

2

Android Application Development For Dummies, 2nd Edition Android developer. This book isn’t a recipe book, but it gives you the basic knowledge to assemble various pieces of the Android framework to create interactive and compelling applications.

Conventions Used in This Book Throughout the book, you use the Android framework classes, and you will be creating Java classes and XML files. Code examples in this book appear in a monospace font so that they stand out from other text in the book. This means that the code you’ll see looks like this: public class MainActivity Java is a high-level programming language that is case-sensitive, so be sure to enter the text into the editor exactly as you see it in the book as it follows standard Java conventions. Therefore, you can transition easily between the book examples and the example code provided by the Android Software Development Kit (SDK). All class names, for example, appear in PascalCase format, and all class-scoped variables start with m. All the URLs in the book appear in monospace font as well: http://d.android.com

Foolish Assumptions To begin programming with Android, you need a computer that runs one of the following operating systems: ✓ Windows XP (32 bit), Vista (32 or 64 bit), or Windows 7 or 8 (32 or 64 bit) ✓ Mac OS X (Intel) 10.5.8 or later (x86 only) ✓ Linux (i386)

www.it-ebooks.info

Introduction You also need to download the Android SDK (which is free) and the Java Development Kit (or JDK, which is also free), if you don’t already have them on your computer. Chapter 2 outlines the entire installation process for all the tools and frameworks. Because Android applications are developed in the Java programming language, you need to understand the Java language. Android also uses XML quite heavily to define various resources inside the application, so you should understand XML too. You don’t have to be an expert in these languages, however. You don’t need a physical Android device, because all the applications you build in this book work on an emulator.

How This Book Is Organized Android Application Development For Dummies has five parts, described in the following sections.

Part I: The Nuts and Bolts of Android Part I introduces the tools and frameworks that you use to develop Android applications. It also introduces the various SDK components and shows you how they’re used in the Android ecosystem.

Part II: Building and Publishing Your First Android Application Part II introduces you to building your first Android application: the Silent Mode Toggle application. After you build the initial application, you create an app widget for the application that you can place on the Home screen of an Android device. Then you publish your application to the Google Play Store.

www.it-ebooks.info

3

4

Android Application Development For Dummies, 2nd Edition

Part III: Creating a Feature-Rich Application Part III takes your development skills up a notch by walking you through the construction of the Task Reminder application, which allows users to create various tasks with reminders. You implement an SQLite content provider in this multiscreen application. You also see how to use the Android status bar to create notifications that can help increase the usability of your application.

Part IV: Tablets Part IV takes the phone app you built in Part III and tweaks it to work on an Android tablet. You also find out how to bring your applications to nonGoogle Android devices such as the Amazon Kindle Fire.

Part V: The Part of Tens Part V gives you a tour of sample applications that prove to be stellar launching pads for your Android apps, and useful Android libraries that can make your Android development career a lot easier.

Icons Used in This Book

This icon indicates a useful pointer that you shouldn’t skip.

This icon represents a friendly reminder about a vital point you should keep in mind while proceeding through a particular section of the chapter. This icon signifies that the accompanying explanation may be informative but isn’t essential to understanding Android application development. Feel free to skip these snippets, if you like.

This icon alerts you to potential problems that you may encounter along the way. Read and remember these tidbits to avoid possible trouble.

www.it-ebooks.info

Introduction

Where to Go from Here It’s time to explore the Android platform! If you’re a bit nervous, let me assure you that you don’t have to worry; you should be nervous only because you’re excited. This book includes some extras online: ✓ Find the cheat sheet for this book at www.dummies.com/cheatsheet/ androidapplicationdevelopment. ✓ Don’t want to type all the code in the book? You can download it from the book’s website at www.dummies.com/go/androidappdevfd2e. ✓ If there are ever updates to this book, you can find them at www. dummies.com/go/androidappdevfdupdates2e.

www.it-ebooks.info

5

6

Android Application Development For Dummies, 2nd Edition

www.it-ebooks.info

Part I

The Nuts and Bolts of Android

www.it-ebooks.info

P

In this part . . .

art I introduces you to the Android platform and describes what makes a spectacular Android application. You explore various parts of the Android software development kit (SDK) and explain how you can use them in your applications. You install the tools and frameworks necessary to develop Android applications.

www.it-ebooks.info

Chapter 1

Developing Spectacular Android Applications In This Chapter ▶ Seeing reasons to develop Android apps ▶ Starting with the basics of Android development ▶ Working with the hardware ▶ Getting familiar with the software

G

oogle rocks! Google acquired the Android project in 2005 (see the sidebar “The roots of Android,” later in this chapter) to ensure that a mobile operating system (OS) can be created and maintained in an open platform. Google continues to pump time and resources into the Android project, which has already proved to be beneficial. Though devices have been available only since October 2008, as of today about a million Android devices are activated daily. In only a few years, Android has already made a huge impact. It has never been easier for Android developers to make money developing apps. Android users trust Google. Because your app resides in the Google Play Store — which Google controls — many Android users assume that your application is trustworthy, too.

Why Develop for Android? The real question is, “Why not develop for Android?” If you want your app to be available to millions of users worldwide or you want to publish apps as soon as you finish writing and testing them or you like developing on an open platform, you have your answer. But in case you’re still undecided, continue reading.

www.it-ebooks.info

10

Part I: The Nuts and Bolts of Android

Market share As a developer, you have an opportunity to develop apps for a fairly new — and booming — market. Many analysts believe that the number of Android devices in use is greater than the number of devices on all other mobile operating systems combined. The Google Play Store puts your app directly and easily into a user’s hands (or, more accurately, device). Users don’t have to search the Internet to find an app to install — they can simply go to the preinstalled Google Play Store on their devices and have access to all your apps. Because the Google Play Store comes preinstalled on most Android devices (see Chapter 19 for some exceptions), users typically search the Google Play Store for all their application needs. It isn’t unusual to see an app’s number of downloads soar in only a few days.

Time to market Because of all the application programming interfaces (APIs) packed into Android, you can easily develop full-featured applications in a relatively short time frame. After you register as a developer at the Google Play Store, simply upload your apps and publish them. Unlike other mobile marketplaces, the Google Play Store has no app approval process. All you have to do is write apps and publish them.

Though anyone can publish any type of app (technically speaking), maintain your good karma — and your compliance with the Google terms of service — by producing family-friendly apps. Android has users from diverse areas of the world and in all age categories.

Open platform The Android operating system is an open platform: Any hardware manufacturer or provider can make or sell Android devices. As you can imagine, the openness of Android has allowed it to gain market share quickly. Feel free to dig into the Android source code — at http://source.android.com — to see how certain tasks are handled, for example. By using open source code, manufacturers can even create custom user interfaces (UIs) and add built-in features to certain devices.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications

The roots of Android Though most people aren’t aware of it, Google didn’t start the Android project. The initial version of the Android operating system was created by Android, Inc., a small start-up company in Silicon Valley that was purchased by Google in July 2005. The founders (who worked for various Internet

technology companies, such as Danger, Wildfire Communications, T-Mobile, and WebTV) became part of the Google team that helped create what is now the full-fledged Android mobile operating system.

Cross-compatibility Android is cross-compatible: It can run on devices of many different screen sizes and resolutions, including phones and tablets. In addition, Android comes supplied with tools to help you develop cross-compatible applications. Google allows apps to run only on Android-compatible devices, however. If your app requires a front-facing camera, for example, only phones with front-facing cameras can “see” your app in the Google Play Store — an arrangement known as feature detection. (For more information on publishing your apps to the Google Play Store, see Chapter 8.)

Mashup capability A mashup combines two or more services to create an application. You can create a mashup by using the camera and the Android location services, for example, to take a photo with the exact location displayed on the image. Or you can use a map’s API with the Contacts list, for example, to show all contacts on a map. You can easily make apps by combining services or libraries in countless new and exciting ways. A few other types of mashups that can help your brain juices start pumping out ideas ✓ Geolocation and social networking: Suppose that you want to write an app that tweets a user’s current location every ten minutes throughout the day. Using the Android location services and a third-party Twitter API (such as iTwitter), you can do it easily.

www.it-ebooks.info

11

12

Part I: The Nuts and Bolts of Android ✓ Geolocation and gaming: Location-based gaming, which is increasingly popular, is a helpful way to inject players into the thick of a game. A game might run a background service to check a player’s current location and compare it with other players’ locations in the same area. If a second player is within a specified distance, the first one could be notified to challenge her to a battle. All this is possible because of GPS technology on a strong platform such as Android. ✓ Contacts and Internet: With all the useful APIs at your disposal, you can easily make full-featured apps by combining the functionality of two or more APIs. You can combine the Internet and names from the Contacts list to create a greeting-card app, for example. Or you may simply want to add an easy way for users to contact you from an app or enable them to send your app to their friends. (See “Google APIs,” later in this chapter, for more information on the APIs.) Developers can make Android do almost anything they want, so use your best judgment when creating and publishing apps for mass consumption. Just because you want live wallpaper to highlight your version of the hula in your birthday suit doesn’t mean that anyone else wants to see it.

Android Development Basics Thank goodness you don’t have to be a member of Mensa to develop Android applications! Developing in Android is simple because its default language is Java. Though writing Android applications is fairly easy, developing alone can be a difficult task to conquer.

If you’ve never developed applications before, this book isn’t the best place to start reading about app development. Pick up a copy of Beginning Programming with Java For Dummies, by Barry Burd (John Wiley & Sons, Inc.) to learn the ropes. After you have a basic understanding of Java under your belt, you should be ready to tackle this book. Although the Android operating system consists primarily of Java code, small parts of the framework aren’t included. Android uses the XML language as well as basic Apache Ant scripting for build processes. You need to cement your basic understanding of XML before delving into this book.



If you need an introduction to XML, check out XML For Dummies, by Lucinda Dykes and Ed Tittel (John Wiley & Sons, Inc.). If you already know how to use Java and XML, congratulations — you’re ahead of the curve.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications

Java: Your Android programming language Android applications are written in Java — not the full-blown version of Java that’s familiar to developers using Java Platform, Enterprise Edition (J2EE), but a subset of the Java libraries that are specific to Android. This smaller subset of Java excludes classes that aren’t suitable for mobile devices. If you have experience in Java, you should feel right at home developing apps in Android. Even with a Java reference book on hand, you can always search at www. google.com to find information about topics you don’t understand. Because Java isn’t a new language, you can find plenty of examples on the web that demonstrate how to do virtually anything. Not every class that’s available to Java programmers is available also on Android. Verify that it’s available to you before you start trying to use it. If it’s not, an alternative is probably bundled with Android that can work for your needs.

Activities An Android application can consist of only a single activity or several. An activity serves as a container for both the user interface and the code that runs it. You can think of activities as pages of your app — one page in your app corresponds to one activity. Activities are discussed in more detail in Chapters 3 and 5.

Intents Intents make up the core message system that runs Android. An intent is composed of two elements: ✓ An action: The general action to be performed (such as view, edit, or dial) when the intent is received ✓ Data: The information that the action operates on, such as the name of a contact Intents are used to start activities and to communicate among various parts of the Android operating system. An application can either broadcast an intent or receive an intent.

www.it-ebooks.info

13

14

Part I: The Nuts and Bolts of Android Sending messages with intents When you broadcast an intent, you send a message telling Android to make something happen. The intent can tell Android to start a new activity from within your application or to start another application.

Registering intent receivers Sending an intent doesn’t make something happen automatically. You have to register an intent receiver that listens for the intent and then tells Android what to do — whether the task is starting a new activity or another app. If more than one receiver can accept a given intent, a chooser can be created to allow the user to choose which app to use to complete the activity — such as how the YouTube app allows the user to choose whether to watch videos in the YouTube app or in a browser. Various registered receivers, such as the Gmail and the Messaging apps, handle image-sharing intents by default. When you find more than one possible intent receiver, a chooser opens with a list of options to choose from and asks what to do: Use e-mail, messaging, or another application, as shown in Figure 1-1.



Figure 1-1: A chooser.



Follow best practice and create choosers for intents that don’t target other activities within your application. If the Android system cannot find a match for an intent that was sent, and if a chooser wasn’t created manually, the application crashes after experiencing a run-time exception — an unhandled error in the application. (Android expects developers to know what they’re doing.)

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications

Cursorless controls Unlike the PC, where you manipulate the mouse to move the cursor, an Android device lets you use your fingers to do nearly anything you can do with a mouse. Rather than right-click in Android, however, you long-press an element until its context menu appears. As a developer, you can create and manipulate context menus. You can allow users to use two fingers on an Android device, rather than a single mouse cursor, for example. Fingers come in all sizes, so design the user interface in your apps accordingly. Buttons should be large enough (and have sufficient spacing) so that even users with larger fingers can interact with your apps easily, whether they’re using your app on a phone or tablet.

Views A view, which is a basic element of the Android user interface, is a rectangular area of the screen that’s responsible for drawing and event handling. Views are a basic building block of Android user interfaces, much like paragraph

or anchor tags are building blocks of an HTML page. Some common views you might use in an Android application might be a TextView, ImageView, Layout, and Button, but there are dozens more out there for you to explore. Many more views are ready for you to use. For complete details about views, check out the android.widget and android.view packages in the Android documentation at http://developer.android.com/reference/ android/widget/package-summary.html.

Asynchronous calls You use the AsyncTask class in Android to run multiple operations at the same time without having to manage a separate thread yourself. The AsyncTask class not only lets you start a new process without having to clean up after yourself but also returns the result to the activity that started it — creating a clean programming model for asynchronous processing. In general, we use loaders in this book rather than AsyncTasks, but it’s useful to know about AsyncTasks for those occasional cases where a loader won’t do what you want. A thread is a process that runs separately from, but simultaneously with, everything else that’s happening.

www.it-ebooks.info

15

16

Part I: The Nuts and Bolts of Android You use asynchronous processing for tasks that might take more than a small fraction of a second, such as network (Internet) communication; reading from, or writing to, storage; or media processing. When users have to wait for your task to complete, use an asynchronous call and an element in the user interface to notify them that something is happening. Failing to use an asynchronous programming model can cause users of your application to believe that it’s buggy. Downloading the latest Twitter messages via the Internet takes time, for example. If the network slows and you aren’t using an asynchronous model, the application will lock up and the user will likely assume that something is wrong because the application isn’t responding to her interaction. If the application fails to respond within a reasonable length of time (defined by the Android operating system), the user sees the Application Not Responding (ANR) dialog box, as shown in Figure 1-2. The user can then choose whether to close the application or wait for it to recover.



Figure 1-2: The ANR dialog box.





To follow the best practice, run CPU-intensive or long-running code inside another thread, as described in the Designing for Responsiveness page on the Android developer site (http://developer.android.com/guide/ practices/design/responsiveness.html).

Background services If you’re a Windows user, you may already know what a service is: an application that runs in the background and doesn’t necessarily have a user interface. A classic example is an antivirus application that usually runs in the background as a service. Even though you don’t see it, you know that it’s running. Most music players that can be downloaded from the Google Play Store, for example, run as background services. Users can then listen to music while checking e-mail or performing other tasks that require the use of the screen.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications

Honeycomb, Ice Cream Sandwich, and Jelly Bean Features Android 3.0, nicknamed Honeycomb, introduced the world to the Android tablet. Honeycomb and its subsequent 3.1 and 3.2 releases brought about a number of changes to support this new device class. Android 4.0 Ice Cream Sandwich and 4.1 Jelly Bean refined the ideas introduced in Honeycomb for tablets and brought them to phones, allowing developers to use the same code to support both phones and tablets in a single code base. The following sections introduce you to some of the features in these three versions (that will be covered throughout this book).

Fragments Every “page” in an Android application is a separate activity. In older versions of Android, you would place any element that you wanted to display onscreen directly into the activity class. This arrangement worked well when viewed on a phone’s small screen, on which you typically can’t see a lot of information at once. You may be able to see a list of tasks, or a task that you’re editing, but cramming both elements onto the screen at the same time is impossible. On a tablet, however, you’re swimming in real estate. Not only does it make sense to let users see a list of tasks and edit them on the same page, but it also looks silly not to let them do so. The screen size on a table is simply too big to fill with a single long list of items or lots of empty space. Android doesn’t allow you to easily put two activities on the screen at the same time. What to do? The answer is the fragment. Using fragments, a single list fragment can occupy half the screen, and an edit fragment can occupy the other half. You can find out how to use fragments in your phone application in Chapter 9 and how to scale your app to tablets in Chapter 17.

You can think of fragments as miniature activities: Because every fragment has its own lifecycle, you know when it’s being created and destroyed, among other information. Fragments go inside activities.

www.it-ebooks.info

17

18

Part I: The Nuts and Bolts of Android

Loaders A fragment is often used to display data to the user. For example, you might list some tasks by loading the list from the database. However, it’s important to never perform I/O operations on the main user interface thread. If you perform a database operation in the main user interface thread, the user may see the (dreaded) Application Not Responsive dialog box, which is intrusive and confusing and often looks like a crash to many users. A loader provides an easy way to load data on a background thread so that you don’t delay the user interface (UI) thread and hang your app. You can find out more about loaders in Chapter 10.

Android support library Fragments and loaders are effective ways to add usefulness to Android 3.x and 4.x applications. However, you may need to support older devices that use Android 1.x and 2.x, which don’t support these new features. Luckily, Android provides a solution. You can use the Android support library to make fragments and loaders compatible with devices all the way back to the Android Stone Age (circa 2009 A.D.). In addition to supplying fragments and loaders, the support library adds several other excellent features to old devices, such as: ✓ ViewPager: Swipes pages left and right ✓ GridLayout: A new way to lay out views ✓ ShareCompat: For sharing activities with your friends Visit http://developer.android.com/tools/extras/supportlibrary.html to see the complete list of features in the Android support library.

Action bar The Menu button is an important element in any application using Android 1.x or 2.x. All Android phones have (unlike another popular type of smartphone) the hardware Menu button, which can be used to access functions that aren’t otherwise shown onscreen.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications Or, rather, all Android phones did have this button. Beginning with Android 3.0, Android has dropped the Menu button. It still shows up on a few devices, such as on the Samsung Galaxy S III, but for the most part it’s a relic of the past. Generally speaking, elements placed on the Android menu weren’t easy to find, and users even tended to forget that they were there. In place of the menu in devices using Android 3.x and later, the action bar is almost always present across the top of the screen — and it’s therefore extremely difficult not to notice. See Figure 1-3 for an example of the action bar from the YouTube application.



Figure 1-3: The YouTube action bar for a funny cat video.

Check out these elements on the action bar:

✓ Up Button, app logo: Tap the Up button or the app logo on the action bar to move up one level. Note the subtle distinction between the Up button and the Back button: Pressing the Back button returns the user to the previous activity, regardless of which app is being used; pressing the Up button returns the user to the previous activity in the current application, even if that activity wasn’t an activity the user was just performing. Suppose that you’re viewing a web page in the Chrome browser and you tap a link to open the YouTube app. Pressing the Back button returns you to Chrome; pressing the Up button takes you to the YouTube app’s home page. ✓ Page: Next to the application icon on the action bar is the title of the current page. If your application lets you filter data on the current page, you can add a drop-down menu there to allow users to change the filter. ✓ Tab: You can put tabs (rather than the page title) on the action bar to let users switch tabs in the current activity.

www.it-ebooks.info

19

20

Part I: The Nuts and Bolts of Android ✓ Action: You can see, on the right end of the action bar, various actions that the user can perform. In the YouTube app shown in Figure 1-3, the user can add the video to a list, share the video, or search for more videos. Actions can take the form of text or icons (as shown in the figure) or both. You can add as many actions as you want. Actions that don’t fit onscreen are placed on an overflow submenu on the right end. ✓ Context action bar: The action bar can change to show what the user is doing. For example, if a user chooses several items from a list, you can replace the standard action bar with a contextual action bar to let users choose actions based on those items. For example, if you want to allow bulk deletions, you can provide a Delete Items button on the contextual action bar. Visit http://developer.android.com/guide/topics/ui/actionbar. html for more information about the versatility that this element of the user interface can add to your app. The action bar doesn’t exist at all on Android 2.x and earlier! It’s not supported by the support library either. Any action bars you add to your application will not show up in these versions of Android. But don’t dismay, the actions you put in your action bar will still show up under the Menu button for those devices, so users can still find them.

If you’re interested in placing the action bar in an app running on an earlier version of Android (on an older phone or on the Kindle Fire, for example), try ActionBarSherlock at http://actionbarsherlock.com.

Holo Android 3.0 adds three holographic themes to help you create beautiful Android applications: ✓ Holo Dark ✓ Holo Light ✓ Holo Light with dark action bars These somewhat darker themes may require some getting used to, but they’re much cleaner and more consistent than Android 2.x themes. The Holo themes are also visually less cluttered, which leaves more “real estate” for the important information you want your app to display.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications The best quality of Holo is its consistency (at long last) across all Android devices and manufacturers — a manufacturer can’t modify the Holo theme to make its version of Android look different.

Widgets, notifications, performance The list of new features in Android 3.0, 4.0, and 4.1 seems endless. Here’s a brief description of a few standouts: ✓ Widgets: Widgets are much improved in later versions of Android. They’re easier to find, now that they’ve been moved to the Applications list. You can even add list views to widgets, to handle limited swiping and scrolling, and you can resize widgets to occupy more or less space. In fact, these user-friendly widgets automatically resize as they’re dragged around the screen. These changes make them feel much more lively and responsive than in earlier versions. ✓ Notifications: Android 4.1 brings stylish new options to the formerly staid Android notification system. Because a notification is now expandable and collapsible, a user can see more information about it. For example, if your mother sends you a photo of her new puppy in a text message, you can see it directly in the notification without having to open the app. A notification about a new e-mail message can show a preview of the message text so that it can be read directly. In addition, a notification now also lets the user take action on it directly from whichever app is being used. To reply to a birthday e-mail from Grandma, for example, simply tap the Reply button on the notification to launch Gmail with an editor so that you can thank her. ✓ Performance: Android 4.1 brings significant performance improvements to the platform. You don’t have to do anything special to benefit from a faster, smoother interface in your app — it will run smoothly on devices running Android 4.1 or later.

Hardware Tools Google gives developers (even independent ones) the tools that are necessary to create top-notch, full-featured mobile apps. Google makes it simple to tap into, and make use of, all available hardware on a device.

www.it-ebooks.info

21

22

Part I: The Nuts and Bolts of Android To create a spectacular Android app, you should take advantage of all that the hardware has to offer. Don’t get us wrong — if you have an idea for an app that needs no hardware assistance, that’s okay, too. Android devices come supplied with several hardware features that you can use to build apps. Table 1-1 describes the hardware features available on most Android devices.

Table 1-1

Android Device Hardware

Android Hardware Feature

What It Does

Accelerometer

Indicates whether the phone is moving

Bluetooth radio

Indicates whether a headset is connected

Built-in compass

Indicates in which direction the user is heading

Camera

Records video

GPS radio

Indicates the user’s location

Proximity sensor

Indicates whether the device is facing up or down

Most Android devices are released with the hardware discussed in the following four sections, but not all devices are created equal. Android is free for hardware manufacturers to distribute, so it’s used in a wide range of devices, including some made by small manufacturers overseas (and it isn’t uncommon for some of these devices to be missing a feature or two). Android devices come in all shapes and sizes: phones, tablets, and e-book readers. You will find many other implementations of Android in the future, such as Google TV (an Android-powered home appliance) as well as cars with built-in, Android-powered, touchscreen computers. The engineers behind Android provide tools that let you easily deploy apps on multiple screen sizes and resolutions. Don’t worry — the Android team has done all the hard work for you. Chapter 4 covers the basics of screen sizes and densities.

Touchscreen The Android touchscreen opens a ton of possibilities to enhance users’ interaction with your apps. Users can swipe, flip, drag, or pinch to zoom, for example, by moving a finger on the touchscreen. You can even supply custom gestures in your app, which opens even more possibilities.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications Android also supports multitouch capability, which lets a user touch the entire screen with more than one finger at a time. Hardware buttons are old news. You can place buttons of any shape anywhere on the screen to create the user interface best suited for your app.

GPS Combining the Android operating system with the GPS radio on a device lets the developer access, and track, a user’s location at any time. The Foursquare social networking app is a good example — it uses the GPS feature to determine the user’s location and then accesses the web to determine the closest venues to the user. Another helpful example is the Maps application’s ability to pinpoint a user’s location on a map and provide directions to that person’s destination. Combining Android with GPS hardware gives you access to the user’s exact GPS location. Many apps use this combination to show users where the nearest gas station, coffeehouse, or even restroom is located.

Accelerometer An accelerometer is a device that measures acceleration, and Android comes packed with accelerometer support. The accelerometer tells you whether a user’s device is being moved or shaken, and even in which direction it’s being turned. You can then use this information as a way to control your application. You can use the accelerometer to perform simple tasks, such as determine when the device has been turned upside down and then complete an action. For example, you can immerse users in game play by having them shake their device to roll the dice. This level of usefulness is setting mobile devices apart from typical desktop personal computers.

SD card Android gives you the tools you need to access (save and load) files on the device’s SD card — a portable storage medium that you can insert into compatible phones, tablets, and computers. Starting with Android version 2.2 (Froyo), if a device is equipped with an SD card, you can use the card to store

www.it-ebooks.info

23

24

Part I: The Nuts and Bolts of Android and access files that are needed by your application. To avoid bloating your app with extra required resources and hogging limited built-in memory, you can download some or all of your application’s resources from your web host and save them to the device’s SD card (which makes users less likely to uninstall your app when they need to clear space on their devices).

Not every device has an SD card preinstalled, though most do. Always ensure that a device has an SD card installed and that adequate space is available before trying to save files to it.

Software Tools Various Android tools are at your disposal while you’re writing Android applications. The following sections outline some of the most popular tools to use in your day-to-day Android development process.

Internet Thanks to the Internet capabilities of Android devices, users can find realtime information on the Internet, such as the next showing of a new movie or the next arrival of a commuter train. As a developer, you can have your apps use the Internet to access real-time, up-to-date data, such as weather, news, and sports scores, or (like Pandora and YouTube) to store your application’s icons and graphics. You can even offload your application’s more intense processes to a web server whenever appropriate, to save processing time or to streamline the app. In this well-established software architecture, known as client–server computing, the client uses the Internet to make a request to a server that’s ready to perform some work for your app. The built-in Maps app is an example of a client that accesses map and GPS data from a web server.

Audio and video support Including audio and video in your apps is a breeze in the Android operating system. Many standard audio and video formats are supported, and adding multimedia content to your apps — such as sound effects, instructional videos, background music, and streaming video and audio from the Internet — couldn’t be easier. Be as creative as you want to be. The sky’s the limit.

www.it-ebooks.info

Chapter 1: Developing Spectacular Android Applications

Contacts Your app can access a user’s Contacts list, which is stored on the device, to display the contact information in a new or different way or you can create your own Contacts list. You might even write an app that couples the contact information with the GPS system to alert the user whenever she’s near a contact’s address. Don’t use information from the Contacts list in a malicious way. Use your imagination, but be responsible about it. (See the next section “Security.”)

Security Suppose that someone releases an app that sends a user’s entire Contacts list to a server for malicious purposes. For this reason, most functions that modify a user’s Android device or access its protected content need specific permissions. For example, if you want to download an image from the web, you need permission to use the Internet so that you can download the file to your device, and you need a separate permission to save the image file to an SD card. When your app is being installed, the user is notified of the permissions your app is requesting and can decide whether to proceed. Though asking for permission isn’t optional, it’s as easy as implementing a single line of code in your application’s manifest file. (Manifest files are described in Chapter 3.)

Google APIs Users of the Android operating system aren’t limited to making calls, organizing contacts, or installing apps. As a developer, you have great power at your fingertips — you can even integrate maps into your application, for example. To do so, you use the Maps APIs that contain map widgets.

Pinpointing locations on a map Perhaps you want to write an app that displays a user’s current location to friends. You can spend hundreds of hours developing a mapping system, or you can use the Android Maps API, which Google provides for use in your apps. You can embed the API in your application and you don’t have to invest hundreds of development hours or even a single cent. Using the Maps API, you can find almost anything that has an address. The possibilities are endless — a friend’s location, the nearest grocery store, or your favorite gas station, for example.

www.it-ebooks.info

25

26

Part I: The Nuts and Bolts of Android

The KISS principle The most difficult task in developing applications is remembering the KISS principle: Keep It Simple, Stupid. One way to unnecessarily complicate the code you create is to dive into development before understanding the role of the built-in APIs. Choosing this route may take more of your time than simply glossing over the Android documentation; you don’t have to memorize the documentation, but do yourself a favor and at least skim it. Then you can see how easily you can use the built-in functionality — and how much time it can save you. You can easily write multiple lines of code to complete a one-line task. Changing the volume of the



media player or creating a menu, for example, is a simple process, but if you don’t know how to use the APIs, you may cause more problems by having to rewrite them. Another way to muck things up is to add unnecessary functionality — give users the simplest way to operate their devices. For example, avoid designing a fancy, custom-tab layout when a couple of menu items will suffice. Also, Android comes supplied with enough widgets (built-in controls) to help you accomplish virtually any task. Using these controls makes your app even easier for users to work with because they already know and love them.

Showing your current location to friends is cool, but the Android Maps API can also access the Google Navigation API, to pinpoint your location and show your users how to reach it.

Messaging in the clouds Suppose that your application’s data is stored in the cloud (the Internet) and you download all its assets the first time it runs. And then you realize, after the fact, that an image is outdated. To update the image, the app needs to know that the image has changed. You can use the Google Cloud Messaging framework to send a cloud-to-device notification (a message from the web server to the device) to direct the app to update the image. This process works even if your app isn’t running. When the device receives the message, it dispatches a message to start your app so that it can take the appropriate action.

www.it-ebooks.info

Chapter 2

Prepping Your Development Headquarters In This Chapter ▶ Becoming an Android application developer ▶ Collecting your tools of the trade ▶ Downloading and installing the Android software development kit ▶ Getting and configuring Eclipse ▶ Working with the Android development tools

A

ll the software that you need to develop Android applications is free. That’s where the beauty of developing Android applications lies. The basic building blocks you need to develop rich Android applications — the tools, the frameworks, and even the source code — are free. No one gives you a free computer, but you get to set up your development environment and start developing applications for free, and you can’t beat free. Well, maybe you can — if someone pays you to write an Android application, but you’ll reach that point soon enough. This chapter walks you through the necessary steps to install the tools and frameworks so that you can start building kick-butt Android applications.

Developing the Android Developer Inside You Becoming an Android developer isn’t a complicated task. And it’s likely simpler than you believe. To see what’s involved, ask yourself these questions: ✓ Do I want to develop Android applications? ✓ Do I like free software development tools? ✓ Do I like to pay no developer fees? ✓ Do I have a computer to develop on?

www.it-ebooks.info

28

Part I: The Nuts and Bolts of Android If you answered yes to every question, today is your lucky day — you’re ready to become an Android developer. You may be wondering what we mean by pay no developer fees. You’re reading that question correctly: You pay no fees to develop Android applications. There’s always a catch, right? You can develop for free to your heart’s content, but as soon as you want to publish your application to the Google Play Store, where you upload and publish your apps, you need to pay a small, nominal registration fee. At this writing, the fee is $25.

If you’re developing an application for a client, you can publish your application as a redistributable package to give to him. Then your client can publish the application to the Google Play Store, using his Google account, to ensure that you don’t have to pay a fee for client work. You can then be a bona fide Android developer and never have to pay a fee. That’s cool.

Assembling Your Toolkit After you know that you’re ready to be an Android developer, grab your computer and get cracking on installing the tools and frameworks necessary to build your first blockbuster application.

Linux 2.6 kernel Android was created on top of the open source Linux 2.6 kernel. The Android team chose to use this kernel because it provided proven core features on which to develop the Android operating system. The features of the Linux 2.6 kernel include (but aren’t limited to) ✓ Security model: The Linux kernel handles security between the application and the system. ✓ Memory management: The kernel handles memory management, leaving you free to develop your app. ✓ Process management: The Linux kernel manages processes well, allocating resources to processes as they need them. ✓ Network stack: The Linux kernel also handles network communication. ✓ Driver model: The goal of Linux is to ensure that the application works. Hardware manufacturers can build their drivers into the Linux build. You can see a good sampling of the Linux 2.6 feature set in Figure 2-1.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters



Figure 2-1: Some Linux kernel features.



Android framework Atop the Linux 2.6 kernel, the Android framework was developed with various features. These features were pulled from numerous open source projects. The output of these projects resulted in these elements: ✓ The Android runtime: The Android runtime is composed of Java core libraries and the Dalvik virtual machine. ✓ Open GL (graphics library): This cross-language, cross-platform application program interface (API) is used to produce 2D and 3D computer graphics. ✓ WebKit: This open source web browser engine provides the functionality to display web content and to simplify page loading. ✓ SQLite: This open source relational database engine is designed to be embedded in devices. ✓ Media frameworks: These libraries allow you to play and record audio and video. ✓ Secure Sockets Layer (SSL): These libraries are responsible for Internet security. See Figure 2-2 for a list of common Android libraries.

Android source code You should be aware that the full Android source code is open source, which means that it’s not only free to use but also free to modify. If you want to download the Android source code and

create a new version of Android, you’re free to do so. Check the Android Open Source Project at http://source.android.com.

www.it-ebooks.info

29

30

Part I: The Nuts and Bolts of Android



Figure 2-2: Android and other third-party libraries sit atop the Linux 2.6 kernel.



Application framework If you’ve read the preceding section, you may say, “Well, that’s all nice and well, but how do these libraries affect me as a developer?” It’s simple: All these open source frameworks are available to you via Android. You don’t have to worry about how Android interacts with SQLite and the surface manager; you use them as tools in your Android tool belt. The Android team has built on a known set of proven libraries, built in the background, and has given them to you, all exposed through Android interfaces. These interfaces wrapped up the various libraries and made them useful to the Android platform and to you as a developer. You benefit from these features because you don’t have to build any of the functionality they provide: ✓ Activity manager: Manages the activity life cycle. ✓ Telephony manager: Provides access to telephony services as well as to certain subscriber information, such as phone numbers. ✓ View system: Handles the views and layouts that make up your user interface (UI). ✓ Location manager: Finds the device’s geographic location. Take a look at Figure 2-3 to see the libraries that make up the application framework.



Figure 2-3: A glimpse at part of the Android application framework.



www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters From kernel to application, the Android operating system has been developed with proven open source technologies. You, as a developer, can therefore build rich applications that have been fostered in the open source community. See Figure 2-4 for a full picture of how the Android application framework stacks up. The Applications section is where your application sits.



Figure 2-4: How the Android application framework stacks up.





Sometimes when you’re developing an Android application, you want to use the same resource as in the core Android system. A good example is an icon for a Settings menu option. By accessing the Android source code, you can browse the various resources and download the resources you need for your project. Having access to the source code also allows you to dig in and see exactly how Android does what it does. Be aware though that you need to follow Google’s branding guidelines when borrowing these resources. Find out more at http://developer.android.com/distribute/googleplay/ promote/brand.html.

Open Handset Alliance libraries Huh? You didn’t join an “alliance,” so what’s the Open Handset Alliance about? Don’t worry — you don’t have to use The Force to battle Darth Vader. It’s not that big of a deal, and it’s even kind of cool, like a bunch of smart companies combining their efforts to achieve the same goal. The Open Handset Alliance (OHA) was announced in November 2007. At the time, the alliance consisted of 34 members, led by Google. With 84 members at the time this book was published, this group of technology and mobile

www.it-ebooks.info

31

32

Part I: The Nuts and Bolts of Android companies (including T-Mobile, Sprint, LG, Motorola, HTC, NVidia, and Texas Instruments) have come together to pursue innovation in the mobile field and make the world a better place. Their goal is to provide users with comprehensive, compelling, and useful handsets. You can read more about the OHA at www.openhandsetalliance.com. You should be aware of the OHA because all the libraries that comprise the Android operating system are based on open source code. Every member contributes in its own, special way. Chip manufacturers ensure that chipsets support the platform; hardware manufacturers build devices; and other companies contribute intellectual property (code and documentation, for example). The goal is to make Android a commercial success. As these members contribute, they also start to innovate on the Android platform. Some of this innovation is incorporated into the Android source code, and some of it remains the intellectual property of the alliance members as decided by the OHA. Just because one device has a fancy doohickey on it doesn’t mean that another device will. The only thing you can count on as a developer is the core Android framework. OHA members may have added an extra library to help facilitate something on a device, but you have no guarantee that this library will be available on another device in, say, Turkey or England. An exception occurs if you’re developing for a particular device, and only that device, such as an e-book reader. If that hardware has the sole function of reading books, you can program it for that specific purpose. Such as the Barnes & Noble Nook, which is powered by Android. It has special Forward and Back buttons that other Android devices don’t have. Therefore, you’d program for these buttons because this device is a special case (if you’re developing for the Nook), but you can’t expect these buttons to be used on other devices.

Java knowledge The Java programming language is one of the glorious tools that make programming Android a breeze compared with programming for other mobile platforms. Whereas other languages insist that you manage memory, deallocate and allocate bytes, and then shift bits around like a game of dominoes, Java’s little buddy, the Java Virtual Machine (JVM), helps take care of that for you. The JVM allows you to focus on writing code to solve a business problem by using a clean, understandable programming language (or to build that next cool first-person shooter game you’ve been dreaming of) instead of focusing on the “plumbing” just to get the screens to show up.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters You’re expected to understand the basics of the Java programming language before you write your first Android application. If you’re feeling rusty and need a refresher course on Java, you can visit the Java tutorials site at http://docs.oracle.com/javase/tutorial.

Though you find a little Java information in this book, you may want to spend some time with a good book like Java All-in-One For Dummies, by Doug Lowe (John Wiley & Sons, Inc.), if you have no Java experience.

Tuning Up Your Hardware You can develop Android applications on various operating systems, including Windows, Linux, and Mac OS X. In this book, you find a combination of the Windows 7 operating system and Mac OS X, but you can use Linux as well.

Operating system Android supports these platforms: ✓ Windows XP or later ✓ Mac OS X 10.5.8 or later (x86 only) ✓ Ubuntu Linux Note that 64-bit Linux distributions must be capable of running 32-bit applications. Visit http://developer.android.com/sdk/installing/index. html for more details. Throughout this book, some examples use Windows 7 64-bit Edition. Windows paths look similar to this: c:\path\to\file.txt Some examples use Mac OS X; a Mac or Linux path looks similar to this: /path/to/file.txt

www.it-ebooks.info

33

34

Part I: The Nuts and Bolts of Android

Computer hardware Before you start installing the required software, make sure that your computer can run it adequately. Just about any desktop or laptop computer manufactured in the past four years will suffice. A laptop with a 1.6GHz Pentium D processor with 1GB of RAM running Windows XP and Windows 7 can run and debug Eclipse applications with no problem. (Eclipse — the software you use to develop your applications — should run smoothly on whatever computer you use.) To ensure that you can install all the tools and frameworks you’ll need, make sure that you have enough hard drive space to accommodate them. The Android developer site has a list of hardware requirements, outlining how much hard drive space each component requires, at http://developer. android.com/sdk/requirements.html.

To save you time, you need about 3GB of free hard drive space to install all the tools and frameworks necessary to develop Android applications.

Installing and Configuring Your Support Tools It’s time to put these exciting Android concepts into action, but before you can do so, you need to install and configure a few tools, including the software development kits (SDKs): ✓ Java JDK: Lays the foundation for the Android SDK. ✓ Android SDK: Provides access to Android libraries and allows you to develop for Android. ✓ Eclipse IDE (integrated development environment): Brings together Java, the Android SDK, and the Android Android Development Tools (ADT) and provides tools for you to write Android programs. ✓ Android ADT: Does a lot of the grunt work for you, such as creating the files and structure required for an Android app. The following sections show you how to acquire and install all these tools. A benefit of working with open source software is that, most of the time, you can get the tools to develop the software for free. Android is no exception to that rule. All the tools that you need to develop rich Android applications are free.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters

Getting the Java Development Kit For some reason, the folks responsible for naming the Java SDK decided that it would be more appropriate to name it the Java Development Kit, or JDK. The following steps work for Windows machines, but the steps are similar for Macs or Linux machines. Follow these steps to install the JDK:

1. Go to www.oracle.com/technetwork/java/javase/downloads/ index.html.

The Java SE downloads page appears. See Figure 2-5.

2. Click the Download button for the Java Platform (JDK). A new Java SE Downloads page appears, asking you to specify which platform (Windows, Linux, or Mac) you’re using for your development work. The web page shown in Figure 2-5 may look different in the future. To ensure that you’re visiting the correct page, visit the Android SDK System Requirements page in the online Android documentation for a direct link to the Java SDK download page. View the requirements page at http://developer.android.com/sdk/requirements.html.

Figure 2-5: Select JDK.





www.it-ebooks.info

35

36

Part I: The Nuts and Bolts of Android

3. Click the Download link for the particular operating system you’re using.

On Windows, choose the 32-bit install. If you’re on a 64-bit machine, you can install both the 32-bit (x86) and 64-bit (x64) JDKs if you like, but you must install the 32-bit to develop with Android. Windows may open a message box with a security warning.

4. In the Save As dialog box, select the location where you want to save the file, and click Save.



5. When the download is complete, double-click the file to install the JDK.

A dialog box asks whether you want to allow the program to make changes to your computer.

6. Click the Yes button.

If you click the No button, the installation stops.

7. When you’re prompted to do so, read and accept the license agreement. That’s all there is to it. You have the JDK installed and are ready to move to the next phase.

Acquiring the Android SDK The Android SDK is composed of a debugger, Android libraries, a device emulator, documentation, sample code, and tutorials. You can’t develop Android apps without the SDK.

Downloading the Android SDK To download the Android SDK, follow these steps:

1. Go to http://developer.android.com/sdk/index.html.



2. Choose the latest version of the SDK starter package for your platform to download the SDK.

You’ve just downloaded the Android SDK.

3. Open SDK Manager. • Windows: Run the SDK Installer and install the SDK to the default location. When finished, check the Start SDK Manager check box and click Finish. If you’re prompted to accept the authenticity of the file, click Yes. The Android SDK Manager dialog box opens.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters

• Mac: Double-click the SDK file to unzip it. Move the resulting android-sdk-mac_x86 directory to a safe place, such as your Applications directory. Open the Terminal and enter cd to go to the android-sdk-mac_x86 directory, and then run tools/ android. You may be prompted to install Java at this point if you don’t already have it. If so, click Install.



4. Select the SDK Platform Android 4.1 check box.

For the purposes of this book, select version 4.1, as shown in Figure 2-6. At this writing, 4.1 is the latest and greatest version of Android. You should also select the check boxes for the documentation and samples that correspond with Android version 4.1 (API 16). Every time a new version of the Android operating system is released, Google also releases an SDK that contains access to the added functionality in that version. If you want to include Bluetooth functionality in your app, for example, make sure that you have Android SDK version 2.0 or later because this functionality isn’t available in earlier versions.



Figure 2-6: Choose packages to install.

5. Click Install packages.

The Choose Packages to Install dialog box opens.

6. Select the Accept radio button to accept the license, and then click Install, as shown in Figure 2-7.

The Installing Archives dialog box opens, displaying a progress bar.

7. When the archives installation is complete, click the Close button.

www.it-ebooks.info

37

38

Part I: The Nuts and Bolts of Android



Figure 2-7: The Choose Packages to Install dialog box.





While the Android SDK is attempting to connect to the servers to obtain the files, you may occasionally see the Failure to fetch URL error. If this happens to you, navigate to Settings, select Force https://... Sources to Be Fetched Using http://, and then attempt to download the available packages again.

Following and setting your tools path Setting the tools path is optional, but doing so saves you from having to remember and type the full path when you’re accessing the Android Debug Bridge (adb) via the command line. The adb lets you manage the state of an emulator or Android device so that you can debug your application or interact with the device at a high level. The adb tool has a lot of capabilities. For detailed information, see the Android documentation.

Adding the optional Android NDK The set of tools known as the Android Native Development Kit (NDK) is a set of tools that allows lets you to embed components that use native code — code that you’ve written in a native language such as C or C++. Most developers won’t ever need the NDK to build their apps.

If you decide to take on the NDK, you still have to download the SDK. The NDK isn’t a replacement for the SDK. It’s an added functionality set that complements the SDK.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters To add the Android tools to your system-path variable on a Windows machine, follow these steps:

1. Open Control Panel, and double-click the System icon to open System Preferences.



2. Click the Advanced System Settings link to open the System Properties window.



3. Click the Environment Variables button to open the Environment Variables dialog box.



4. Click the New button.

The New System Variable dialog box opens, as shown in Figure 2-8.



Figure 2-8: The Environment Variables dialog box.





5. In the Variable Name field, type ANDROID.



6. Type the full path to the SDK directory (c:\android\android-sdkwindows\) in the Variable Value field.



7. Click OK.

The Environment Variables dialog box opens, as shown in Figure 2-9.



Figure 2-9: Editing the PATH variable.



www.it-ebooks.info

39

40

Part I: The Nuts and Bolts of Android

8. In the System Variables section, select the PATH variable.



9. Click Edit and then type the following text at the end of the Variable Value field and click OK: ;%ANDROID%/tools;%ANDROID%/platform-tools If you’re on a Mac, open the .profile file in your home directory (/Users/ ) using TextEdit. If you can’t see it, press ⌘+Shift+ period in the Open File dialog box to show hidden files. At the end of .profile, add the following: export ANDROID= export PATH=$PATH:$ANDROID/tools:$ANDROID/platform-tools

Then save the file and restart your Mac. That’s it — you’re done. Now any time you access the Android tools directory, simply use your newly created environment variable.

In most operating systems, the system PATH variable won’t be updated until you log out of and log back on to your operating system. If you find that your PATH variable values aren’t present, try logging out of your computer and logging back on to your computer.

Getting the Total Eclipse After you have the SDK, you need an integrated development environment (IDE) to use it. It’s time to download Eclipse!

Installing Eclipse To download Eclipse, navigate to the Eclipse downloads page at www. eclipse.org/downloads. Select Eclipse IDE for Java Developers (Eclipse IDE for JAVA EE Developers works as well) and download the zip file. To install Eclipse, extract the contents of the Eclipse .zip file to the location of your choice, such as C:\Program Files\Eclipse on Windows or in your Applications folder on a Mac. On Windows, once you unzip Eclipse, pin a shortcut to your Start menu instead so that Eclipse is easy to find when you need it.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters To start Eclipse, follow these steps:

1. To run Eclipse, double-click the Eclipse icon.

If you’re running a recent version of Windows, the first time you run Eclipse, a Security Warning dialog box may appear, as shown in Figure 2-10. It tells you that the publisher hasn’t been verified and asks whether you still want to run the software. Clear the Always Ask Before Opening This File check box, and click the Run button.



Figure 2-10: The Windows security warning.

2. Set your workspace.

When Eclipse starts, the first thing you see is the Workspace Launcher dialog box, as shown in Figure 2-11. You can modify your workspace there, if you want, but for this book, you can stick with the default: c:\users\\workspace on Windows, or \Users\\workspace on a Mac Leave the Use This As the Default and Do Not Ask Again check box deselected, and click the OK button. If you plan to develop multiple applications, use a separate workspace for each project. If you store multiple projects in one workspace, maintaining organization becomes difficult, and you can easily change a similarly named file in a different project. Keeping projects in their own workspaces makes it easier to find the project when you have to go back to it to fix bugs. When Eclipse finishes loading, you see the Eclipse welcome screen, shown in Figure 2-12.

www.it-ebooks.info

41

42

Part I: The Nuts and Bolts of Android



Figure 2-11: Set your workspace.



Figure 2-12: The Eclipse welcome screen.



3. Click the curved-arrow icon on the right side of the screen to go to the workbench.

Eclipse is installed and easily accessible. You configure it in the next section.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters

Configuring Eclipse The Android Development Tools (ADT) plug-in adds functionality to Eclipse to do a lot of the work for you. The ADT allows you to ✓ Create new Android projects easily. ✓ Start coding your application quickly because it creates all the necessary base files. ✓ Debug your application using the Android SDK tools. ✓ Export a signed application file, known as an Android Package (APK), right from Eclipse, eliminating the need for some command-line tools. Programmers used to need various command-line utilities to build an APK. Although that task wasn’t difficult, it was tedious and sometimes frustrating. The ADT eliminates this frustrating process by guiding you through it “wizard style” from within Eclipse. Flip to Chapter 8 to export a signed APK.

Setting up Eclipse with the ADT To set up Eclipse with the ADT, follow these steps:

1. Start Eclipse, if it’s not already running.



2. Choose Help➪Install New Software.

The Install window opens. You use this window to install new plug-ins in Eclipse.

3. Click the Add button to add a new site. A site is a web address where software is hosted on the Internet. Adding a site to Eclipse makes it easier for you to update the software when a new version is released.

The Add Repository window opens, as shown in Figure 2-13.



Figure 2-13: Enter the name and location of the site.



www.it-ebooks.info

43

44

Part I: The Nuts and Bolts of Android

4. Type a name in the Name field.

This name can be anything you choose, but an easy one to remember is Android ADT.

5. Type https://dl-ssl.google.com/android/eclipse/ in the Location field.



6. Click OK.

Android ADT is selected in the Work With drop-down menu, and the available options are displayed in the Name and Version window of the Install Details dialog box, as shown in Figure 2-14.



Figure 2-14: Select Developer Tools.

7. Select the check box next to Developer Tools, and click the Next button.

The Install Details dialog box should list both the Android DDMS (see “Getting physical with a real Android device,” later in this chapter) and the ADT. See Figure 2-15.

8. Click the Next button to review the software licenses.



9. Click the Finish button.



10. When you’re prompted to do so, click the Restart Now button to restart Eclipse.

The ADT plug-in is installed.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters



Figure 2-15: DDMS and ADT listed in the Install Details dialog box.





If you’re having difficulty downloading the tools from https://dl-ssl. google.com/android/eclipse, try removing the s from https://, like this: http://dl-ssl.google.com/android/eclipse.

Setting the location of the SDK This section guides you through the configuration process. Completing it seems like a lot to do, but you’re almost done, and you have to do this work only once. Follow these steps:

1. Choose Window➪Preferences.

The Preferences dialog box opens, as shown in Figure 2-16.

2. Select Android in the left pane.



3. Set the SDK Location to the folder to which you saved the Android SDK.

If you saved Android SDK to c:\android on your computer, the location is c:\android\android-sdk-windows.

4. Click OK. Eclipse is configured, and you’re ready to start developing Android apps.

www.it-ebooks.info

45

46

Part I: The Nuts and Bolts of Android



Figure 2-16: Specify the location of the SDK in the Preferences dialog box.



Navigating the Android SDK Whoa — you find a lot of folders in the SDK! Don’t worry: The folder structure of the Android SDK is easy to understand when you get the hang of it. You need to understand the structure of the SDK to be able to master it. Table 2-1 outlines the content of each folder.

Table 2-1

Folders in the Android SDK

SDK Folder

What It Contains

usb_driver

Drivers for Android devices. If you connect your Android device to the computer, install this driver so that you can view, debug, and push applications to your phone via the ADT. The usb_driver folder isn’t visible until you install the USB driver.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters SDK Folder

What It Contains

tools and platform-tools

Various tools that are available for use during development — such as for debugging, view management, and building.

temp

A temporary swapping location for the SDK when it needs a temporary space to perform work.

samples

Sample projects for you to play with. Full source code is included.

platforms

The platforms you target when you build Android applications, such as folders named android-16 (which is Android 4.1) and android-8 (which is Android 2.2).

docs

A local copy of the Android SDK documentation.

add-ons

Additional APIs that provide extra functionality. The Google APIs in this folder include mapping functionality. This folder remains empty until you install any of the Google Maps APIs.

Targeting Android Platforms Android platform is a fancy way of saying Android version. At this writing, many versions of Android are available, ranging up through version 4.1. You can target any platform you choose. Several versions of Android are still widely used on phones. If you want to reach the largest number of users, target an earlier version. If your app requires functionality that older platforms can’t support, however, by all means target the newer platform. It would make no sense to write a Bluetooth toggle widget targeting any platform earlier than 2.0 because earlier platforms can’t use Bluetooth. Figure 2-17 shows the percentage of each platform in use as of May 2012. To view current platform statistics, visit http://developer.android.com/ resources/dashboard/platform-versions.html.

www.it-ebooks.info

47

48

Part I: The Nuts and Bolts of Android



Figure 2-17: Android distribution as of May 2012.



Using SDK Tools for Everyday Development The SDK tools are the building blocks you use in developing Android apps. New features packed into every release enable you to develop for the latest version of Android.

Saying hello to the emulator Google provides not only the tools you need to develop apps but also an awesome little emulator to test your app. The emulator has some limitations (for example, it cannot emulate certain hardware components, such as the accelerometer) but not to worry — plenty of apps can be developed and tested using only an emulator. When you’re developing an app that uses Bluetooth, for example, you should use a physical device that has Bluetooth on it. If you develop on a speedy computer, testing on an emulator is fast; on slower machines, however, the emulator can take a long time to complete a seemingly simple task. If you’re developing on an older machine, use a physical device. When you’re developing on a newer, faster machine, use the emulator.

www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters The emulator is handy for testing apps at different screen sizes and resolutions. It isn’t always practical or possible to have several devices connected to your computer at the same time, but you can run multiple emulators with varying screen sizes and resolutions.

Getting physical with a real Android device The emulator is awesome, but sometimes you need a physical device for testing. The Dalvik Debug Monitor Server, or DDMS, allows you to debug your app on an actual device, which comes in handy for developing apps that use hardware features that aren’t, or can’t be, emulated. Suppose that you’re developing an app that tracks the user’s location. You can send coordinates to the device manually, but at some point in your development, you probably want to test the app to find out whether it, in fact, displays the correct location. Using an actual device is the only way to do it. If you develop on a Windows machine and you want to test your app on a real-life device, you need to install a driver. If you’re on a Mac or Linux machine, you can skip this section because you don’t need to install the USB driver. To download the Windows USB driver for Android devices, follow these steps:

1. In Eclipse, choose Window➪Android SDK Manager.

The Android SDK Manager dialog box opens, as shown in Figure 2-18.

2. Expand the Extras repository, and select the Google USB Driver package.



3. Click the Install Packages button.

The Choose Packages to Install dialog box opens, as shown in Figure 2-19.

www.it-ebooks.info

49

50

Part I: The Nuts and Bolts of Android



Figure 2-18: Available packages.





4. Select the Accept radio button to accept the license, and then click the Install button.

The Installing Archives dialog box opens, displaying a progress bar.



Figure 2-19: Click the Install button.



www.it-ebooks.info

Chapter 2: Prepping Your Development Headquarters

5. When the package finishes downloading and installing, click the Close button.



6. Exit the Android SDK Manager dialog box.

Debugging your work The DDMS equips you with the necessary tools to find those pesky bugs, allowing you to go behind the scenes as your app is running to see the state of its hardware, such as the wireless radio. But wait — there’s more! The DDMS also simulates actions normally reserved for physical devices, such as sending global positioning system (GPS) coordinates manually, simulating phone calls, or simulating text messages. Get all the DDMS details at http://developer.android.com/guide/developing/debugging/ ddms.html.

Trying out the API and SDK samples The API and SDK samples are provided to demonstrate how to use the functionality provided by the API and SDK. If you’re ever stuck and can’t figure out how to make something work, visit http://developer.android.com/ resources/samples/index.html to find samples of almost anything, from using Bluetooth to making a two-way text application or a 2D game. You also have a few samples in your Android SDK. Simply open the Android SDK and navigate to the samples directory, which contains various samples that range from interacting with services to manipulating local databases. Spend some time playing with the samples — the best way to learn to develop Android applications is to look at existing working code bases and then experiment with them in Eclipse.

Giving the API demos a spin The API demos inside the samples folder in the SDK are a collection of apps that demonstrate how to use the included APIs. You can find sample apps with a ton of examples, such as ✓ Notifications ✓ Alarms

www.it-ebooks.info

51

52

Part I: The Nuts and Bolts of Android ✓ Intents ✓ Menus ✓ Search ✓ Preferences ✓ Background services If you get stuck or you simply want to prepare yourself for writing your next spectacular Android application, check out the complete details at http://developer.android.com/resources/samples/ApiDemos/ index.html.

www.it-ebooks.info

Part II

Building and Publishing Your First Android Application

www.it-ebooks.info

P

In this part . . .

art II walks you through developing a useful Android application. You start with the basics of the Android tools and then delve into developing the screens and home-screen widgets that users will interact with. When the application is complete, you sign your application digitally so that you can deploy it to the Google Play Store. You finish by publishing your application to the Google Play Store.

www.it-ebooks.info

Chapter 3

Your First Android Project In This Chapter ▶ Creating a new, blank project in Eclipse ▶ Understanding errors ▶ Creating an emulator ▶ Setting up and copying launch configurations ▶ Running your first app ▶ Studying the anatomy of a project ▶ Closing the project

B

efore you start creating that next blockbuster Android application, we walk you through creating your first Android application to help solidify a few key aspects in the Android project-creation process. In this chapter, you create a simple “Hello Android” application that requires no coding whatsoever. What — no coding? How is that possible? Follow along as we show you.

Starting a New Project in Eclipse First things first: Start Eclipse. You should see a screen that looks similar to the one shown in Figure 3-1. Now you’re ready to start cooking with Android. If you haven’t set up your development environment yet, turn to Chapter 2. It shows you how to set up all the tools and frameworks necessary to develop Android applications and, in the process, install the Eclipse Android Development Tools (ADT) plug-in. It gives you the power to generate new Android applications directly from within the Eclipse File menu.

www.it-ebooks.info

56

Part II: Building and Publishing Your First Android Application



Figure 3-1: The Eclipse development environment.

Follow these steps to create your first Android application project:



1. In Eclipse, choose File➪New➪Other. Select Android Application Project.

The New Android App Wizard opens, as shown in Figure 3-2.

2. Enter Hello Android as the application name.

The application name is the name of the application as it pertains to Android. When the application is installed on the emulator or physical device, this name appears in the application launcher. The Project and Package names should autocomplete for you. The Project Name field is important. The descriptive name you provide identifies your project in the Eclipse workspace. After your project is created, a folder in the workspace is named with the project name you define. When you set up Eclipse in Chapter 2, the Eclipse system asks you to set your default workspace. The workspace usually defaults to your home directory, where the system places files pertinent to you and where you can find your home directory listed in the Location field. If you would rather store your files in a location other than the default workspace location, deselect the Create Project in Workspace check box, which enables the Location text box. Click the Browse button, and select a location where you want your files to be stored.

www.it-ebooks.info

Chapter 3: Your First Android Project



Figure 3-2: The New Android App Wizard.

3. In the Package Name box, type com.dummies.android.helloandroid.

This is the name of the Java package. (See the nearby sidebar “Java package nomenclature.”)

Java package nomenclature A package in Java is a way to organize Java classes into namespaces similar to modules. Each package must have a unique name for the classes it contains. Classes in the same package can access one another’s package-access members. Java packages have a naming convention defined as the hierarchical naming pattern. Each level of the hierarchy is separated by periods. A package name starts with the highest-level domain name of the organization; then the subdomains are listed in reverse order. At the end of the package name, the company can choose what it wants to call the package. The package

name com.dummies.android.hello android is the name used in this example. Notice that the highest-level domain is at the front of the package name (com). Subsequent subdomains are separated by periods. The package name traverses through the subdomains to get to the final package name of helloandroid. A great example of another use for a package is having a Java package for all your web-related communications. Any time you needed to find a web-related Java class, you can open that Java package and work on your web-related Java classes. Packages allow you to keep your code organized.

www.it-ebooks.info

57

58

Part II: Building and Publishing Your First Android Application

Understanding Android versioning Version codes aren’t the same as version names. (Huh?) Android has version names and version codes. Each version name has a single version code associated with it. The following Version Name (Platform Level) 2.0 2.0.1 2.1 2.2 2.3.0–2.3.2 2.3.3 - 2.3.4 3.0 3.1 3.2 4.0.0 - 4.0.2 4.0.3 4.1



table outlines the version names and their respective version code. You can also find this information in the Build Target section of the New Android Project dialog box. Version Code (API Level) 5 6 7 8 9 10 11 12 13 14 15 16

4. Select Android 4.1 from the Build SDK drop-down list and API 8: Android 2.2 from the Minimum Required SDK drop-down list, and then click Next.

The Build SDK drop-down list identifies which application programming interface (API) you want to develop for this project. Always set the Build Target SDK to the latest version that you’ve tested your app on. When you select Android 4.1, you build and test your app on devices going up to Android 4.1. Doing so allows you to develop with the Android 4.1 APIs, which include new features such as Android Beam. If you had selected Android 2.2 as the target, you wouldn’t be able to use any features supported by version 4.1 (or 3.1). Setting the Minimum Required SDK version lower than the Build Target SDK means that your app still runs on older devices, all the way down to Android 2.2 in this case. When you set the build target and minimum required SDKs to different values, you can’t use any APIs newer than the minimum required SDK on old devices. For example, you can’t use Android Beam on an Android 2.2 device; the app will crash.

www.it-ebooks.info

Chapter 3: Your First Android Project For more information, see the section “Understanding the Build Target and Min SDK Version settings,” later in this chapter. The Android Application Icon Editor appears.

5. (Optional) Create an application icon for your project and click Next.



6. In the Create Activity box, choose BlankActivity and click Next.

The New Blank Activity screen appears, as shown in Figure 3-3.



Figure 3-3: Set up your new activity.

7. Enter MainActivity in the Activity Name box.

The New Blank Activity screen defines what the initial activity is called — the entry point to your application. When Android runs your application, this file is the first one to be accessed. A common naming pattern for the first activity in your application is MainActivity.java. (How creative.)

8. Click the Finish button.

You’re done! You should see Eclipse with a single project in the Package Explorer. For the purpose of this book, Package Explorer and Project Explorer (which is showing in Figure 3-4) are the same thing. Different names; same function.

www.it-ebooks.info

59

60

Part II: Building and Publishing Your First Android Application



Figure 3-4: The Eclipse development environment with your first Android project, Hello Android.



Deconstructing Your Project The Android project generated by Eclipse is a fresh, clean project with no compiled binary sources. Sometimes, Eclipse takes a second to catch up to you, so you may notice minor oddities about the system. You also need to understand what happens under the hood of Eclipse at a high level. That’s what you find in the next couple of sections.

Responding to error messages If you were quick enough to look (or if your computer runs on the slower edge of the spectrum), you may have noticed, immediately after you clicked the Finish button, a little red icon hovering over the Hello Android folder icon in the Package Explorer in your Eclipse window. (See Figure 3-5.) That icon is Eclipse’s way of letting you know that something is wrong with the project in the workspace.

www.it-ebooks.info

Chapter 3: Your First Android Project



Figure 3-5: A project with errors in Eclipse.



By default, Eclipse is set up to let you know with this visual cue when an error is found within a project. How can you have an error with this project? You just created the project using the New Android Project Wizard — what gives? Behind the scenes, Eclipse and the Android Development Tools do a few things for you: ✓ Provide workspace feedback: This feedback lets you know when a problem exists with any project in the workspace. You receive notification in Eclipse via icon overlays, such as the one shown in Figure 3-5. Another icon overlay you may see often is a small yellow warning icon, which alerts you to some warnings in the contents of the project. ✓ Automatically compile: By default, Eclipse autocompiles the applications in your workspace when any files within them are saved after a change.

If you don’t want automatic recompilation turned on, you can turn it off by choosing Project➪Build Automatically. This command disables the automatic building of the project. If this option is deselected, build your project manually by pressing Ctrl+B every time you change your source code. So why are you getting an error in the first build? When the project was added to your workspace, Eclipse took over and, in conjunction with the ADT, determined that the project in the workspace had an error. The issue that raised the error in Eclipse was that neither the gen folder nor its contents were present. (See the section “Understanding Project Structure,” later in this chapter, for information about the gen folder.) The gen folder is automatically generated by Eclipse and the ADT when the compilation takes place. The process works like this:



1. As soon as the New Android Project Wizard finishes, Eclipse creates and saves the new project in its workspace.



2. Eclipse sees the new project and says, “Hey! I see some new files in my workspace. I need to report any errors I find and compile the project.”



3. Eclipse reports the errors by placing an error icon over the folder. (Refer to Figure 3-5.)

www.it-ebooks.info

61

62

Part II: Building and Publishing Your First Android Application

4. Eclipse compiles the project.

During the compilation step, the gen folder is created by Eclipse, and the project is successfully built.

5. Eclipse recognizes that the project has no more errors and removes the error icon from the folder.

You’re left with a clean workspace and a clean folder icon, as shown in Figure 3-6.



Figure 3-6: A project in the Package Explorer that has no errors.



Understanding the Build Target and Min SDK Version settings The build target is the operating system in which you write code. If you choose 4.1, you can write code with all the APIs in version 4.1. If you choose 2.2, you can write code only with the APIs that are in version 2.2. You can’t use the Wi-Fi Direct APIs in version 2.2, for example, because they weren’t introduced until version 4.0. If you’re targeting 4.1, you can write with the Wi-Fi Direct APIs.

Know which version you want to target before you start writing your Android application. Identify which Android features you need to use to ensure that your app functions as you expect. If you’re positive that you need Bluetooth support, target at least version 2.0. If you’re not sure which versions support the features you’re looking for, you can find that information on the platformspecific pages in the SDK section of http://d.android.com. The Android 4.1 platform page is at http://d.android.com/sdk/android-4.1.html. Android operating system (OS) versions are backward-compatible. If you target Android version 2.2, for example, your application can run on Android 4.x, 3.x, and of course 2.2. The benefit of targeting the 2.2 framework is that your application is exposed to a much larger market share. Your app can be installed on devices with version 2.2, 3.0, or 4.0 (and on future versions, assuming that no breaking framework changes are introduced in future Android OS releases). Selecting an older version isn’t free of consequences, however. By targeting an older framework, you’re limiting the functionality you have access to. By targeting 2.2, for example, you don’t have access to the social media APIs.

www.it-ebooks.info

Chapter 3: Your First Android Project

Version codes and compatibility The Min SDK Version is also used by the Google Play Store (covered in detail in Chapter 8) to help identify which applications to show users based on which version of Android they’re running. If a user’s device is running version code 8 (Android 2.2), you want your app to show up if it’s compatible with version code 3, not with version code 16 (Android 4.1) apps. The Google Play Store manages which apps to show to each user via the Min SDK Version setting.

If you’re having trouble deciding which version to target, the current version distribution chart can help you decide: http://developer. android.com/about/dashboards. A good rule is to analyze the distribution chart to determine which version will give your app the best market share. The more devices you can target, the wider your audience; the more installs you have, the more successful your app.

The Min SDK Version setting is the minimum version of Android that the user must be running for the application to run properly on the device. This field isn’t required to build an app, but if you don’t indicate the Min SDK Version, a default value of 1 is used, indicating that your application is compatible with all versions of Android. If your application is not compatible with all versions of Android (for example, if it uses APIs that were introduced in version code 5 — Android 2.0) and you haven’t declared the Min SDK Version, when your app is installed on a system with an SDK version code of less than 5, your application will crash at runtime when it attempts to access the unavailable APIs. As a best practice, always set the Min SDK Version in your application to prevent these types of crashes.

Setting Up an Emulator You’re almost ready to run your application in Eclipse. You have one final thing to set up, and then you get to see all your setup work come to life in the Hello Android application. To see this application in a running state, you need to know how to set up an emulator through the various launch configurations. You need to create an Android Virtual Device (AVD), also known as an emulator. An AVD is a virtual Android device that looks, acts, walks, and talks (well, maybe not walks and talks) like a physical Android device. AVDs can be configured to run any particular version of Android as long as the SDK for that version is downloaded and installed. It’s time to get reacquainted with the old standbys Android SDK and AVD Manager. Follow these steps to create your first AVD:

www.it-ebooks.info

63

64

Part II: Building and Publishing Your First Android Application

1. Click the icon on the Eclipse toolbar, shown in Figure 3-7.

The AVD Manager dialog box opens.

Figure 3-7: The Android AVD Manager icon on the Eclipse toolbar.





AVD nomenclature Be careful when naming AVDs. Android is available on many devices in the real world, such as phones, e-book readers, and netbooks. The time will come when you have to test your app on various configurations; therefore, adhering to a common nomenclature when creating AVDs can later help you recognize which AVD is intended for what purpose. The following line can help you remember the purpose of an AVD: {TARGET_VERSION}_{SKIN}_{SCREENSIZE}[{_Options}] The AVD 4_1_Default_WVGA has the TARGET_VERSION value of Android 4.1. The version name 4.1 is transformed into 4_1. The underscores are used in place of periods to keep the name of the AVD combined. Creating an AVD name as a single combined word helps when you’re working in advanced scenarios with AVDs via the command line. SKIN is the name of the skin of the emulator. Emulators can have various skins that make them look like actual devices. The default skin is provided by the Android SDK. The SCREENSIZE value is the size of the screen with regard to the Video Graphics Array (VGA) size. The default is WVGA800. Other options are QVGA and HVGA.

www.it-ebooks.info

Chapter 3: Your First Android Project

2. Click the New button.

The Create New Android Virtual Device (AVD) dialog box opens, as shown in Figure 3-8.



Figure 3-8: The Create New Android Virtual Device (AVD) dialog box.

3. For this AVD, in the Name field, type 4_1_Default_WVGA.

For more information on naming your AVDs, see the nearby sidebar “AVD nomenclature.”

4. In the Target box, select Android 4.1 — API Level 16.



5. In the SD Card section, leave the fields blank.

You have no use for an SD Card in the Hello Android application. You would use the SD Card option if you needed to save data to the SD card. If you want to have an emulator in the future, insert the size of the SD card in megabytes (MB) that you want to have created for you. At that time, an emulated SD Card will be created and dropped in your local file system.

6. Leave the Skin option set to Default (WVGA800).

www.it-ebooks.info

65

66

Part II: Building and Publishing Your First Android Application

7. Don’t select new features in the Hardware section.

The Hardware section outlines the hardware features your AVD should emulate. You don’t need extra hardware configuration for the Hello Android application.

8. Click the Create AVD button.

Figure 3-9 shows the completed AVD Manager dialog box.



Figure 3-9: The recently created AVD in the Android SDK and AVD Manager dialog box.

9. Close the Android SDK and AVD Manager dialog box. You may see this error message after you create your AVD: Android requires .class compatibility set to 5.0. Please fix project properties If so, you can fix it by right-clicking the project in Eclipse and choosing Android Tools➪Fix Project Properties from the context menu.

Creating Launch Configurations You’re almost at the point where you can run the application. A run configuration specifies the project to run, the activity to start, and the emulator or

www.it-ebooks.info

Chapter 3: Your First Android Project device to connect to. Whoa! That’s a lot of stuff happening quickly. Not to worry — the ADT can help you by automating many key steps so that you can get up and running quickly. The Android ADT gives you two options for creating launch configurations: ✓ Run configuration: You need to run your application on a given device. You’ll use run configurations most of the time during your Android development career. ✓ Debug configuration: You’re debugging your application while it’s running on a given device. You can find out how to debug in Chapter 5.

When you first run a project as an Android application by choosing Run➪Run, the ADT automatically creates a run configuration for you. The Android Application option is visible when you choose Run➪Run. After the run configuration is created, it’s the default run configuration, now used every time you choose Run➪Run. If you’re feeling ambitious and decide that you want to create a run configuration manually, follow along here. Don’t worry — following these steps is simple:



1. Choose Run➪Run Configurations.

The Run Configurations dialog box opens, as shown in Figure 3-10. In this dialog box, you can create many types of run configurations. The left side of the dialog box lists many types of configurations, but focus on these:

• Android Application



• Android JUnit Test



2. Select the Android Application item, and click the New Launch Configuration icon.

Or right-click Android Application and choose New from the context menu. The New Launch Configuration window opens.

3. Type ExampleConfiguration in the Name field. If you want to start from an existing launch configuration, right-click it, and choose Duplicate from the context menu. Change the name of the run configuration by entering a name in the Name field. You can then change various settings to give the launch configuration a unique configuration.

www.it-ebooks.info

67

68

Part II: Building and Publishing Your First Android Application



Figure 3-10: The Run Configurations dialog box.





4. On the Android tab, click the Browse button to select the project you’re creating this launch configuration for.

The Project Selection dialog box opens, as shown in Figure 3-11.



Figure 3-11: Selecting the project for the new launch configuration.



www.it-ebooks.info

Chapter 3: Your First Android Project

5. Select Hello Android and click OK.

The Run Configurations dialog box reopens.

6. On the Android tab, leave the Launch Action option set to Launch Default Activity.

In this case, the default activity is MainActivity, which you set up in “Starting a New Project in Eclipse,” earlier in this chapter.

7. On the Target tab, shown in Figure 3-12, leave Automatic selected.

Notice that an AVD is listed in the Select a Preferred Android Virtual Device for Deployment section.



Figure 3-12: A new, manually created launch configuration.

8. Select the 4_1_Default_WVGA device.

This device is the AVD you created earlier. By selecting it, you’re instructing this launch configuration to launch this AVD when a user runs the app by choosing Run➪Run. This view has both manual and automatic options. The manual option lets you choose which device to connect to when using this launch configuration. Automatic sets a predefined AVD to use when launching in the current launch configuration.

9. Leave the rest of the settings alone, and click the Apply button. When you have no need for a launch configuration, select it in the left panel and click the Delete button on the toolbar, or right-click it and choose Delete from the context menu.

www.it-ebooks.info

69

70

Part II: Building and Publishing Your First Android Application

Running the Hello Android App Understanding the basics of how to get an Android application up and running is a simple yet detailed process. You’re now ready to see your hard work in action. You’ve created a launch configuration and Android Virtual Device; now it’s time to get the application running. Finally!

Running the app in the emulator Running the application is simple. Upon your instruction, the ADT launches an emulator with the default launch configuration you build earlier in this chapter. Starting your application is as simple as choosing Run➪Run or pressing Ctrl+F11. Either action launches the application in an emulator using the default launch configuration — in this case, ExampleConfiguration. The ADT compiles your application and then deploys it to the emulator. If you didn’t create a launch configuration, you see the Run As dialog box, shown in Figure 3-13. Choose Android Application, and a launch configuration is created for you.



Figure 3-13: The Run As dialog box appears when a launch configuration isn’t set up.

If you created the ExampleConfiguration, you see the emulator loading, as shown in Figure 3-14.

www.it-ebooks.info

Chapter 3: Your First Android Project



Figure 3-14: The initial emulator in a loading state, with the port number the emulator is running under and the AVD name on the window’s title bar.



Help! If your emulator never loads and stays stuck on the ANDROID screen(s), there’s no need to worry, comrade. The first time the emulator starts, the emulator can take upward of ten minutes to finish loading, because you’re running a virtual Linux system in the emulator. The emulator has to boot up and initialize. The slower your computer, the slower the emulator is in its boot process. Figure 3-14 shows the emulator boot screen. The window’s title bar contains the port number that the emulator is running on your computer (5554) and the AVD name (4_1_Default_WVGA). The Android logo is the same one that users of the default Android operating system see when they boot their phones (if a device manufacturer hasn’t installed its own user interface customizations, as on the HTC Sense).

www.it-ebooks.info

71

72

Part II: Building and Publishing Your First Android Application The third and final screen you see is the loaded emulator, shown in Figure 3-15.



Save valuable time by leaving the emulator running. The emulator doesn’t have to be loaded every time you want to run your application. After the emulator is running, you can change your source code and then rerun your application. The ADT finds the running emulator and deploys your application to the emulator.

Figure 3-15: The loaded 4_1_ Default_ WVGA emulator.



www.it-ebooks.info

Chapter 3: Your First Android Project When the emulator completes its loading phase, the default locked Home screen appears, as shown in Figure 3-16. To unlock the Home screen, click and drag the Lock icon to the right side of the screen. When the icon reaches the far side of the Android screen, release the icon. During the drag, the icon’s background turns green and its label changes to Unlock.



Figure 3-16: Unlocking a locked Home screen.



www.it-ebooks.info

73

74

Part II: Building and Publishing Your First Android Application After the emulator is unlocked, the Home screen appears, as shown in Figure 3-17.



Figure 3-17: The emulator Home screen.

Immediately thereafter, the ADT starts the Hello Android application for you. You see an empty screen containing the words Hello world!, as shown in Figure 3-18. You’ve just created and started your first Android application.

www.it-ebooks.info

Chapter 3: Your First Android Project



Figure 3-18: The Hello Android application in the emulator.



If you don’t unlock the screen when the emulator starts, the ADT can’t start the application. If you unlock the Home screen and your application doesn’t start within five to ten seconds, simply run the application from Eclipse again by choosing Run➪Run. The application is redeployed to the device, and it starts running. You can view the status of the installation via the Console view in Eclipse, as shown in Figure 3-19.

www.it-ebooks.info

75

76

Part II: Building and Publishing Your First Android Application



Figure 3-19: The Console view in Eclipse allows you to view what’s happening behind the scenes while your app is deploying to a device.



Checking deployment status Inside Console view, you can see information regarding the state of your application deployment. Here’s the full text of that information: [2012-07-05 [2012-07-05 [2012-07-05 [2012-07-05 [2012-07-05 [2012-07-05 [2012-07-05 [2012-07-05

[2012-07-05

13:13:46 - Hello Android] -----------------------------13:13:46 - Hello Android] Android Launch! 13:13:46 - Hello Android] adb is running normally. 13:13:46 - Hello Android] Performing com.dummies.android. helloandroid.MainActivity activity launch 13:13:46 - Hello Android] Automatic Target Mode: using existing emulator ‘emulator-5554’ running compatible AVD ‘4_1_Default_WVGA’ 13:13:48 - Hello Android] Application already deployed. No need to reinstall. 13:13:48 - Hello Android] Starting activity com.dummies.android. helloandroid.MainActivity on device 13:13:49 - Hello Android] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category. LAUNCHER] cmp=com.dummies.android.helloandroid/.MainActivity } 13:13:49 - Hello Android] ActivityManager: Warning: Activity not started, its current task has been brought to the front

www.it-ebooks.info

Chapter 3: Your First Android Project

Console view provides valuable information on the state of the application deployment. It lets you know it’s launching an activity; shows which device the ADT is targeting; and shows warning information, as presented in the last line of Console view: [2012-07-05 13:13:49 - Hello Android] ActivityManager: Warning: Activity not started, its current task has been brought to the front

ADT informs you that the activity — MainActivity, in this case — hasn’t been started because it was already running. Because the activity was already running, ADT brought that task to the foreground (the Android screen) for you to see.

Understanding Project Structure You’ve created your first application. You even did it without coding. It’s nice that the ADT provides you with the tools to fire up a quick application, but that won’t help you create your next blockbuster application. The beginning of this chapter walks you through how to create a boilerplate Android application by using the New Android Project Wizard. The rest of this chapter shows you how to use the file structure that the Android wizard created for you. The following sections aren’t ones you should skim (they’re vital!), because you’ll spend your entire Android development time navigating these folders. Understanding what they’re for and how they got there is a key aspect of understanding Android development.

Navigating the app’s folders In Eclipse, the Package or Project Explorer expands the Hello Android project, as shown in Figure 3-20. After the Hello Android project is expanded, the list of subfolders includes ✓ src ✓ gen ✓ The Android version, such as Android 4.1 ✓ assets ✓ res

www.it-ebooks.info

77

78

Part II: Building and Publishing Your First Android Application



Figure 3-20: The Project Explorer with the Hello Android project folder structure expanded.

These folders aren’t the only ones you can have inside an Android project, but they’re the default folders created by the New Android Project Wizard. Other folders include bin, libs, and Android Dependencies. Two important files in the project are AndroidManifest.xml and project. properties. The AndroidManifest.xml file helps you identify the components that build and run the application, whereas the project. properties file helps you identify the default properties of the Android project (such as the Android version). The following sections discuss all these folders and files.

Source (src) folder The source folder — known as the src folder in Android projects — includes your stub MainActivity.java file, which you create in the New Android Project Wizard, earlier in this chapter. To inspect the contents of the src folder, you must expand it. Follow these steps:

1. Select the src folder, and click the small arrow to the left of the folder to expand it.

You see your project’s default package: com.dummies.android. helloandroid.

www.it-ebooks.info

Chapter 3: Your First Android Project

2. Select the default package, and expand it.

This step exposes the MainActivity.java file within the com. dummies.android.helloandroid package, as shown in Figure 3-21.

Figure 3-21: The src folder expanded and showing the stub

Main Activity .java file inside the default

com. dummies. android. hello android

Java package.





You aren’t limited to a single package in your Android applications. In fact, separating into packages the different pieces of core functionality in your Java classes is considered to be a best practice. An example is a class whose responsibility is to communicate with a web API via eXtensible Markup Language (XML). Also, your application might have Customer objects that represent a customer domain model, and those customers are retrieved via the web API classes. At this point, you might have two extra Java packages that contain the additional Java classes:

✓ com.dummies.android.helloandroid.models ✓ com.dummies.android.helloandroid.http These packages would contain their respective Java components. com. dummies.android.helloandroid.models would contain the domain model Java classes, and com.dummies.android.helloandroid.http would contain the HTTP-related Java classes (web APIs). Figure 3-22 shows an Android project set up this way.

www.it-ebooks.info

79

80

Part II: Building and Publishing Your First Android Application



Figure 3-22: Multiple packages under the src folder that contain their own respective Java classes.



Target Android Library folder The Target Android Library folder isn’t a folder per se, but it’s more along the lines of an item in Eclipse presented through the ADT. This item includes the android.jar file that your application builds against. The version of this file was determined by the build target that you chose in the New Android Project Wizard. Expanding the Android 4.1 item in the project exposes the android.jar file and the path to where it’s installed, as shown in Figure 3-23.

Figure 3-23: The Android 4.1 version of the

android. jar file

with its location.



www.it-ebooks.info

Chapter 3: Your First Android Project Assets (assets) folder The assets folder is empty by default. This folder is used to store raw asset files. A raw asset file can be one of many assets you may need for your application to work. A great example is a file that contains data in a proprietary format for consumption on the device. Android has the Asset Manager, which can return all assets in the assets directory. Upon reading an asset, your application can read the data in the file. If you create an application that has its own dictionary for word lookups (for autocomplete, perhaps), you may want to bundle the dictionary into the project by placing the dictionary file (usually, an XML or binary file such as a SQLite database) in the assets directory. Android treats assets as a raw approach to resource management. You aren’t limited in what you can place in the assets directory. Note, however, that working with assets can be a little more tedious than working with resources, because you’re required to work with streams of bytes and convert them to the objects you’re after — audio, video, or text, for example.

Assets don’t receive resource IDs like resources in the res directory. You have to work with bits, bytes, and streams manually to access the contents.

Resources (res) folder The res folder contains the various resources that your application can consume. Always externalize any resources that your application needs to consume. Classic examples of such resources include strings and images. As an example, you should avoid placing strings inside your code. Instead, create a string resource, and reference that resource from within code. (You find out how to do this later in this book.) These types of resources should be grouped in the res subdirectory that suits them best. You should also provide alternative resources for specific device configurations by grouping them in specifically named resource directories. At runtime, Android determines which configuration the application is running in and chooses the appropriate resource (or resource folder) to pull its resources from. You may want to provide a different user interface (UI) layout depending on the screen size or different strings depending on the language setting, for example. After you externalize your resources, you can access them in code via resource IDs that are generated by the ADT in the R class. (See “The mysterious gen folder,” later in this chapter.) You should place each resource in a specific subdirectory of your project’s res directory. Table 3-1 lists the subdirectories that are the most common types of resource folders under the parent res directory.

www.it-ebooks.info

81

82

Part II: Building and Publishing Your First Android Application Table 3-1

Supported Subdirectories of the res Directory

Directory

Resource Type

anim/

XML files that define animations.

color/

XML files that define a list of colors.

drawable/

Bitmap files (.png, .9.png, .jpg, .gif) or XML files that are compiled into the following drawable resources.

drawable-xhdpi/

Drawables for screens with extra-high resolution. The xhdpi qualifier stands for extra-high-density screens. This is the same as the drawable/ resource folder except that all bitmap or XML files stored here are compiled into extra-high-resolution drawable resources.

drawable-hdpi/

Drawables for high-resolution screens. The hdpi qualifier stands for high-density screens, the same as the drawable/ resource folder except that all bitmap or XML files stored here are compiled into high-resolution drawable resources.

drawable-ldpi/

Drawables for low-resolution screens. The ldpi qualifier stands for low-density screens. It’s the same as the drawable/ resource folder except that all bitmap or XML files stored here are compiled into low-resolution drawable resources.

drawable-mdpi/

Drawables for medium-resolution screens. The mdpi qualifier stands for medium-density screens. It’s the same as the drawable/ resource folder except that all bitmap or XML files stored here are compiled into medium-resolution drawable resources.

layout/

XML files that define a user interface layout.

menu/

XML files that represent application menus.

raw/

Arbitrary files to save in their raw form. Files in this directory aren’t compressed by the system.

values/

XML files that contain simple values, such as strings, integers, and colors. Whereas XML resource files in other res/ folders define a single resource based on the XML filenames, files in the values/ directory define multiple resources for various uses. You should follow a few filename conventions, outlined in the nearby sidebar “Naming resources in the values directory,” for the resources you can create in this directory.

www.it-ebooks.info

Chapter 3: Your First Android Project

Naming resources in the values directory You should follow a few filenaming conventions for the resources you can create in the values directory: ✓ arrays.xml for resource arrays (storing like items, such as strings or integers, together) ✓ colors.xml for resources that define color values; accessed via the R.color class



✓ dimens.xml for resources that define dimension values (20px equals 20 pixels, for example); accessed via the R.dimen class ✓ s t r i n g s . x m l for string values; accessed via the R.string class ✓ styles.xml for resources that represent styles; accessed via the R.style class. A style is similar to a cascading style sheet in HTML. You can define many styles and have them inherit from one another.

Never save resource files directly in the res directory. If you do, a compiler error occurs. The resources you save in the resource folders listed in Table 3-1 are known as default resources — they define the default design and layout of your Android application. Different types of Android-powered devices may need different resources, however. If you have a device with a larger-than-normal screen, for example, provide alternative layout resources to account for the difference. A discussion of the powerful resource mechanism inside Android could require its own chapter, but this book covers the basics to get you up and running. The resource mechanism can help with internationalization (enabling your app for different languages and countries), device size and density, and even resources for the mode that the phone may be in. To dive into the ocean of resources, review the “Providing Resources” section of the Dev Guide in the Android documentation, at http://d.android.com/ guide/topics/resources/providing-resources.html.

Bin, libs, and Referenced Libraries folders Library folders aren’t shown in your Hello Android application, but you should be aware of a couple of extra folders, one of which is the libs/ directory. It can contain private third-party libraries that perform a function for you. An example is jTwitter, a third-party Java library for the Twitter API. If you were to use jTwitter in your Android application, you’d place the jtwitter.jar library in the libs directory.

www.it-ebooks.info

83

84

Part II: Building and Publishing Your First Android Application After a library is placed in the libs directory, add it to your Java build path — the class path that’s used for building a Java project. If your project depends on another third-party or private library, Eclipse should know where to find that library, and setting the build path via Eclipse does exactly that. Assuming that you added jtwitter.jar to your libs directory, you can add it to your build path easily by right-clicking the jtwitter.jar file and choosing Build Path➪Add to Build Path from the context menu. It’s then listed in under the libs folder in Package Explorer, as shown in Figure 3-24.

You can find out more about jTwitter at www.winterwell.com/software/ jtwitter.php.

Figure 3-24: The libs folder with

jtwitter. jar. We don’t use the libs directory in this book, though developers commonly use third-party libraries in Android applications.

The mysterious gen folder Ah, you finally get to witness the magic that is the gen folder. When you create an Android application, before the first compilation, the gen folder doesn’t exist. Upon the first compilation, ADT generates the gen folder and its contents. The gen folder contains Java files generated by ADT. The ADT creates an R.java file. (We tell you more about that topic in a moment.) The gen folder contains items generated from the res directory. Without a proper understanding of what the res folder is and what it contains, you have no clue what the gen folder is for. But because you’re already an expert on the res folder, you can dive into the gen folder.

www.it-ebooks.info

Chapter 3: Your First Android Project When you write Java code in Android, you reach a point when you need to reference the items in the res folder. You do this by using the R class. The R.java file is an index to all resources defined in your res folder. You use this class as a shorthand way to reference resources you’ve included in your project. This is particularly useful with the code-completion features of Eclipse because you can quickly identify the proper resource via code completion. Expand the gen folder in the Hello Android project and the package name contained within the gen folder. Now open the R.java file by double-clicking it. You can see a Java class that contains nested Java classes. These nested Java classes have the same names as some of the res folders defined in the preceding res section. Under each of those subclasses, you can see members that have the same names as the resources in their respective res folders (excluding their file extensions). The Hello Android project’s R.java file should look similar to the following code: /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.dummies.android.helloandroid; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } Whoa — what’s all that 0x stuff? The ADT tool generates this code for you so that you don’t have to worry about what’s happening behind the scenes. As you add resources and the project is rebuilt, ADT regenerates the R.java file. This newly generated file contains members that reference your recently added resources.

www.it-ebooks.info

85

86

Part II: Building and Publishing Your First Android Application

You should never edit the R.java file by hand. If you do, your application may not compile, and then you’re in a world of hurt. If you accidentally edit the R.java file and can’t undo your changes, you can delete the gen folder and build your project. At this point, ADT regenerates the R.java file for you.

Viewing the application’s manifest file You keep track of everything you own and need through lists, don’t you? Well, that’s exactly what the Android manifest file does. It keeps track of everything your application needs, requests, and has to use to run. The Android manifest file is stored at the root of your project and is named AndroidManifest.xml. Every application must have an Android manifest file in its root directory. The application manifest file provides all essential information to the Android system — information that it must have before it can run any of your application’s code. The application manifest file also provides ✓ The name of your Java package for the application, which is the unique identifier for your application in the Android system as well as in the Google Play Store ✓ The components of the application, such as the activities and background services ✓ The declaration of the permissions your application requires to run ✓ The minimum level of the Android API that the application requires The Android manifest file declares the version of your application. You must version your application. How you version your application is similar to how the Android OS is versioned. It’s important to determine your application’s versioning strategy early in the development process, including considerations for future releases of your application. The versioning requirements are that each application has a version code and version name.

Version code The version code is an integer value that represents the version of the application code relative to other versions of your application. This value is used to help other applications determine their compatibility with your application. Also, the Google Play Store uses it as a basis for identifying the application internally and for handling updates.

www.it-ebooks.info

Chapter 3: Your First Android Project You can set the version code to any integer value you like, but you must make sure that each successive release has a version code greater than the previous one. Typically, on the first release, you set the version code to 1. Then you monotonically increase the value in a given order with each release, whether the release is major or minor. This means that the version code doesn’t have a strong resemblance to the application release version that’s visible to the user, which is the version name. (See the next section.) The version code typically isn’t displayed to users in applications. Upgrading your application code and releasing the app without incrementing the version code causes different code bases of your app to be released under the same version. Consider a scenario in which you release your application with version code 1. This is your first release. A user installs your application via the Google Play Store and notices a bug in your application, and she lets you know. You fix the bug in the code, recompile, and release the new code base without updating the version code in the Android manifest file. At this point, the Google Play Store doesn’t know that anything has changed because it’s inspecting your version code in the application manifest. If the version code had changed to a value greater than 1, such as 2, the Google Play Store would recognize that an update had been made and would inform users who installed the version-code 1 app that an update is available. If you didn’t update the version code, users would never get the update to your code base and would run a buggy app. No one likes that!

Version name The version name is a string value that represents the release version of the application code as it should be shown to users. The value is a string that can be anything, but it typically follows a common release-name nomenclature that describes the application version: .. An example of this release-name nomenclature is 2.1.4 or, without the value (4, in this case), 2.1. The Android system doesn’t use this value for any purpose other than to enable applications to display it to users.

The version name may be any other type of absolute or relative version identifier. The Foursquare application, for example, uses a version-naming scheme that corresponds to the date. An example of the version application name is 2012.05.02, which clearly represents a date. The version name is left up

www.it-ebooks.info

87

88

Part II: Building and Publishing Your First Android Application to you. You should plan ahead and make sure that your versioning strategy makes sense to you and your users.

Permissions Assume that your application needs to access the Internet to retrieve some data. Android restricts Internet access by default. For your application to have access to the Internet, you need to ask for it. In the application manifest file, you must define which permissions your application needs to operate. Table 3-2 lists some commonly requested permissions.

Table 3-2

Commonly Requested Application Permissions

Permission

What It Means

Internet

The application needs access to the Internet.

Write External Storage

The application needs to write data to the Secure Digital card (SD card).

Camera

The application needs access to the camera.

Access Fine Location

The application needs access to the global positioning system (GPS) location.

Read Phone State

The application needs to access the state of the phone (such as ringing).

Viewing the project.properties file The project.properties file is used in conjunction with ADT and Eclipse. It contains project settings such as the build target. This file is integral to the project, so don’t lose it. The project.properties file should never be edited manually. To edit the contents of the file, use the editor in Eclipse: Right-click the project name in the Package Explorer and choose Properties from the context menu. This action opens the Properties editor, shown in Figure 3-25. This editor allows you to change various properties of the project by selecting any of the options on the left. You can select the Android property and change the Android SDK, for example.

www.it-ebooks.info

Chapter 3: Your First Android Project



Figure 3-25: The Properties editor in Eclipse.



Closing Your Project When you’ve created your application, you need to close any files you have open in Eclipse before you start your next application. You can do this by closing each file individually or by right-clicking the files and choosing Close All from the shortcut menu. After you have closed all the files, you need to close the project itself. In Eclipse, in the Package Explorer, right-click the project and choose Close Project. By closing the project, you’re telling Eclipse that you currently don’t need to work with that project. This frees resources that Eclipse uses to track the project state, therefore speeding up your application.

www.it-ebooks.info

89

90

Part II: Building and Publishing Your First Android Application

www.it-ebooks.info

Chapter 4

Designing the User Interface In This Chapter ▶ Setting up the Silent Mode Toggle application ▶ Designing the layout ▶ Developing the user interface ▶ Adding an image and a button widget ▶ Making a launcher icon ▶ Previewing your work

I

n Chapter 3, you discover what Android is and how to build your first application. This chapter helps you delve into the fun stuff: building a real application and publishing it to the Google Play Store. The application you build in this chapter allows the user to toggle the ringer mode on the phone by simply pressing a button. This application seems simple, but it solves a real-world problem. Imagine that you’re at work and you’re about to go to a meeting. You can turn down the volume on your phone to silence it and then attend the meeting. (You wouldn’t want to be the one whose phone always rings during a meeting, would you?) The problem is that you like your ringer loud, but not too loud, so you use only the second-to-loudest setting. When you leave your meeting, you remember to restore the ringer volume, but you always have to move all the way to the maximum volume and then down one setting, to ensure that you have the correct one. Though this event isn’t life changing, it’s a nuisance to complete every time you need to silence your phone’s ringer. If an application would allow you to tap a button to turn off the ringer and then, when you leave the meeting, tap the button again to restore the ringer to the last state it was in, you would never have to readjust it again. That’s the application you’re about to build.

www.it-ebooks.info

92

Part II: Building and Publishing Your First Android Application

Creating the Silent Mode Toggle Application Create the new application by choosing File➪New Project. Choose Android Project from the list, and then click the Next button. Use Table 4-1 for your project settings.

Table 4-1

Project Settings for Silent Mode Toggle

Setting

Value

Application Name

Silent Mode Toggle

Project name

Silent Mode Toggle

Contents

Leave the default selected (create new project in workspace)

Build target

Android 4.1

Package name

com.dummies.android.silentmodetoggle

Create activity

MainActivity

Min SDK Version

8 (2.2)

Click the Finish button. You should now have the Silent Mode Toggle application in your Package Explorer, as shown in Figure 4-1. If you receive an error that looks similar to this — “The project cannot be built until build path errors are resolved” — you can resolve it by right-clicking the project and choosing Android Tools➪Fix Project Properties. This realigns your project with the IDE workspace.



Figure 4-1: The Silent Mode Toggle application in Eclipse.



www.it-ebooks.info

Chapter 4: Designing the User Interface

Notice how you set the build target to 4.1 and the minimum SDK to 2.2 (API level 8). What you have done is told Android that your code can run on any device that runs at least version code 8 (Android 2.2). If you were to change this to version code 16, you would be saying that your app can run on any device running version 16 (Android 4.1) or higher. When creating a new application, you should decide whether you want it to run on older versions.

If you need a refresher on how to create a new Android app in Eclipse, see Chapter 3.

Laying Out the Application When you have the Silent Mode Toggle application created inside Eclipse, it’s time for you to design the application’s user interface, the part of an application where users interact with the app. This area of your application should be as snappy as possible. Your application will have a single button centered in the middle of the screen to toggle silent mode. Directly above the button, an image will provide visual feedback to let the user know whether the phone is in silent mode or normal ringer mode. Figures 4-2 and 4-3 show what the finished application will look like.



Figure 4-2: The Silent Mode Toggle application in normal ringer mode.



www.it-ebooks.info

93

94

Part II: Building and Publishing Your First Android Application



Figure 4-3: The Silent Mode Toggle application in silent ringer mode.



Using the XML layout file All layout files for an application are stored in the res/layouts directory of the Android project in Eclipse. When you create the Silent Mode Toggle application, the Android Development Tools (ADT) creates a file named activity_ main.xml in the res/layouts directory. This default layout file is the one the ADT creates for you when you create a new application. Double-click the file, click the activity_main.xml tab at the bottom of the screen, and you see some XML in the Eclipse editor window, as shown in Figure 4-4. Figure 4-4 shows a simple layout in which a text value is in the middle of the screen. Your code should look like this:

www.it-ebooks.info

Chapter 4: Designing the User Interface

Figure 4-4: The

activity_ main. xml layout file opened in Eclipse.



This XML file defines exactly what the view should look like. The following sections break down this file, element by element.

Default XML declaration The first element in the XML file provides the default XML declaration, letting text editors such as Eclipse and platforms such as Android know what type of file it is:

Layout type The next element in the XML file defines the layout type. In this case, you’re working with RelativeLayout, where children can be arranged relative to one another. RelativeLayout is a container for other items that show up onscreen:

www.it-ebooks.info

95

96

Part II: Building and Publishing Your First Android Application

The closing
tag isn’t showing because this tag is a container for other items. The close tag is inserted after all view items have been added to the container. See Table 4-2, later in this chapter, for more information about layout types — RelativeLayout or otherwise.

Views RelativeLayout can hold views, which are the basic building blocks of user interface components. The following code shows TextView, which is responsible for displaying text to the screen:

A view occupies a rectangular space on the screen and is responsible for drawing and event handling. All items that can show up on a device screen are views. The View class is the superclass that all items inherit from in Android. At the end of the XML file, you have the closing tag for the RelativeLayout. This line closes the container: The following section describes the forest that’s filled with different types of layouts.

Using the Android SDK layout tools When you create a user interface, you sometimes have to lay out components relative to each other or in a table or, under certain circumstances, even using absolute positioning. Thankfully, the engineering geniuses at Google who created Android thought of all this and provided the necessary tools to

www.it-ebooks.info

Chapter 4: Designing the User Interface create those types of layouts. Table 4-2 briefly introduces the common types of layouts available in the Android Software Development Kit (SDK).

Table 4-2

Android SDK Layouts

Layout

What It Does

LinearLayout

Arranges its children in a single row or column.

RelativeLayout

Lets the positions of the children be described in relation to each other or to the parent.

FrameLayout

Designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the upper-left area of the screen. Children are drawn in a stack, with the most recently added child at the top of the stack. This layout is commonly used as a way to lay out views in an absolute position.

GridLayout

Arranges its children into a grid.

Other, different types of layout tools exist, such as a TabHost for creating tabs and Sliding Drawer for finger-swiping motions that hide and display views. Programmers tend to use these layout tools in special-case scenarios. The items in Table 4-2 outline the most commonly used layouts.

Using the visual designer Good news: Eclipse has a visual designer. Bad news: The designer is limited in what it can do (as are all visual designers).

Opening the visual designer To view the visual designer, with the activity_main.xml file open in the Eclipse editor, click the Graphical Layout button, as shown in Figure 4-5.

www.it-ebooks.info

97

98

Part II: Building and Publishing Your First Android Application

Figure 4-5: The Graphical Layout button, which shows the visual designer.



The visual designer is now onscreen, as shown in Figure 4-6. From here, you can drag and drop items from the Layouts or Views toolboxes.

Inspecting a view’s properties Using the visual designer, you can view the properties of a given view by simply clicking it. Most likely, your Properties window is hidden. To look at properties, follow these steps:

1. Choose Window➪Show View➪Other.



2. Expand General and choose Properties.

The Properties view opens in Eclipse, as shown in Figure 4-7.

3. Select the “Hello world” view in the visual designer.

The view has a blue border, and the properties show up in the Properties window below it.

4. Scroll the list of properties to determine which elements can be changed in the view.

www.it-ebooks.info

Chapter 4: Designing the User Interface



Figure 4-6: The visual designer.





If you’re unsure which properties a view has, open the visual designer, click the Properties tab, and quickly inspect the Properties view to see what the view has to offer. If the Properties tab isn’t visible, enable it by choosing Window➪Show View➪Other➪General➪Properties.



A view’s available properties can change depending on its parent layout. For example, a TextView inside a LinearLayout has a different set of properties (for layout) than when it’s inside a RelativeLayout. The visual designer works well for simple scenarios where the contents are static in nature. But what happens when you need to draw items on the screen dynamically based on user input? The designer cannot help you in this scenario — it’s best suited for a static content scenario, where you create your layout once and it doesn’t update dynamically. The text of TextViews or images might change, but the actual layout of the views inside the layout doesn’t change.

www.it-ebooks.info

99

100

Part II: Building and Publishing Your First Android Application

Figure 4-7: A selected item in the visual designer, with some properties listed in the Properties window.





Developing the User Interface Okay, it’s time to start developing the user interface. First make sure that you’re in XML view of your layout by clicking the activity_main.xml tab. When you’re in XML view, delete the XML and replace it with the following. Your layout should now look like this:

www.it-ebooks.info

Chapter 4: Designing the User Interface

Viewing XML layout attributes Before continuing, you need to understand the attributes of the Android layout XML you’re working with. See Table 4-3.

Table 4-3

XML Layout Attributes

Layout

What It Does

xmlns:android=”...”

Defines the XML namespace that you use to reference part of the Android SDK

android:orientation= ”vertical”

Informs Android that this view will be laid out vertically, such as in the portrait format in printing

android:layout_width= ”match_parent”

Informs the view that it should fill as much horizontal space as it can, up to its parent, to make its own width the same as its parent’s

android:layout_height= ”match_parent”

Informs the view that it should fill as much vertical space as it can, up to its parent, to make its own height the same as its parent’s

At this point, you have defined the layout to fill the entire screen by setting the width and height to “match_parent”.

Working with views As stated earlier in this chapter, views in Android are the basic building blocks of user interface components. Anytime you implement a user interface component, such as a Layout or TextView, in the Android system, you’re using a view. When you work with views in Java, you have to cast them to their appropriate type to be able to work with them.

Setting layout_width and layout_height values Before a view can be presented to the screen, a couple of settings must be configured on the view so that Android knows how to layout the view on the screen. The attributes that are required, layout_width and layout_ height, are known as LayoutParams in the Android SDK.

www.it-ebooks.info

101

102

Part II: Building and Publishing Your First Android Application The layout_width attribute specifies the given width of a view, and the layout_height attribute specifies the given height of a view.

Setting match_parent and wrap_content values The layout_width and layout_height attributes can take any pixel value or density-independent pixel value to specify their respective dimensions. However, two of the most common values for layout_width and layout_ height are match_parent and wrap_content constants. The match_parent value informs the Android system to fill as much space as possible on screen based on the available space of the parent layout. The wrap_content value informs the Android system to occupy only as much space as needed to show the view. As the view’s contents grow, as would happen with a TextView, the view’s viewable space grows, similar to the Autosize property in Windows forms development. If you’re using a static layout, these two attributes must be set in the XML layout. If you’re creating views dynamically via code, the layout parameters must be set via Java code. Either way, you cannot be without them. To find out more about dynamic creation of views, see the API samples that come with the Android SDK. If you forget to provide values for layout_width or layout_height, your Android application will crash when rendering the view. Thankfully, you find out quickly when you test your application. Before Android 2.2, match_parent was named fill_parent (though its meaning remains the same). If you plan to support Android devices in versions earlier than 2.2, you need to use fill_parent instead of match_ parent.

Adding an Image to Your Application Although looking at text is fun, the truly interesting components are added via input mechanisms and images. The following sections demonstrate how to include images in your application — it’s time to put some stuff on the screen!

Placing an image onscreen The first element to add to the screen is the phone image (refer to Figures 4-2 and 4-3), so first you need the phone image, of course. You can download an image from this book’s source code, available from this book’s website, or you can use your own.

www.it-ebooks.info

Chapter 4: Designing the User Interface

Why you should worry about density folders Android supports various screen sizes and densities. Elsewhere in this chapter, we mention placing an image in the mdpi folder, which is for medium-density devices. What about smalland large-density devices? If Android cannot find the requested resource in the desired density, it opts for a density of the resource it can find. If your device has a high-density screen, the image is stretched out and most likely

quite pixilated. If your device has a low-density device, the image is compressed to fit within the screen dimensions. To avoid this problem, create multiple versions of your image to target multiple screen densities. For more information, see the Supporting Multiple Screens page in the Android documentation at http:// developer.android.com/guide/ practices/screens_support.html.

Adding images to a project is simple: Drag them from the folder where they’re stored to the res/drawable-mdpi folder, as shown in Figure 4-8. For the Silent Mode Toggle application, you need two phone images: normal and silent. Be sure to put both images in the res/drawable-mdpi folder.

Figure 4-8: Dragging the image file into the res/

drawablemdpi folder.





www.it-ebooks.info

103

104

Part II: Building and Publishing Your First Android Application To follow along in the rest of the chapter, be sure that the images are named this way: ✓ Normal mode image: phone_on.png ✓ Silent mode image: phone_silent.png If your images aren’t named correctly, you can rename them now. Your Eclipse project should then look like the one shown in Figure 4-9.



Figure 4-9: The Silent Mode Toggle project, with phone images.



When you drag images into Eclipse, the ADT recognizes that the project file structure has changed. The ADT then rebuilds the project because the Build Automatically selection is enabled on the Project menu. The gen folder, where the R.java file resides, regenerates, and the R.java file then includes a reference to the two new images you added. You can use the references to these resources to add images to your layout in code or in XML definition. You declare them in the XML layout in the following section.

www.it-ebooks.info

Chapter 4: Designing the User Interface

Adding the image to the layout To add an image to the layout, type the following into the activity_main. xml file, overwriting the current content of the file:

This code adds the ImageView inside the LinearLayout. An ImageView allows you to project an image to the screen on the device.

Setting image properties The ImageView contains a couple of extra parameters: ✓ The android:id=”@+id/phone_icon” property: The id attribute defines the unique identifier for the view in the Android system. You can find an in-depth explanation of the android:id value nomenclature at http://developer.android.com/guide/topics/ui/declaringlayout.html. ✓ The layout_gravity property: This property defines how to place the view (both its x- and y-axes) with its parent. In this example, the value is defined as the center_horizontal constant. This value instructs the Android system to place the object in the horizontal center of its container, not changing its size. You can use many other constants, such as center_vertical, top, bottom, left, right, and many more. See the LinearLayout.LayoutParams Android documentation for a full list. ✓ The android:src=”@drawable/phone_on” property: This property is a direct child of the ImageView class. You use this property to set the image that you want to show up on the screen.

www.it-ebooks.info

105

106

Part II: Building and Publishing Your First Android Application Notice the value of the src property — “@drawable/phone_on”. What you’re seeing is the use of the R.java file. You can reference drawable resources via XML by typing the at symbol (@) and the resource you want. Certain Android attributes begin with the layout_ prefix — android: layout_width, android:layout_height, android:layout_gravity are all examples. The layout_ convention tells you that the attribute relates to the view’s parent. Attributes that don’t begin with layout_ pertain to the view itself. So the ImageView’s android:src attribute tells the ImageView which image to use, but its android:layout_gravity tells the ImageView’s parent (the LinearLayout, in this case) to lay out the ImageView in the center of the parent.

Setting drawable resources You don’t type @drawable-mdpi for the drawable resource identifier, @drawable, because it’s Android’s job (not yours) to support multiple screen sizes. The Android layout system knows only about drawables — it knows nothing of low-, medium-, high-, or extra high density drawables during design time. At runtime, Android determines whether and when it can use low-, medium-, or high-density drawables. For example, if the app is running on a high-density device and the requested drawable resource is available in the drawable-hdpi folder, Android uses that resource. Otherwise, it uses the closest match it can find. Support for various screen sizes and densities is a broad topic (and complex, in some aspects). For an in-depth view into this subject, read the “Managing Multiple Screen Sizes” article in the Android documentation at http://developer. android.com/guide/practices/screens_support.html. The phone_on portion identifies the drawable you want to use. The image filename is phone_on.png. To stay within Java’s member-naming guidelines, however, the file extension is removed, leaving phone_on. If you were to open the R.java file in the gen folder, you would see a member variable with the name phone_on, not phone_on.png. Thanks to the ADT, you can see your available options for this property via code completion. Place the cursor directly after @drawable/ in the src property of the ImageView in the Eclipse editor, and press Ctrl+spacebar. The code completion window opens, as shown in Figure 4-10. The other resource names in the window are other options you could choose for the src portion of the drawable definition.

www.it-ebooks.info

Chapter 4: Designing the User Interface



Figure 4-10: Code completion, with resources.



Creating a Launcher Icon for the Application When your app is installed, its icon helps users identify its presence in the application launcher. When you create the Silent Mode Toggle application, the ADT automatically includes a default launcher icon, as shown on the left in Figure 4-11. You should change this somewhat bland icon to one of your own. A round phone icon works for the Silent Mode Toggle application, as shown on the right in Figure 4-11. You can create your own (as shown in the following section) or use the one from the downloaded source code from this book’s website.



Figure 4-11: The default icon (left) and a unique icon (right).



www.it-ebooks.info

107

108

Part II: Building and Publishing Your First Android Application

Designing a custom launcher icon Creating your own launcher icons is fairly easy, thanks to the Android project. The article “Icon Design Guidelines” in the Android documentation covers all aspects of icon design — a how-to manual for creating icons for the Android platform, a style guide, a list of do’s and don’ts, materials and colors, size and positioning guidelines, and (best of all) icon templates that you can use. You can find useful resources for designing icons at http://d. android.com/guide/practices/ui_guidelines/icon_design.html and http://d.android.com/design/style/iconography.html.

Working with templates After you download the Android SDK, these icon templates and materials are available for you to use immediately on your computer’s hard drive. Navigate to your Android SDK installation directory (see Chapter 2), and from there navigate to the docs/shareables directory. You’ll find various .zip files that contain templates and samples. Open the templates in the image-editing program of your choice, and follow the design guidelines in the documentation to create your next rockin’ icon set.

Matching icon sizes with screen densities Because every screen density requires an icon in a different size, you, as the designer, need to know how large the icon should be. Each density must have its own icon size to look appropriate (no pixilation, stretching, or compressing) on the screen. Table 4-4 summarizes the finished icon sizes for each of the three generalized screen densities.

Table 4-4

Finished Icon Sizes

Screen Density

Icon Size in Pixels

Low-density screen (ldpi)

36 x 36

Medium-density screen (mdpi)

48 x 48

High-density screen (hdpi)

72 x 72

Extra-high-density screen (xhdpi)

96 x 96

www.it-ebooks.info

Chapter 4: Designing the User Interface

Adding a custom launcher icon To place your custom launcher icon into the project, follow these steps:

1. Rename the image icon to ic_launcher.png.



2. Drag your icon into the drawable-mdpi folder.

Eclipse asks whether you want to overwrite the existing ic_launcher. png.

3. Click Yes.

The ic_launcher.png file is now in the drawable-mdpi folder. You’re not done yet! For the ldpi, hdpi and xhdpi folders, you need a low-, high-, and extra high density version of the icon. Copy the respective icons into the ldpi, hdpi, and xhdpi folders. If you don’t copy the icons of other densities into their respective folders, users who have a low- or high-density device receive the default launcher icon (refer to Figure 4-11), whereas the medium-density devices receive the new icon that you included in the project. You dragged the file into the drawable-mdpi folder — what gives? Each of the other folders contains its own version of the icon. Open the drawablehdpi, drawable-xhdpi, and drawable-ldpi folders in your Eclipse project, and you can see that each density has its own ic_launcher.png file. Be sure to place the correct icon in each density-specific folder.

Adding a Toggle Button View Android devices come fully equipped with various views that include buttons, check boxes, and text-entry fields so that you can quickly build your user interface. Some views are more complex, such as a date picker, a clock, and zoom controls. Views also provide user interface events that inform you when a user has interacted with the particular view, such as tapping a button. You need to add a button view to your application so that you can toggle silent mode on the phone.

www.it-ebooks.info

109

110

Part II: Building and Publishing Your First Android Application To add a button to your layout, type the following code after ImageView:

© Copyright 2013 - 2019 AZDOC.PL All rights reserved.