Introduction to Android™

App Development for the Kindle Fire™

Lauren Darcey

Shane Conder

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

Android™ is a trademark of Google, Inc. Kindle Fire™ is a trademark of Amazon.com, Inc.

Android™ and Google® are trademarks of Google, Inc. Kindle Fire™ and Amazon.com® are trademarks of Amazon.com, Inc. Neither Amazon.com, Inc., nor Google, Inc., have authorized or approved publication of this work and references to their marks herein are not intended to imply their sponsorship or affiliation with this work.

Visit us on the web: informit.com/aw

Copyright © 2012 Lauren Darcey and Shane Conder

All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.

ISBN-13: 978-0-133-04047-0

ISBN-10: 0-133-04047-X

First publication: April 2012

Acquisitions Editor

Laura Lewin

Senior Development Editor

Chris Zahn

Managing Editor

Kristy Hart

Project Editor

Jovana San Nicolas-Shirley

Copy Editor

Sheri Cain

Technical Reviewer

Ray Rischpater

Publishing Coordinator

Olivia Basegio

For Ellie

Table of Contents

Preface

Chapter 1: Getting Started with Kindle Fire

Chapter 2: Mastering the Android Development Tools

Chapter 3: Building Kindle Fire Applications

Chapter 4: Managing Application Resources

Chapter 5: Configuring the Android Manifest File

Chapter 6: Designing an Application Framework

Preface

Key Features of This Book

This mini-book covers Android Fundamentals for Kindle Fire application development. Here, you are introduced to Android, become familiar with the Android SDK and tools, install the development tools, and write your first Android application and deploy it to a Kindle Fire device. You are also introduced to the design principles necessary to write Android applications, including how Android applications are structured and configured, as well as how to incorporate application resources, such as strings, graphics, and user interface components, into your projects.

If you like this mini-book, we recommend continuing with the full version of the text, which provides a full hands-on tutorial for developing a real Kindle Fire application from start to finish. The full edition of this book is available in print and as an e-book.

Target Audience for This Book

There’s no reason anyone with an Android device, a good idea for a mobile application, and some programming knowledge couldn’t put this book to use for fun and profit. Whether you’re a programmer looking to break into mobile technology or an entrepreneur with a cool app idea, this book can help you realize your goals of making killer Android apps.

We make as few assumptions about you, as a reader of this book, as possible. No wireless development experience is necessary. We do assume that you’re somewhat comfortable installing applications on a computer (for example, Eclipse, the Java JDK, and the Android SDK) and tools and drivers (for USB access to a phone). We also assume that you own at least one Android device and can navigate your way around it for testing purposes.

Android apps are written in Java. Therefore, we assume you have a reasonably solid understanding of the Java programming language (classes, methods, scoping, OOP, and so on), ideally using the Eclipse development environment. Familiarity with common Java packages, such as java.lang, java.net, and java.util, will serve you well.

Android can also be a fantastic platform for learning Java, provided you have some background in object-oriented programming and adequate support, such as a professor or some really good Java programming references. We have made every attempt to avoid using any fancy or confusing Java in this book, but you will find that with Android, certain syntactical Java wizardry not often covered in your typical beginner’s Java book is used frequently: anonymous inner classes, method chaining, templates, reflection, and so on. With patience, and some good Java references, even beginning Java developers should be able to make it through this book alive; those with a solid understanding of Java should be able to take this book and run with it without issue.

Finally, regardless of your specific skill set, we expect you to use this book in conjunction with other supplementary resources, specifically the Android SDK reference and the sample source code that accompanies each coding chapter. The Android SDK reference provides exhaustive documentation about each package, class, and method of the Android SDK. It’s searchable online. If we were to duplicate this data in book form, this book would weigh a ton, literally.

Development Environment Used In This Book

The code in this book was written and tested using the following development environments:

• Windows 7 and Mac OS X 10.6.7.

• Eclipse Java IDE Version 3.7 (Indigo).

• Android ADT plug-in for Eclipse, 16.0.1.

• Android SDK Tools, Release 16.

• Sun Java SE Development Kit (JDK) 6 Update 21.

• Code examples target Android SDK API Level 10.

• The code was tested on the original Android Kindle Fire (Android SDK 2.3.4, API Level 10).

Code Examples for This Book

This source code is also available for download on the publisher website (http://www.informit.com/title/9780133040470) and on the authors’ website (http://androidbook.blogspot.com/p/book-code-downloads.html).

We provide complete, functional code projects for each coding chapter in this book. If you have trouble building the tutorial application as you go along, compare your work to the sample code for that chapter. The sample code is not intended to be the “answer,” but it is the complete code listings that could not otherwise be reproduced in a book of this length.

What Is (and Isn’t) in This Book

First and foremost, this book provides a thorough introduction to the Android platform for Kindle Fire application development. In this mini-book, we begin with the fundamentals, try to cover the most important aspects of development, and provide information on where to go for more information. This is not an exhaustive reference on the Android SDK. We assume that you will use this book as a companion to the Android SDK documentation, available for download as part of the SDK and online at http://developer.android.com.

We only have six chapters to get you, the reader, up to speed on the fundamentals of Android development, so forgive us if we stay strictly to the topic at hand. Therefore, we take the prerequisites listed earlier seriously. This book will not teach you how to program, explain Java syntax and programming techniques, or stray too far into the details of supporting technologies often used by mobile applications, like algorithm design, network protocols, developing web servers, graphic design, database schema design, and other such peripheral topics; there are fantastic references available on each of these subjects.

The Android SDK and related tools are updated frequently (every few months). This means that no matter how we try, some minor changes in step-by-step instructions may occur if you choose to use versions of the tools that do not match those listed in the previous section, “Development Environment Used In This Book.” This book is written for Kindle Fire app developers, so it focuses on the Android SDK version used by this specific device.

Supplementary Tools Available

Shane Conder and Lauren Darcey run a blog at http://androidbook.blogspot.com, where you can always download the latest source code for their books. This website also covers a variety of Android topics as well as reader discussions, questions, clarifications, the occasional exercise walk-through, and lots of other information about Android development. You can also find links to their various technical articles online and in print.

Contacting the Authors

Feel free to contact us if you have specific questions; we often post addendum information or tool-change information on our book’s website, http://androidbook.blogspot.com. You can email us at androidwirelessdev+kf1@gmail.com.

Acknowledgments

This book would never have been written without the guidance and encouragement we received from a number of patient and supportive people, including our editorial team, co-workers, friends, and family. Throughout this project, our editorial team at Pearson (Sams Publishing) has been top notch. Special thanks go to Trina MacDonald, Olivia Basegio, and our development editor Chris Zahn. Our technical reviewer, Ray Rischpater, helped us ensure that this book provides accurate information.

Thanks go out to past reviewers of our other books, technical editors, and readers for their valuable feedback. Finally, we’d like to thank our friends and family members who were patient and supportive when we needed to make our book deadlines, especially our daughter, Ellie, who has been more patient than we would reasonably expect any 2-month old to be.

About the Authors

Lauren Darcey is responsible for the technical leadership and direction of a small software company specializing in mobile technologies, including Android, Apple iOS, Blackberry, Palm Pre, BREW, and J2ME and consulting services. With more than two decades of experience in professional software production, Lauren is a recognized authority in application architecture and the development of commercial-grade mobile applications. Lauren received a B.S. in Computer Science from the University of California, Santa Cruz.

Lauren spends her free time traveling the world with her geeky mobile-minded husband and daughter. She is an avid nature photographer. Her work has been published in books and newspapers around the world. In South Africa, she dove with 4-meter-long great white sharks and got stuck between a herd of rampaging hippopotami and an irritated bull elephant. She’s been attacked by monkeys in Japan, gotten stuck in a ravine with two hungry lions in Kenya, gotten thirsty in Egypt, narrowly avoided a coup d’état in Thailand, geocached her way through the Swiss Alps, drank her way through the beer halls of Germany, slept in the crumbling castles of Europe, and gotten her tongue stuck to an iceberg in Iceland (while being watched by a herd of suspicious wild reindeer).

Shane Conder has extensive development experience and has focused his attention on mobile and embedded development for the past decade. He has designed and developed many commercial applications for Android, iOS, BREW, Blackberry, J2ME, Palm, and Windows Mobile—some of which have been installed on millions of phones worldwide. Shane has written extensively about the mobile industry and evaluated mobile-development platforms on his tech blogs and is well-known within the blogosphere. Shane received a B.S. in Computer Science from the University of California.

A self-admitted gadget freak, Shane always has the latest smartphone, tablet, or other mobile device. He can often be found fiddling with the latest technologies, such as cloud services and mobile platforms, and other exciting, state-of-the-art technologies that activate the creative part of his brain. He is a very hands-on geek dad. He also enjoys traveling the world with his geeky wife, even if she did make him dive with 4-meter-long great white sharks and almost get eaten by a lion in Kenya. He admits that he has to take at least two phones with him when backpacking—even though there is no coverage—and that he snickered and whipped out his Android phone to take a picture when Laurie got her tongue stuck to that iceberg in Iceland, and that he is catching on that he should be writing his own bio.

The authors have published several other Android books, including Android Wireless Application Development, Android Wireless Application Development Volume I: Android Essentials, Android Wireless Application Development Volume 2: Advanced Topics, Sams Teach Yourself Android Application Development, and the mini-book Introducing Android Development with Ice Cream Sandwich. Lauren and Shane have also published numerous articles on mobile-software development for magazines, technical journals, and online publishers of educational content. You can find dozens of samples of their work in Linux User and Developer, Smart Developer magazine (Linux New Media), developer.com, Network World, Envato (MobileTuts+ and CodeCanyon), and InformIT, among others. They also publish articles of interest to their readers at their own Android website: http://androidbook.blogspot.com. You can find a full list of the authors’ publications at http://goo.gl/f0Vlj.

1. Getting Started with Kindle Fire

Android is the first complete, open, and free mobile platform. Developers enjoy a comprehensive Software Development Kit (SDK), with ample tools for developing powerful, feature-rich applications. The platform is open source, relying on tried-and-true open standards with which developers will be familiar. Best of all, there are no costly barriers to entry for developers: no required fees. (A modest fee is required to publish on third-party distribution mechanisms, such as the Android Market.) Android developers have numerous options for distributing and commercializing their applications.

Introducing Android

To understand where Android fits in with other mobile technologies, let’s first talk about how and why this platform came about.

Google and the Open Handset Alliance

In 2007, a group of handset manufacturers, wireless carriers, and software developers (notably, Google) formed the Open Handset Alliance, with the goal of developing the next generation of wireless platform. Unlike existing platforms, this new platform would be nonproprietary and based on open standards, which would lead to lower development costs and increased profits. Mobile software developers would also have unprecedented access to the handset features, allowing for greater innovation.

As proprietary platforms, such as RIM BlackBerry and Apple iPhone, gained traction, the mobile-development community eagerly listened for news of this potential game-changing platform.

Android Makes Its Entrance

In 2007, the Open Handset Alliance announced the Android platform and launched a beta program for developers. Android went through the typical revisions of a new platform. Several prerelease revisions of the Android Software Development Kit (SDK) were released. The first Android handset (T-Mobile G1) began shipping in late 2008. Throughout 2009 and 2010, new and exciting Android smartphones reached markets throughout the world, and the platform proved itself to industry and consumers alike. Over the last three years, numerous revisions to the Android platform have been rolled out, each providing compelling features for developers to leverage and users to enjoy. Recently, mobile platforms have begun to consider devices above and beyond the traditional smartphone paradigm, to other devices, like tablets, e-book readers, and set-top boxes (like Google TV).

As of this writing, hundreds of Android devices are available to consumers around the world—from high-end smartphones to low-end “free with contract” handsets and everything in between. This figure does not include the numerous Android tablet and e-book readers also available, nor the dozens of upcoming devices already announced, nor the consumer electronics running Android. (For a nice list of Android devices, check out this Wikipedia link: http://goo.gl/fU2X5.) There are more than 200,000 applications currently published on the Android Market. In the United States, all major carriers now prominently carry Android phones in their product lines, as do many in Asia, Europe, Central/South America, and beyond. The rate of new Android devices reaching the world markets has continued to increase.

Google has been a contributing member of the Open Handset Alliance from the beginning. The company hosts the Android open source project and the developer website at http://developer.android.com. This website is your go-to site for downloading the Android SDK, getting the latest platform documentation, and browsing the Android developer forums. Google also runs the most popular service for selling Android applications to end users: the Android Market. The Android mascot is the little green robot shown in Figure 1.1.

Figure 1.1. The Android Mascot (Bugdroid)

Cheap and Easy Development

If there’s one time when “cheap and easy” is a benefit, it’s with mobile development. Wireless application development, with its ridiculously expensive compilers and preferential developer programs, has been notoriously expensive to break into compared to desktop development. Here, Android breaks the proprietary mold. Unlike with other mobile platforms, there are virtually no costs to developing Android applications.

The Android SDK and tools are freely available on the Android developer website (http://developer.android.com ([http://goo.gl/K8GgD]). The freely available Eclipse program has become the most popular integrated development environment (IDE) for Android application development; there is a powerful plug-in available on the Android developer site for facilitating Android development with Eclipse.

So, we’ve covered cheap; now let’s talk about why Android development is easy. Android applications are written in Java, which is one of the most popular development languages around. Java developers will be familiar with many of the packages provided as part of the Android SDK, such as java.net. Experienced Java developers will be pleased to find that the learning curve for Android is reasonable.

This book focuses on the most common, popular, and simple setup for developing Android applications:

• We use the most common and supported development language: Java. Although we do not teach Java, we try our best to keep the Java code simple and straightforward, so that even beginners won’t be wrestling with syntax. Even so, if you are new to Java, we recommend reading Sams Teach Yourself Java in 24 Hours by Rogers Cadenhead and Thinking in Java, Fourth Edition in Print, by Bruce Eckel. (The third edition is free at http://goo.gl/mtjoz, provided in a zip file from Bruce Eckel’s website at http://www.mindviewinc.com/Books/.)

• We use the most popular development environment: Eclipse. It’s free, it’s well supported by the Android team, and it’s the only supported IDE compatible with the Android Development Tools plug-in. Did we mention it’s free?

• We write instructions for the most common operating system used by developers: Windows. Users of Linux or Mac may need to translate some keyboard commands, paths, and installation procedures.

• We focus on the Android platform version available on the Amazon Kindle Fire: Android 2.3.4, API Level 10.

If you haven’t installed the development tools needed to develop Android applications or the Android SDK and tools yet, do so at this time.

Let’s get started!

Familiarizing Yourself with Eclipse

Let’s begin by writing a simple Android “Hello, World” application that displays a line of text to the user. As you do so, you will also be taking a tour through the Eclipse environment. Specifically, you will learn about some of the features offered by the Android Development Tools (ADT) plug-in for Eclipse. The ADT plug-in provides functionality for developing, compiling, packaging, and deploying Android applications. Specifically, the ADT plug-in provides the following features:

• The Android Project Wizard, which generates all the required project files

• Android-specific resource editors, including a Graphical Layout editor for designing Android application user interfaces

• The Android SDK Manager

• The Android Virtual Devices (AVD) Manager

• The Eclipse DDMS perspective for monitoring and debugging Android applications

• Integration with the Android LogCat logging utility

• Integration with the Android Hierarchy Viewer layout utility

• Automated builds and application deployment to Android emulators and devices

• Application packaging and code signing tools for release deployment, including ProGuard support for code optimization and obfuscation

Now, let’s take some of these features for a spin.

Creating Android Projects

The Android Project Wizard creates all the required files for an Android application. Open Eclipse and follow these steps to create a new project:

1. Choose File, New, Android Project, or click the Android Project creator icon ) on the Eclipse toolbar.

2. Choose a project name. In this case, name the project HelloKindle. The first time you try to create an Android Project in Eclipse, you might need to choose File, New, Project..., and then select the Android, Android Project. After you do this once, it appears in the Eclipse project types, and you can use the method described in Step 1.

3. Choose a location for the project source code. Because this is a new project, select the Create New Project in Workspace radio button. If you prefer to store your project files in a location other than the default, simply uncheck the Use Default Location check box and browse to the directory of your choice. The settings should look like Figure 1.2.

Figure 1.2. Project Name and Location

4. Press the Next button.

5. Select a build target for your application, as shown in Figure 1.3. For most applications, you want to select the version of Android most appropriate for the devices used by your target audience and the needs of your application. For Kindle development, choose API Level 10 (Android 2.3.3) using the Android Open Source Project vender version (not the Google, Inc., vender version). Kindle Fire devices do not have access to Google add-ons.

Figure 1.3. Choose SDK Target

6. Press the Next button.

7. Specify an application name. This name is what users will see. In this case, call the application Hello Kindle.

8. Specify a package name, following standard package namespace conventions for Java. Because all the code in this book falls under the com.kindlebook.* namespace, use the package name com.kindlebook.hellokindle.

9. Check the Create Activity check box. This instructs the wizard to create a default launch Activity class for the application. Call your activity HelloKindleActivity.

10. Confirm that the Minimum SDK field is correct. This field will be set to the API level of the build target by default. (Android 2.3.3 is API Level 10.) If you want to support older versions of the Android SDK, you need to change this value. For example, to support devices with Android 1.6, set the Min SDK Version to API Level 4. The Kindle is based on API Level 10, however, so an application just targeting the Kindle does not need to worry about this. Your project settings will look like what’s shown in Figure 1.4.

Figure 1.4. Configure Package Name, Initial Activity, and Minimum SDK

11. The Android Project Wizard allows you to create a test project in conjunction with your Android application, also shown in Figure 1.4. For this example, a test project is unnecessary. However, you can always add a test project later by clicking the Android Test Project creator icon, which is to the right of the Android Project Wizard icon ) on the Eclipse toolbar.

12. Click the Finish button.

Note

You can also add existing Android projects to Eclipse by using the Android Project Wizard. To do this, simply select Create Project from Existing Source instead of the default Create New Project in Workspace in the New Android Project dialog (refer to Figure 1.2). Several sample projects are provided in the /samples directory of the Android SDK, under the specific platform they support. For example, the Android SDK sample projects are found in the directory /platforms/android-xxx/samples (where xxx is the platform level number, such as 10).

You can also select a third option: Create Project from Existing Sample, which will do as it says. However, make sure that you choose the build target first to get the list of sample projects you can create.

Exploring the Android Project Files

You will now see a new Android project called HelloKindle in the Eclipse File Explorer. In addition to linking the appropriate Android SDK jar file, the following core files and directories are created:

• AndroidManifest.xml—The central configuration file for the application.

• project.properties—A generated build file used by Eclipse and the Android ADT plug-in. Do not edit this file.

• proguard.cfg—A generated build file used by Eclipse, ProGuard, and the Android ADT plug-in. Edit this file to configure your code optimization and obfuscation settings for release builds.

• /src folder—Required folder for all source code.

• /src/com.kindlebook.hellokindle/HelloKindleActivity.java—Main entry point to this application, named HelloKindleActivity. This activity has been defined as the default launch activity in the Android manifest file.

• /gen/com.kindlebook.hellokindle/R.java—A generated resource management source file. Do not edit this file.

• /assets folder—Required folder where uncompiled file resources can be included in the project.

• /res folder—Required folder where all application resources are managed. Application resources include animations, drawable graphics, layout files, data-like strings and numbers, and raw files.

• /res/drawable-* folders—Application icon graphic resources are included in several sizes for different device screen resolutions.

• /res/layout/main.xml—Layout resource file used by DroidActivity to organize controls on the main application screen.

• /res/values/strings.xml—The resource file where string resources are defined.

Editing Project Resources

The Android manifest file is the central configuration file for an Android application. Double-click the AndroidManifest.xml file within your new project to launch the Android manifest file editor (see Figure 1.5).

Figure 1.5. Editing the Android Manifest File in Eclipse

Editing the Android Manifest File

The Android manifest file editor organizes the manifest information into a number of tabs:

• Manifest—This tab, shown in Figure 1.5, is used for general application-wide settings, such as the package name and application version information (used for installation and upgrade purposes).

• Application—This tab is defines application details, such as the name and icon the application displays, as well as the “guts” of the application, such as what activities can be run (including the default launch DroidActivity) and other functionality and services that the application provides.

• Permissions—This tab defines the application’s permissions. For example, if the application requires the ability to access Internet resources, it must register a uses-permission tag within the manifest, with the name android.permission.INTERNET.

• Instrumentation—This tab is used for unit testing, using the various instrumentation classes available within the Android SDK.

• AndroidManifest.xml—This tab provides a simple XML editor to directly edit the manifest file. Because all Android resource files, including the Android manifest file, are simply XML files, you can always edit the XML instead of using the resource editors. You can create a new Android XML resource file by clicking the Android XML creator icon () on the Eclipse toolbar.

If you switch to the AndroidManifest.xml tab, your manifest file will look something like this:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.kindlebook.hellokindle"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="10"

android:targetSdkVersion="10" />

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

<activity

android:name=".HelloKindleActivity"

android:label="@string/app_name" >

<intent-filter>

<action

android:name="android.intent.action.MAIN" />

<category

android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Editing Other Resource Files

Android applications are made up of functions (Java code, classes) and data (including resources like graphics, strings, and so on). Most Android application resources are stored under the /res subdirectory of the project. The following subdirectories are also available by default in a new Android project:

• /drawable-ldpi, /drawable-hdpi, /drawable-mdpi—These subdirectories store graphics and drawable resource files for different screen densities and resolutions. If you browse through these directories using the Eclipse Project Explorer, you will find the icon.png graphics file in each one; this is your application’s icon.

• /layout—This subdirectory stores user interface layout files. Within this subdirectory, you will find the main.xml screen layout resource file that defines the user interface for the one activity in this simple application.

• /values—This subdirectory organizes the various types of resources, such as text strings, color values, and other primitive types. Here, you find the strings.xml resource file, which contains all the string resources used by the application.

If you double-click any of resource files, the resource editor will launch. Remember that you can always directly edit the XML. For example, let’s try editing a string resource file. If you inspect the main.xml layout file of the project, you notice that it displays a simple layout with a single TextView control. This user interface control simply displays a string. In this case, the string displayed is defined in the string resource called @string/hello. To edit the string resource called @string/hello, using the string resource editor, follow these steps:

1. Open the strings.xml file in the resource editor by double-clicking it in the Eclipse Package Explorer.

2. Select the String called hello and note the name (hello) and value (Hello World, HelloKindleActivity!) shown in the resource editor.

3. Within the Value field, change the text to Hello, Kindle Fire.

4. Save the file.

If you switch to the strings.xml tab and look through the raw XML, you notice that two string elements are defined within a <resources> block:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello">Hello, Kindle Fire</string>

<string name="app_name">Hello Kindle</string>

</resources>

The first resource is the string called @string/hello. The second resource is the string called @string/app_name, which contains the name label for the application. If you look at the Android manifest file again, you see @string/app_name used in the application configuration.

We talk more about project resources in Chapter 4, “Managing Application Resources.” For now, let’s move on to compiling and running the application.

Running and Debugging Applications

To build and debug an Android application, you must first configure your project for debugging. The ADT plug-in enables you to do this entirely within the Eclipse development environment. Specifically, you need to do the following:

1. Create and configure an Android Virtual Device (AVD).

2. Create an Eclipse debug configuration for your project.

3. Build the Android project and launch the emulator with the AVD.

When you complete each of these tasks, Eclipse attaches its debugger to the Android emulator (or Android device connected via USB), and you are free to run and debug the application as desired.

Managing Android Virtual Devices

To run an application in the Android emulator, you must configure an Android Virtual Device (AVD). The AVD profile describes the type of device you want the emulator to simulate, including which Android platform to support. You can specify different screen sizes and resolutions, and you can specify whether the emulator has an SD card and, if so, its capacity. In this case, a slightly modified AVD for the default installation of Android 2.3.3 will suffice. Here are the steps for creating a basic AVD:

1. Launch the Android Virtual Device Manager from within Eclipse by clicking on the little Android icon with the bugdroid in mini-phone ) on the toolbar. You can also launch the manager by selecting Window, AVD Manager in Eclipse.

2. Click the New button to create a new AVD.

3. Choose a name for the AVD. Because you are going to take all the defaults, name this AVD KindleFire-Portrait.

4. Choose a build target. The Kindle Fire is based on API Level 10, Android 2.3.3.

5. Choose an SD card capacity, in either kibibytes or mibibytes. (Not familiar with kibibytes? See this Wikipedia entry: http://goo.gl/N3Rdd.)

Note

Although to mimic a Kindle Fire, you’d choose 8GiB, we recommend choosing something fairly small, because a file of the size of the SD card will be allocated on your drive each time you create a new AVD; these can quickly add up. Unless your application requires substantial storage, we recommend something like 64MiB.

6. Choose a skin. This option controls the different visual looks of the emulator. In this case, we use the effective resolution of the Kindle Fire screen of 600 pixels wide and 1004 pixels high (the default portrait resolution). Alternately, we could create an AVD for landscape mode, where we’d need to use 1024 pixels wide and 580 pixels high. The Kindle Fire reserves some space for a soft key menu.

7. Under Hardware, change the Abstracted LCD density to 169 and change the Device ram size to 512 to better emulate the Kindle Fire device characteristics.

8. Optionally enable the Snapshot feature. This allows you to save and restore the state of an emulator session, dramatically improving the speed with which it launches.

Your project settings should look like what’s shown in Figure 1.6.

Figure 1.6. Creating a New AVD in Eclipse

9. Click the Create AVD button and wait for the operation to complete. This may take a few seconds if your SD card capacity is large, because the memory allocated for the SD card emulation is formatted as part of the AVD creation process.

10. Check the Snapshot checkbox to enable much faster emulator restart times at the expense of some storage space.

11. Click Finish. You should now see your newly created AVD in the list.

Creating Debug and Run Configurations in Eclipse

You are almost ready to launch your application. You have one last remaining task: You need to create a Debug configuration (or Run configuration) for your project in Eclipse. To do this, follow these steps:

1. In Eclipse, choose Run, Debug Configurations from the menu or, alternately, click the drop-down menu next to the Debug icon () on the Eclipse toolbar and choose the Debug Configurations... option.

2. Double-click the Android Application item to create a new entry.

3. Edit that new entry, currently called New_configuration.

4. Change the name of the configuration to HelloKindleDebug.

5. Set the project by clicking the Browse button and choosing the HelloKindle project.

6. On the Target tab, check the box next to the AVD you created.

7. Apply your changes by clicking the Apply button. Your Debug Configurations dialog should look like Figure 1.7.

Figure 1.7. The HelloKindleDebug Debug Configuration in Eclipse

Launching Android Applications Using the Emulator

It’s launch time, and your application is ready to go! To launch the application, simply click the Debug button from within the Launch Configuration screen, or you can do it from the project by clicking the little green bug icon () on the Eclipse toolbar. Then, select HelloKindleDebug debug configuration from the list.

Note

The first time you try to select HelloKindleDebug debug configuration from the little green bug drop-down, you must navigate through the Debug Configurations manager. Future attempts will show the HelloKindleDebug configuration for convenient access.

After you click the Debug button, the emulator launches (see Figure 1.8). This can take some time, so be patient.

Figure 1.8. The Android Emulator Home Screen

Now, the Eclipse debugger is attached, and your application runs, as shown in Figure 1.9.

Figure 1.9. The Application Running

As you can see, the application is simple. It displays a single TextView control with a line of text. The application does nothing else.

The emulator’s home screen doesn’t look anything like the home screen on a real Kindle Fire device, because it has been redesigned by Amazon. Among other things, this means the emulator won’t work for full application testing. You need to get a real Kindle Fire device for that.

Controlling the Emulator

When you create an AVD in this way, it will not have the keyboard and control buttons to the left of the screen, like you might be used to with the default emulators. All the commands are available through your development machine keyboard. For example, the Home key maps conveniently to the Home key. The menu key maps to F2 or Page-Up. Search maps to F5. Back maps to Esc. There are many more; find them in the Android documentation at http://goo.gl/5DMiI.

Debugging Android Applications Using DDMS

In addition to the normal Debug perspective built into Eclipse for stepping through code and debugging, the ADT plug-in adds the DDMS perspective. Although you have the application running, take a quick look at this perspective in Eclipse. You can get to the DDMS perspective (see Figure 1.10) by clicking the Android DDMS icon () in the top-right corner of Eclipse. To switch back to the Eclipse Project Explorer, simply choose the Java perspective from the top-right corner of Eclipse.

Figure 1.10. The DDMS Perspective

The DDMS perspective can be used to monitor application processes, as well as interact with the emulator. You can simulate voice calls and send SMS messages to the emulator. You can send a mock location fix to the emulator to mimic location-based services. You learn more about DDMS and the other tools available to Android developers in Chapter 2, “Mastering the Android Development Tools.”

The LogCat logging tool is displayed on both the DDMS perspective and the Debug perspective. This tool displays logging information from the emulator or the device, if a device is plugged in via USB.

Launching Android Applications on a Device

It’s time to load your application onto a real Kindle Fire device. To do this, you need to connect the Kindle Fire into your computer using a USB data cable. Make sure that you have your machine configured for Kindle Fire debugging.

To ensure that you debug using the correct settings, follow these steps:

1. In Eclipse, from the Java perspective (as opposed to the DDMS perspective), choose Run, Debug Configurations.

2. Single-click HelloKindleDebug Debug Configuration.

3. On the Target tab, change Deployment Target Selection Mode to Manual. You can always change it back to Automatic later, but choosing Manual forces you to choose whether to debug within the emulator (with a specific AVD) or a device, if one is plugged in via USB, whenever you choose to deploy and debug your application from Eclipse.

4. Apply your changes by clicking the Apply button.

5. Plug a Kindle Fire device into your development computer using a USB cable.

6. Click the Debug button within Eclipse. The dialog shown in Figure 1.11 appears, showing all available configurations for running and debugging your application. All physical devices are listed, as are existing emulators that are running. You can also launch new emulator instances by using other AVDs you have created.

Figure 1.11. Choosing an Application Deployment Target

7. Choose the available Kindle Fire device. If you do not see the Kindle Fire listed, check your cables and make sure that you installed the appropriate drivers.

Eclipse now installs the Android application onto your Kindle Fire, attaches the debugger, and runs your application. Your device shows a screen similar to the one you saw in the emulator. If you look at the DDMS perspective in Eclipse, you see that logging information is available, and many features of the DDMS perspective work with physical devices and the emulator, such as taking a screenshot (see Figure 1.12).

Figure 1.12. The Application Running on a Kindle Fire

Summary

Congratulations! You are now a Kindle Fire Android developer. You are learning your way around the Eclipse development environment. You created your first Android project. You reviewed and compiled working Android code. Finally, you ran your newly created Android application on the Android emulator as well as on a real Kindle Fire.

Exercises

1. Visit the Android website at http://developer.android.com and look around. Check out the online Developer’s Guide and reference materials. Check out the Community tab and seriously consider signing up for the Android Beginners and Android Developers Google groups.

2. Visit the Eclipse website and look around. Check out the online documentation at http://www.eclipse.org/documentation/ (http://goo.gl/fc406). Eclipse is an open source project, made freely available; check out the Contribute link (http://www.eclipse.org/contribute/) and consider how you might give back to this great project in some way, either by reporting bugs or one of the many other options provided.

3. Visit the Amazon Appstore Developer portal and look around. You can get started here: https://developer.amazon.com/welcome.html. While you’re at it, head over to the Amazon Appstore Developer Blog at http://www.amazonappstoredev.com.

2. Mastering the Android Development Tools

Android developers are fortunate to have more than a dozen development tools at their disposal to help facilitate the design of quality applications. Understanding what tools are available and what they can be used for is a task best done early in the Android learning process, so that, when you are faced with a problem, you have some clue as to which utility might be able to help you find a solution. Most of the Android development tools are integrated into Eclipse using the ADT plug-in, but they can also be launched independently—you’ll find the executables in the /tools subdirectory of the Android SDK installation. In this chapter, we walk through a number of the most important tools available for use with Android. This information will help you develop Android applications faster and with fewer roadblocks.

Using the Android Documentation

Although it is not a tool, per se, the Android documentation is a key resource for Android developers. An HTML version of the Android documentation is provided in the /docs subfolder of the Android SDK documentation, and this should always be your first stop when you encounter a problem. You can also access the latest help documentation online at the Android Developer website, http://developer.android.com (http://goo.gl/K8GgD, see Figure 2.1 for a screenshot of the Dev Guide tab of this website).

Figure 2.1. The Android Developer Website

The Android documentation is divided into seven sections:

• Home—This tab provides some high-level news items for Android developers, including announcements of new platform versions. You’ll also find quick links for downloading the latest Android SDK, publishing your applications on the Android Market, and other helpful information.

• SDK—This tab provides important information about the SDK version installed on your machine. One of the most important features of this tab is the release notes, which describe any known issues for the specific installation. This information is also useful if the online help has been upgraded, but you want to develop to an older version of the SDK.

• Dev Guide—This tab links to the Android Developer’s Guide, which includes a number of FAQs for developers, best practice guides, and a useful glossary of Android terminology for those new to the platform. The Appendix section also lists all Android platform versions (API Levels), supported media formats, and lists of intents.

• Reference—This tab includes a searchable package and class index of all Android APIs provided as part of the Android SDK, in a Javadoc-style format.

• Resources—This tab includes links to articles, tutorials and sample code, as well as acting as a gateway to the Android developer forums. There are many Google groups that you can join, depending on your interests.

• Videos—This tab, which is available online only, is your resource for Android training videos. Here, you find videos about the Android platform, developer tips, and the Google I/O conference sessions.

• Blog—This tab links to the official Android developer blog. Check here for the latest news and announcements about the Android platform. This is a great place to find how-to examples, learn how to optimize Android applications, and hear about new SDK releases and Android Developer Challenges.

Now is a good time to get to know your way around the Android SDK documentation. First, check out the online documentation and then try the local documentation (available in the /docs subdirectory of your Android SDK installation).

Debugging Applications with DDMS

The Dalvik Debug Monitor Service (DDMS) is a debugging utility that is integrated into Eclipse through a special Eclipse perspective. The DDMS perspective provides a number of useful features for interacting with emulators or devices and the applications being debugged (see Figure 2.2).

Figure 2.2. The DDMS Perspective in Eclipse

The features of DDMS are roughly divided into six functional areas:

• Task management

• File management

• Memory management

• Emulator interaction

• Logging

• Screen captures

DDMS and the DDMS perspective are essential debugging tools. Now, let’s look at how to use these features in more detail.

Debugging from the DDMS Perspective

Within the DDMS perspective, you can choose a specific process on an emulator or a device and then click the Debug button()to attach a debugger to that process. You need to have the source code in your Eclipse workspace for this to work properly. This works only in Eclipse, not in the standalone version of DDMS.

Managing Tasks

The top-left corner of the DDMS perspective lists the emulators and devices currently connected. You can select individual instances and view its processes and threads. You can inspect threads by clicking the device process you are interested in—for example, com.androidbook.hellokindle—and clicking the Update Threads button (), as shown in Figure 2.3. You can also prompt garbage collection on a process and then view the heap updates by clicking the Update Heap button (). Finally, you can stop a process by clicking the Stop Process button ().

Figure 2.3. The Threads Tab in DDMS

Browsing the Android File System

You can use the DDMS File Explorer to browse files and directories on the emulator or a device (see Figure 2.4). You can copy files between the Android file system and your development machine by using the Push () and Pull () buttons available in the top right-hand corner of the File Explorer tab.

Figure 2.4. The File Explorer Tab in DDMS

You can also delete files and directories by using the Delete button () or just pressing Delete. There is no confirmation for this delete operation; nor can it be undone.

Taking Screenshots of the Emulator or Device

One feature that can be particularly useful for debugging both devices and emulators is the ability to take screenshots of the current screen (see Figure 2.5).

Figure 2.5. Taking a Screenshot Using DDMS

The screenshot feature of the DDMS perspective is particularly useful when used with real devices. To take a screen capture of what’s going on at this very moment on your device, follow these steps:

1. In the DDMS perspective, choose the device (or emulator) you want a screenshot of. The device must be connected via USB.

2. On that device or emulator, make sure you have the screen you want. Navigate to it, if necessary.

3. Press the Screen Capture button () to take a screen capture. This launches a capture screen dialog.

4. The Rotate button rotates the Device Screen Capture tool to display in portrait mode. This is useful for Kindle Fire screen captures.

5. Within the capture screen dialog, click the Save button to save the screenshot to your local hard drive. This tool does not show a live view, just a snapshot; click the Refresh button to update the capture view if you make changes on the device. The Copy button places the image on your system’s clipboard for pasting into another application, such as an image editor. Click the Done button to exit the tool and return to the DDMS perspective.

Viewing Log Information

The LogCat logging utility that is integrated into the DDMS perspective allows you to view the Android logging console. You may have noted the LogCat logging tab, with its diagnostic output, in Figure 2.2 earlier in this chapter. We talk more about how to implement your own custom application logging in Chapter 3, “Building Kindle Fire Applications.”

Eclipse has the ability to filter logs by log severity. You can also create custom log filters by using tags.

Working with the Android Emulator

The Android emulator is probably the most powerful tool at a developer’s disposal. It is important for developers to learn to use the emulator and understand its limitations. The Android emulator is integrated with Eclipse, using the ADT plug-in for the Eclipse IDE.

The Android emulator is a convenient tool, but it has some limitations:

• The emulator is not a device. It simulates generic device behavior, not specific hardware implementations or limitations. This is particular noticeable with Kindle Fire emulation; not even the home screen is the same. None of the custom Amazon Kindle Fire experience is emulated at this time.

• Sensor data, battery and power settings, and network connectivity are all simulated using your computer.

• No Kindle Fire built-in apps are present on the emulator.

Using the Android emulator is not a substitute for testing on a true Android device.

Providing Input to the Emulator

As a developer, you can provide input to the emulator in a number of ways:

• Use your computer mouse to click, scroll, and drag items (for example, sliding volume controls) onscreen, as well as on the emulator skin.

• Use your computer keyboard to input text into controls.

• Use your mouse to simulate individual finger presses on the soft keyboard or physical emulator keyboard.

• Use a number of emulator keyboard commands to control specific emulator states.

Using Other Android Tools

Although we’ve already covered the most important tools, a number of other special-purpose utilities are included with the Android SDK. A list of the tools that come as part of the Android SDK is available on the Android developer website (http://goo.gl/yzFHz). Here, you can find a description of each tool and a link to its official documentation.

Summary

The Android SDK ships with a number of powerful tools to help with common Android development tasks. The Android documentation is an essential reference for developers. The DDMS debugging tool, which is integrated into the Eclipse development environment as a perspective, is useful for monitoring emulators and devices. The Android emulator can be used for running and debugging Android applications virtually, without the need for an actual device. There are also numerous other tools for interacting with physical devices and emulators in a variety of situations.

Exercises

1. Head over to the Android Developer’s Guide website at http://d.android.com/guide. Consider reading the article “Android Basics: What is Android?” (http://d.android.com/guide/basics/what-is-android.html).

2. Launch the Android emulator. Get familiar with how the emulator tries to mimic a real Kindle Fire device. Note the limitations.

3. Launch the HelloKindle application you wrote in Chapter 1, “Getting Started with Kindle Fire,” and explore it using the DDMS tool.

3. Building Kindle Fire Applications

Amazon built the Kindle Fire using the Android platform. Every platform technology uses different terminology to describe its application components. The three most important classes on the Android platform are Context, Activity, and Intent. Although there are other more advanced components that developers can implement, these three components form the building blocks for each and every Android application. In this chapter, we focus on understanding how Android applications are put together. We also take a look at some handy utility classes that can help developers debug applications.

Note

Some readers have assumed that they were to perform all the tasks discussed in this chapter on their own and build an app in one chapter without any help whatsoever. Not so! This chapter just gives you the 10,000-foot view of Android application development so that you have a good idea what you’ll begin implementing an application from the ground up. We do this so you get an idea of how another application might be built. So, get yourself a cup of coffee, tea, or your “brain fuel” of choice, sit back, relax, and let’s discuss the building blocks of Android apps.

Designing an Android Application

An Android application is a collection of tasks, each of which is called an activity. Each activity within an application has a unique purpose and user interface. To understand this more fully, imagine a theoretical game application called Chippy’s Revenge.

Designing Application Features

The design of the Chippy’s Revenge game is simple. It has five screens:

• Splash—This screen acts as a startup screen, with the game logo and version. It might also play some music.

• Menu—On this screen, a user can choose among several options, including playing the game, viewing the scores, and reading the help text.

• Play—This screen is where game play actually takes place.

• Scores—This screen displays the highest scores for the game (including high scores from other players), providing players with a challenge to do better.

• Help—This screen displays instructions for how to play the game, including controls, goals, scoring methods, tips, and tricks.

Starting to sound familiar? You may recognize this generic design from many a mobile application, game or otherwise, on any platform.

Determining Application Activity Requirements

You need to implement five activity classes, one for each feature of the game:

• SplashActivity—This activity serves as the default activity to launch. It simply displays a layout (maybe just a big graphic), plays music for several seconds, and then launches MenuActivity.

• MenuActivity—This activity is pretty straightforward. Its layout has several buttons, each corresponding to a feature of the application. The onClick() handlers for each button trigger cause the associated activity to launch.

• PlayActivity—The real application guts are implemented here. This activity needs to draw stuff onscreen, handle various types of user input, keep score, and generally follow whatever game dynamics the developer wants to support.

• ScoresActivity—This activity is about as simple as SplashActivity. It does little more than load a bunch of scoring information into a TextView control within its layout.

• HelpActivity—This activity is almost identical to ScoresActivity, except that instead of displaying scores, it displays help text. Its TextView control might possibly scroll.

Each activity class should have its own corresponding layout file stored in the application resources. You could use a single layout file for ScoresActivity and HelpActivity, but it’s not necessary. If you did, however, you would simply create a single layout for both and set the image in the background and the text in the TextView control at runtime, instead of within the layout file.

Figure 3.1 shows the resulting design for your game, Chippy’s Revenge Version 0.0.1 for Android.

Figure 3.1. Chippy’s Revenge Application Design

Implementing Application Functionality

Now that you understand how a typical Android application might be designed, you’re probably wondering how to go about implementing that design.

We’ve talked about how each activity has its own user interface, defined within a separate layout resource file. You might be wondering about implementation hurdles such as the following:

• How do I control application state?

• How do I save settings?

• How do I launch a specific activity?

With our theoretical game application in mind, it is time to dive into the implementation details of developing an Android application. A good place to start is the application context.

Using the Application Context

The application context is the central location for all top-level application functionality. You use the application context to access settings and resources shared across multiple activity instances.

You can retrieve the application context for the current process by using the getApplicationContext() method, like this:

Context context = getApplicationContext();

Because the Activity class is derived from the Context class, you can use the this object instead of retrieving the application context explicitly when you’re writing code inside your Activity class.

Once you retrieve a valid application context, you can use it to access application-wide features and services.

Retrieving Application Resources

You can retrieve application resources by using the getResources() method of the application context. The most straightforward way to retrieve a resource is by using its unique resource identifier, as defined in the automatically generated R.java class. The following example retrieves a String instance from the application resources by its resource ID:

String greeting = getResources().getString(R.string.hello);

Accessing Application Preferences

You can retrieve shared application preferences by using the getSharedPreferences() method of the application context. You can use the SharedPreferences class to save simple application data, such as configuration settings. Each SharedPreferences object can be given a name, allowing you can organize preferences into categories or store preferences all together in one large set.

For example, you might want to keep track of each user’s name and some simple game state information, such as whether the user has credits left to play. The following code creates a set of shared preferences called GamePrefs and saves a few such preferences:

SharedPreferences settings = getSharedPreferences("GamePrefs", MODE_PRIVATE);

SharedPreferences.Editor prefEditor = settings.edit();

prefEditor.putString("UserName", "Spunky");

prefEditor.putBoolean("HasCredits", true);

prefEditor.commit();

To retrieve preference settings, you simply retrieve SharedPreferences and read the values back out:

SharedPreferences settings = getSharedPreferences("GamePrefs", MODE_PRIVATE);

String userName = settings.getString("UserName", "Chippy Jr. (Default)");

Accessing Other Application Functionality Using Contexts

The application context provides access to a number of top-level application features. Here are a few more things you can do with the application context:

• Launch Activity instances

• Retrieve assets packaged with the application

• Request a system-level service provider

• Manage private application files, directories, and databases

• Inspect and enforce application permissions

The first item on this list—launching Activity instances—is perhaps the most common reason you will use the application context.

Working with Activities

The Activity class is central to every Android application. Much of the time, you’ll define and implement an activity for each screen in your application.

In the Chippy’s Revenge game application, you have to implement five different Activity classes. In the course of playing the game, the user transitions from one activity to the next, interacting with the layout controls of each activity.

Launching Activities

There are a number of ways to launch an activity, including the following:

• Designating a launch activity in the manifest file

• Launching an activity using the application context

• Launching a child activity from a parent activity for a result

Designating a Launch Activity in the Manifest File

Each Android application must designate a default activity within the Android manifest file. If you inspect the manifest file of the HelloKindle project, you notice that HelloKindleActivity is designated as the default activity.

In Chippy’s Revenge, SplashActivity is the most logical activity to launch by default.

Launching Activities Using the Application Context

The most common way to launch an activity is to use the startActivity() method of the application context. This method takes one parameter, an Intent object. We talk more about the Intent class in a moment, but for now, let’s look at a simple startActivity() call.

The following code calls the startActivity() method with an explicit intent:

startActivity(new Intent(getApplicationContext(), MenuActivity. class));

This intent requests the launch of the target activity, named MenuActivity, by its class. This class must be implemented elsewhere within the package.

Because the MenuActivity class is defined within this application’s package, it must be registered as an activity within the Android manifest file. In fact, you could use this method to launch every activity in your theoretical game application; however, this is just one way to launch an activity.

Launching an Activity for a Result

Sometimes, you want to launch an activity, have it determine something (such as a user’s choice), and then return that information to the calling activity. When an activity needs a result, it can be launched using the Activity.startActivityForResult() method. The result will be returned in the Intent parameter of the calling activity’s onActivityResult() method. We talk more about how to pass data using an Intent parameter in a moment.

Managing Activity State

Applications can be interrupted when various higher priority events, such as alarms or certain types of notifications, take precedence. There can be only one active application at a time; specifically, a single application activity can be in the foreground at any given time. Although this is less common on a tablet, such as the Kindle Fire, you still need to be prepared for interruptions at any time based on user behavior, such as pressing the Home button and pausing the application.

Android applications are responsible for managing their state, as well as their memory, resources, and data. The Android operating system may terminate an activity that has been paused, stopped, or destroyed when memory is low. This means that any activity that is not in the foreground is subject to shutdown. In other words, an Android application must keep state and be ready to be interrupted and even shutdown at any time.

Using Activity Callbacks

The Activity class has many callbacks that provide an opportunity for an activity to respond to events, such as suspending and resuming. Table 3.1 lists the most important callback methods.

Table 3.1. Key Callback Methods of Android Activities

The main thread is often called the UI thread, because this is where the processing for drawing the UI takes place internally. An activity must perform any processing that takes place during a callback reasonably quickly, so that the main thread is not blocked. If the main UI thread is blocked for too long, the Android system shuts down the activity because of a lack of response. This is especially important to respond quickly during the onPause() callback, when a higher priority task is entering the foreground.

Figure 3.2 shows the order in which activity callbacks are called.

Figure 3.2. Important Activity Lifecycle Callbacks

Saving Activity State

An Activity can have private preferences—much like shared application preferences. You can access these preferences by using the getPreferences() method of the activity. This mechanism is useful for saving state information. For example, PlayActivity for your game might use these preferences to keep track of the current level and score, player health statistics, and game state.

Shutting Down Activities

To shut down an activity, you make a call to the finish() method. There are several different versions of this method to use, depending whether the activity is shutting itself down or shutting down another activity.

Within your game application, you might return from the Scores, Play, and Help screens to the Menu screen by finishing ScoresActivity, PlayActivity, or HelpActivity.

Working with Intents

An Intent object encapsulates a task request used by the Android operating system. When the startActivity() method is called with the Intent parameter, the Android system matches the Intent action with appropriate activity on the Android system. That activity is then launched.

The Android system handles all intent resolution. An Intent instance can be very specific, including a request for a specific activity to be launched, or somewhat vague, requesting that any activity matching certain criteria be launched. For the finer details on intent resolution, see the Android documentation.

Passing Information with Intents

Intents can be used to pass data between activities. You can use an Intent object in this way by including additional data, called extras, within the intent.

To package extra pieces of data along with an intent, use the putExtra() method with the appropriate type of object you want to include. The Android programming convention for intent extras is to name each one with the package prefix (for example, com.androidbook.chippy.NameOfExtra).

For example, the following intent includes an extra piece of information, the current game level, which is an integer:

Intent intent = new Intent(getApplicationContext(), HelpActivity.class);

intent.putExtra("com.androidbook.chippy.LEVEL", 23);

startActivity(intent);

When the HelpActivity class launches, the getIntent() method can be used to retrieve the intent. Then, the extra information can be extracted using the appropriate methods. Here’s an example:

Intent callingIntent = getIntent();

int helpLevel = callingIntent.getIntExtra("com.androidbook.chippy.LEVEL", 1);

This little piece of information can be used to give special hints, based on the level.

For the parent activity that launched a subactivity using the startActivityForResult() method, the result will be passed in as a parameter to the onActivityResult() method with an Intent parameter. The intent data can then be extracted and used by the parent activity.

Using Intents to Launch Other Applications

Initially, an application may only be launching activity classes defined within its own package. However, with the appropriate permissions, applications may also launch external activity classes in other applications.

There are well-defined intent actions for many common user tasks. For example, you can create intent actions to initiate applications such as the following:

• Launching the built-in web browser and supplying a URL address

• Launching the web browser and supplying a search string

• Launching the built-in email app and supplying a recipient, subject, and message body

• Launch third-party apps

Here is an example of how to create a simple intent with a predefined action (ACTION_VIEW) to launch the web browser with a specific URL:

Uri address = Uri.parse("http://www.perlgurl.org");

Intent surf = new Intent(Intent.ACTION_VIEW, address);

startActivity(surf);

This example shows an intent that has been created with an action and some data. The action, in this case, is to view something. The data is a uniform resource identifier (URI), which identifies the location of the resource to view.

For this example, the browser’s activity then starts and comes into foreground, causing the original calling activity to pause in the background. When the user finishes with the browser and clicks the Back button, the original activity resumes.

Applications may also create their own intent types and allow other applications to call them, allowing for tightly integrated application suites.

Working with Dialogs

The Kindle Fire screen has more display space available than many types of applications might need. Instead of creating a entirely new Activity to display a small amount of data, you may want to create a dialog instead. Dialogs can be helpful for creating simple user interfaces that do not necessitate an entirely new screen or activity to function. Instead, the calling activity dispatches a dialog, which can have its own layout and user interface, with buttons and input controls.

Table 3.2 lists the important methods for creating and managing activity dialog windows.

Table 3.2. Important Dialog Methods of the Activity Class

Activity classes can include more than one dialog, and each dialog can be created and then used multiple times.

There are quite a few types of ready-made dialog types available for use in addition to the basic dialog: AlertDialog, CharacterPickerDialog, DatePickerDialog, ProgressDialog, and TimePickerDialog.

You can also create an entirely custom dialog by designing an XML layout file and using the Dialog.setContentView() method. To retrieve controls from the dialog layout, simply use the Dialog.findViewById() method.

Dialogs or DialogFragments?

You may have seen in the Android SDK documentation that these Activity dialog-related methods are deprecated in favor of something called a Fragment. Fragments were introduced in API Level 11 (Android 3.0+). At the time of this writing, the Kindle Fire runs API Level 10 and, as such, does not have Fragment classes available. That being said, the Android Support package (a separate JAR file that can be linked to your project) can be used to gain access to some of these new SDK classes, including DialogFragment, in your Kindle Fire applications.

Working with Fragments

The concept of fragments is relatively new to Android. A fragment is simply a block of UI, with its own lifecycle, that can be reused within different activities. Fragments allow developers to create highly modular user interface components that can change dramatically based on screen sizes, orientation, and other aspects of the display that might be relevant to the design.

Table 3.3 shows some important lifecycle calls that are sent to the Fragment class.

Table 3.3. Key Fragment Lifecycle Callbacks

Although the lifecycle of a fragment is similar to that of an activity, a fragment only exists within an activity. A common example of fragment usage is to change the UI flow between portrait and landscape modes. If an interface has a list of items and a details view, the list and the details could both be fragments. In portrait orientation, the screen would show the list view followed by the details view, both full screen. But, in landscape mode, the view could show the list and details side-by-side.

The modular nature of fragments makes them a powerful user interface building block. The Fragment API is also available as a static support library for use with older versions of Android, as far back as Android 1.6; thus, its features can be leveraged by Kindle Fire applications.

Logging Application Information

Android provides a useful logging utility class called android.util.Log. Logging messages are categorized by severity (and verbosity), with errors being the most severe. Table 3.4 lists some commonly used logging methods of the Log class.

Table 3.4. Commonly Used Log Methods

The first parameter of each Log method is a string called a tag. One common Android programming practice is to define a global static string to represent the overall application or the specific activity within the application such that log filters can be created to limit the log output to specific data.

For example, you could define a string called TAG, as follows:

private static final String TAG = "MyApp";

Now, anytime you use a Log method, you supply this tag. An informational logging message might look like this:

Log.i(TAG, "In onCreate() callback method");

You can use the LogCat utility from within Eclipse to filter your log messages to the tag string.

Note

Excessive use of the Log utility can result in decreased application performance. Debug and verbose logging should be used only for development purposes and removed before application publication.

Summary

In this chapter, you saw how different Android applications can be designed using three application components: Context, Activity, and Intent. Each Android application comprises one or more activities. Top-level application functionality is accessible through the application context. Each activity has a special function and (usually) its own layout, or user interface. An activity is launched when the Android system matches an intent object with the most appropriate application activity, based on the action and data information set in the intent. Intents can also be used to pass data from one activity to another.

In addition to learning the basics of how Android applications are put together, you also learned how to take advantage of useful Android utility classes, such as application logging, which can help streamline Android application development and debugging.

Exercises

1. Add a logging tag to the HelloKindleActivity class you created in the HelloKindle project in Chapter 1, “Getting Started with Kindle Fire.” Within the onCreate() callback method, add an informational logging message using the Log.i() method. Run the application and view the log output in the Eclipse DDMS or Debug perspectives within the LogCat tab.

2. Within the HelloKindleActivity class you created in the HelloKindle project in Chapter 1, add method stubs for the Activity callback methods in addition to onCreate(), such as onStart(), onRestart(), onResume(), onPause(), onStop(), and onDestroy(). To do this easily from within Eclipse, right-click the HelloKindleActivity.java class and choose Source, Override/Implement methods. Under the Activity class methods, select the methods suggested above and hit OK. You will see appropriate method stubs added for each of the methods you selected.

3. Add a log message to each Activity class callback method you created in Exercise 2. For example, add an informational log message such as, “In method onCreate()” to the onCreate() method. Run the application normally and view the log output to trace the application lifecycle. Next, try some other scenarios, such as pausing or suspending the application and then resuming. Simulate an incoming call using the Eclipse DDMS perspective while running your application and see what happens.

4. Managing Application Resources

Android applications for the Kindle Fire rely upon strings, graphics, and other types of resources to generate robust user interfaces. Android projects can include these resources using a well-defined project resource hierarchy. In this chapter, we review the most common types of resources used by Android applications, how they are stored, and how they can be accessed programmatically. This chapter prepares you for working with resources in future chapters, but you are not directly asked to write code or create resources.

Using Application and System Resources

Resources are broken down into two types: application resources and system resources. Application resources are defined by the developer within the Android project files and are specific to the application. System resources are common resources defined by the Android platform and accessible to all applications through the Android SDK. You can access both types of resources at runtime.

You can load resources in your Java code, usually from within an activity. You can also reference resources from within other resources; for example, you might reference numerous string, dimension, and color resources from inside an XML layout resource to define the properties and attributes of specific controls, like background colors and text to display.

Working with Application Resources

Application resources are created and stored within the Android project files under the /res directory. Using a well-defined but flexible directory structure, resources are organized, defined, and compiled with the application package. Application resources are not shared with the rest of the Android system.

Storing Application Resources

Defining application data as resources (as opposed to at runtime in code) is good programming practice. Grouping application resources together and compiling them into the application package has the following benefits:

• Code is cleaner and easier to read, leading to fewer bugs.

• Resources are organized by type and guaranteed to be unique.

• Localization and internationalization are straightforward.

The Android platform supports a variety of resource types (see Figure 4.1), which can be combined to form different types of applications. The Kindle Fire device is no different, although its screen is larger than most Android smartphones and smaller than many tablets.

Figure 4.1. Android Applications Use a Variety of Resources

Android applications can include many different kinds of resources. The following are some of the most common resource types:

• Strings, colors, and dimensions

• Drawable graphics files

• Layout files

• Raw files of all types

Resource types are defined with special XML tags and organized into specially named project directories. Some /res subdirectories, such as the /drawable, /layout, and /values directories, are created by default when a new Android project is created, while others must be added by the developer when required.

Resource files stored within /res subdirectories must abide by the following rules:

• Resource filenames must be lowercase.

• Resource filenames may contain letters, numbers, underscores, and periods only.

• Resource filenames (and XML name attributes) must be unique.

When resources are handled during the build process, their name dictates their variable name. For example, a graphics file saved within the /drawable directory as mypic.jpg is referenced as @drawable/mypic. It is important to name resource names intelligently and be aware of character limitations that are stricter than file system names. (For example, dashes cannot be used in image filenames.) Consult the Android documentation for specific project directory naming conventions.

Each time you save a resource file (that is, copy a resource file, such as a graphics file, into the appropriate directory) within Eclipse, the R.java class file is recompiled to incorporate your changes. If you have not used the correct directory- or file-naming conventions, you see a compiler error in the Eclipse Problems tab. (This assumes the Eclipse default setting for Build Automatically is set in the Project menu.)

Referencing Application Resources

All application resources are stored within the /res project directory structure and are compiled into the project at build time. Application resources can be used programmatically. They can also be referenced in other application resources.

Application resources can be accessed programmatically using the generated class file called R.java. To reference a resource from within your Activity class, you must retrieve the application’s Resources object using the getResources() method and then make the appropriate method call, based on the type of resource you want to retrieve.

For example, to retrieve a string named hello defined in the strings.xml resource file, use the following method call:

String greeting = getResources().getString(R.string.hello);

We talk more about how to access different types of resources later in this chapter. To reference an application resource from another compiled resource, such as a layout file, use the following format:

@[resource type]/[resource name]

For example, the same string used earlier would be referenced as follows:

@string/hello

We talk more about referencing resources later in this chapter, when we discuss layout files.

Working with System Resources

Applications can access the Android system resources in addition to their private resources. This “standardized” set of resources is shared across all applications, providing users with common styles and other useful templates, as well as commonly used strings and colors.

System resources are stored within the android.R package. There are classes for each of the major resource types. For example, the android.R.string class contains the system string resources. For example, to retrieve a system resource string called ok from within an Activity class, you first need to use the static method of the Resources class called getSystem() to retrieve the global system Resource object. Then, you call the getString() method with the appropriate string resource name, like this:

String confirm = Resources.getSystem().getString(android.R.string.ok);

To reference a system resource from another compiled resource, such as a layout resource file, use the following format:

@android:[resource type]/[resource name]

For example, you could use the system string for ok by setting the appropriate string attribute as follows:

@android:string/ok

System Resources on the Kindle Fire Device

System resources are available on the Kindle Fire, just like any Android device. The resources that are provided are a fairly typical set. Curious about which system resources are available on your Kindle Fire and what they look like? Check out the app called rs:ResEnum. Written by a developer for developers, this app enumerates all system resources and displays the drawable ones.

Working with Simple Resource Values

Simple resources, such as string, color, and dimension values, should be defined in XML files under the /res/values project directory in XML files. These resource files use special XML tags that represent name/value pairs. These types of resources are compiled into the application package at build time. You can manage string, color, and dimension resources by using the Eclipse Resource editor, or you can edit the XML resource files directly.

Working with Strings

You can use string resources anywhere your application needs to display text. You define string resources with the <string> tag, identify them with the name property, and store them in the resource file /res/values/strings.xml.

Here is an example of a string resource file:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="app_name">Name this App</string>

<string name="hello">Hello</string>

</resources>

String resources have many formatting options. Strings that contain apostrophes or single straight quotes must be escaped or wrapped within double straight quotes. Table 4.1 shows some simple examples of well-formatted string values.

Table 4.1. String Resource Formatting Examples

There are several ways to access a string resource programmatically. The simplest way is to use the getString() method within your Activity class:

String greeting = getResources().getString(R.string.hello);

Working with Colors

You can apply color resources to screen controls. You define color resources with the <color> tag, identify them with the name attribute, and store them in the file /res/values/colors.xml. This XML resource file is not created by default and must be created manually.

You can add a new XML file, such as this one, by choosing File, New, Android XML File, and then fill out the resulting dialog with the type of file (such as values). This automatically sets the expected folder and type of file for the Android project.

Here is an example of a color resource file:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<color name="background_color">#006400</color>

<color name="app_text_color">#FFE4C4</color>

</resources>

The Android system supports 12-bit and 24-bit colors in RGB format. Table 4.2 lists the color formats that the Android platform supports.

Table 4.2. Color Formats Supported in Android

The following Activity class code snippet retrieves a color resource named app_text_color using the getColor() method:

int textColor = getResources().getColor(R.color.app_text_color);

Working with Dimensions

To specify the size of a user interface control, such as a Button or TextView control, you need to specify different kinds of dimensions. Dimension resources are helpful for font sizes, image sizes, and other physical or pixel-relative measurements. You define dimension resources with the <dimen> tag, identify them with the name property, and store them in the resource file /res/values/dimens.xml. This XML resource file is not created by default and must be created manually.

Here is an example of a dimension resource file:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<dimen name="thumbDim">100px</dimen>

</resources>

Each dimension resource value must end with a unit of measurement. Table 4.3 lists the dimension units that Android supports.

Table 4.3. Dimension Unit Measurements Supported in Android

The following Activity class code snippet retrieves a dimension resource called thumbDim using the getDimension() method:

float thumbnailDim = getResources().getDimension(R.dimen.thumbDim);

Working with Drawable Resources

Drawable resources, such as image files, must be saved under the /res/drawable project directory hierarchy. Typically, applications provide multiple versions of the same graphics for different pixel-density screens. A default Android project contains three drawable directories: drawable-ldpi (low density), drawable-mdpi (medium density), and drawable-hdpi (high density). There are many more possible drawable directories. The system picks the correct version of the resource based on the device the application is running on. Kindle Fire–drawable resources should be stored in the mdpi directory. All versions of a specific resource must have the same name in each of the drawable directories. These types of resources are then compiled into the application package at build time and are available to the application.

You can drag and drop image files into the /res/drawable directories by using the Eclipse Project Explorer. Again, remember that filenames must be unique within a particular drawable directory, lowercase, and contain only letters, numbers, and underscores.

Working with Images

The most common drawable resources used in applications are bitmap-style image files, such as PNG and JPG files. These files are often used as application icons and button graphics, but may be used for a number of user interface components.

As shown in Table 4.4, Android supports many common image formats.

Table 4.4. Image Formats Supported in Android

Using Image Resources Programmatically

Image resources are encapsulated in the class BitmapDrawable. To access a graphic resource file called /res/drawable/logo.png within an Activity class, use the getDrawable() method, as follows:

BitmapDrawable logoBitmap =

(BitmapDrawable)getResources().getDrawable(R.drawable.logo);

Most of the time, however, you don’t need to load a graphic directly. Instead, you can use the resource identifier as the source attribute on a control, such as an ImageView control within a compiled layout resource, and it will display on the screen. However, there are times when you might want to programmatically load, process, and set the drawable for a given ImageView control at runtime. The following Activity class code sets and loads the logo.png drawable resource into an ImageView control named LogoImageView, which must be defined in advance:

ImageView logoView = (ImageView)findViewById(R.id.LogoImageView);

logoView.setImageResource(R.drawable.logo);

Working with Other Types of Drawables

In addition to graphics files, you can also create specially formatted XML files to describe other Drawable subclasses, such as ShapeDrawable. You can use the ShapeDrawable class to define different shapes, such as rectangles and ovals. See the Android documentation for the android.graphics.drawable package for further information.

Working with Layouts

Most Android application user interface screens are defined using specially formatted XML files called layouts. Layout XML files can be considered a special type of resource: They are generally used to define what a portion of, or all of, the screen will look like. It helps to think of a layout resource as a template; you fill a layout resource with different types of view controls, which may reference other resources, such as strings, colors, dimensions, and drawables.

In truth, layouts can be compiled into the application package as XML resources or be created at runtime in Java from within your Activity class using the appropriate layout classes within the Android SDK. However, in most cases, using the XML layout resource files greatly improves the clarity, readability, and reusability of code and flexibility of your application.

Layout resource files are stored in the /res/layout directory hierarchy. You compile layout resources into your application as you would any other resources.

Here is an example of a layout resource file:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello" />

</LinearLayout>

You might recognize this layout: It is the default layout, called main.xml, created with any new Android application. This layout file describes the user interface of the only activity within the application. It contains a LinearLayout control that is used as a container for all other user interface controls—in this case, a single TextView control. The main.xml layout file also references another resource: the string resource called @string/hello, which is defined in the strings.xml resource file.

As with the multiple drawable directories, there can be multiple layout directories. In particular, /layout-land for landscape files and /layout-port for portrait files. As with image drawables, the files must be named the same. This gives you the ability to have a different layout file for landscape and portrait orientations that the Kindle Fire supports.

Designing Layouts Using the Layout Resource Editor

You can design and preview compiled layout resources in Eclipse by using the layout resource editor (see Figure 4.2). Double-click the project file /res/layout/main.xml, within Eclipse to launch the layout resource editor. The layout resource editor has two tabs: Graphical Layout and main.xml. The Graphical Layout tab provides drag-and-drop visual design and the ability to preview the layout in various device configurations. You can configure one for Kindle Fire using the custom option, if you like. The main.xml tab allows you to directly edit the layout XML.

Figure 4.2. The Layout Resource Editor in Eclipse

Chances are, you’ll frequently switch back and forth between the graphical and XML modes. There are also several other Eclipse panes that are helpful for using with the layout resource editor: the Outline pane and the Properties pane. You can add and remove controls to the specific layout using the Outline pane (refer to Figure 4.2, bottom). You can set individual properties and attributes of a specific control by using the Properties pane (refer to Figure 4.2, right). Note that Eclipse panes are not fixed—drag them around and configure them in a way that works for you. Eclipse actually calls these panes “views” (confusing for Android folks). You can also add different types of view “panes” from the Windows menu of Eclipse.

Like most other user interface designers, the layout resource editor works well for basic layout design, but it has some limitations. For some of the more complex user interface controls, you might be forced to edit the XML by hand. You might also lose the ability to preview your layout if you add a control to your layout that is not supported by the Graphical Layout tool. In such a case, you can still view your layout by running your application in the emulator or on your Kindle Fire. Displaying an application correctly on a Kindle Fire, rather than the Eclipse Layout Editor, should always be your primary objective.

Designing Layouts Using XML

You can edit the raw XML of a layout file. As you gain experience developing layouts, you should familiarize yourself with the XML layout file format. Switch to the XML view frequently and accustom yourself to the XML generated by each type of control. Do not rely on the Graphical layout resource editor alone—equivalent to a web designer who knows how to use a web design tool but doesn’t know HTML. Although the Graphical Layout tool has gotten much better recently, knowing the XML can help debug tricky problems.

Tired of theory? Give the Eclipse layout resource editor a spin:

1. Open the HelloKindle Android project you created in Chapter 1, “Getting Started with Kindle Fire.”

2. Navigate to the /res/layout/main.xml layout file and double-click the file to open it in the Eclipse layout resource editor.

3. Switch to the Graphical Layout tab, and you should see the layout preview in the main window.

4. Click the Outline tab. This pane displays the View control hierarchy of XML elements in this layout resource. In this case, you have a LinearLayout control. If you expand it, you see that it contains a TextView control.

5. Select the TextView control on the Outline tab. You see a colored box highlight the TextView control in the layout preview.

6. Click the Properties tab. This tab displays all the properties and attributes that can be configured for the TextView control you just selected. Scroll down to the property called Text and note that it has been set to a string resource called @string/hello.

7. Click the Text property called @string/hello on Properties tab. You can now modify the field. You can type in a string directly, manually enter a different string resource (@string/app_name, for example), or click the little button with the three dots and choose an appropriate resource from the list of string resources available to your application. Each time you change this field, note how the Graphical Layout preview is updated automatically.

8. Switch to the main.xml tab and note how the XML is structured. Changes you make in the XML tab are immediately reflected in the Graphical Layout tab. If you save and run your project in the emulator, you should see results similar to those displayed in the preview.

Feel free to continue to explore the layout resource editor. You might want to try adding additional view controls, such as an ImageView control or another TextView control, to your layout.

Using Layout Resources Programmatically

Layout controls, whether Button, ImageView, TextView controls or LinearLayout controls, are derived from the View class. In most instances, you do not need to load and access a whole layout resource programmatically. Instead, you simply want to modify specific View controls within it. For example, you might want to change the text being displayed by the TextView control in the main.xml layout resource.

The default layout file created with the HelloKindle project contains one TextView control. However, this TextView control does not have a default name attribute. The easiest way to access the correct View control is by its unique name, so take a moment and set the id attribute of the TextView control using the layout resource editor. Call it @+id/TextView01.

Now that your TextView control has a unique identifier, you can find it from within your Activity class using the findViewById() method. After you find the TextView you were looking for, you are free to call its methods, such as the TextView class’s setText() method. Here’s how you would retrieve a TextView object named TextView01 that has been defined in the layout resource file:

TextView txt = (TextView)findViewById(R.id.TextView01);

Note that the findViewById() method takes a resource identifier—the same one you just configured in your layout resource file. Here’s what’s happening behind the scenes: When you save the layout resource file as XML, Eclipse automatically recompiles the generated R.java file associated with your project, making the identifier available for use within your Java classes. (If you don’t have the Build Automatically setting in the Project menu turned on, you have to manually build the project.)

Working with Files

In addition to string, graphic, and layout resources, Android projects can contain files as resources. These files may be in any format. However, some formats are more convenient than others.

Working with XML Files

As you might expect, the XML file format is well supported on the Android platform. Arbitrary XML files can be included as resources. These XML files are stored in the /res/xml resource directory. XML file resources are the preferred format for any structured data your application requires.

How you format your XML resource files is up to you. A variety of XML utilities are available as part of the Android platform, as shown in Table 4.5.

Table 4.5. XML Utility Packages

To access an XML resource file called /res/xml/default_values.xml programmatically from within your Activity class, you could use the getXml() method of the Resources class, like this:

XmlResourceParser defaultDataConfig = getResources().getXml(R.xml.default_values);

Once you had access to an XML parser, you could parse your XML, extract the appropriate data, and do with it whatever you want.

Working with Raw Files

An application can include raw files as resources. Raw files your application might use include audio files, video files, and any other file formats you might need. All raw resource files should be included in the /res/raw resource directory. All raw file resources must have unique names, excluding the file suffix (meaning that file1.txt and file1.dat would conflict).

If you plan to include media file resources, consult the Android platform documentation and Amazon’s Kindle Fire FAQ to determine what media formats and encodings are supported. A general list of supported formats for Android devices is available at http://goo.gl/wMNS9, while the list for the Kindle Fire is at http://goo.gl/hNRnX.

The same goes for any other file format you want to include as an application resource. If the file format you plan on using is not supported by the native Android system, your application will be required to do all file processing itself.

To access a raw file resource programmatically from within your Activity class, simply use the openRawResource() method of the Resources class. For example, the following code would create an InputStream object to access to the resource file /res/raw/file1.txt:

InputStream iFile = getResources().openRawResource(R.raw.file1);

Note

There are times when you might want to include files within your application but not have them compiled into application resources. Android provides a special project directory called /assets for this purpose. This project directory resides at the same level as the /res directory. Any files included in this directory are included as binary resources, along with the application installation package, and are not compiled into the application.

Uncompiled files, called application assets, are not accessible through the getResources() method. Instead, you must use AssetManager to access files included in the /assets directory.

Working with Other Types of Resources

We covered the most common types of resources you might need in an application. There are numerous other types of resources available as well. These resource types may be used less often and may be more complex. However, they allow for very powerful applications. Some of the other types of resources you can take advantage of include the following:

• Primitives (boolean values, integer values)

• Arrays (string arrays, integer arrays, typed arrays)

• Menus

• Animation sequences

• Shape drawables

• Styles and themes

• Custom layout controls

When you are ready to use these other resource types, consult the Android documentation for further details. http://goo.gl/X9XZj is a good place to start.

Summary

Kindle Fire applications can use many different types of resources, including application-specific resources and system-wide resources. The Eclipse resource editors facilitate resource management, but XML resource files can also be edited manually. Once defined, resources can be accessed programmatically as well as referenced, by name, by other resources. String, color, and dimension values are stored in specially formatted XML files, and graphic images are stored as individual files. Application user interfaces are defined using XML layout files. Raw files, which can include custom data formats, may also be included as resources for use by the application. Finally, applications may include numerous other types of resources as part of their packages.

Exercises

1. Add a new color resource with a value of #00ff00 to your HelloKindle project. Within the main.xml layout file, use the Properties pane to change the textColor attribute of the TextView control to the color resource you just created. View the layout in the Eclipse layout resource editor and then rerun the application and view the result on an emulator or Kindle Fire—in all three cases, you should see green text.

2. Add a new dimension resource with a value of 22pt to your HelloKindle project. Within the main.xml layout file, use the Properties pane to change the textSize attribute of the TextView control to the dimension resource you just created. View the layout in the Eclipse layout resource editor and then rerun the application and view the result on an emulator or Kindle Fire—in all three cases, you should larger font text (22pt).

3. Add a new drawable graphics file resource to your HelloKindle project (such as a small PNG or JPG file). Within the main.xml layout resource file, use the Outline pane to add an ImageView control to the layout. Then, use the Properties pane to set the ImageView control’s src attribute to the drawable resource you just created. View the layout in the Eclipse layout resource editor and then rerun the application and view the result on an emulator or Kindle Fire—in all three cases, you should see an image below the text on the screen.

5. Configuring the Android Manifest File

Every Android project, for Kindle Fire or otherwise, includes a special file called the Android manifest file. The Android system uses this file to determine application configuration settings, including the application’s identity and what permissions the application requires to run. In this chapter, we examine the Android manifest file and look at how different applications use its features.

Exploring the Android Manifest File

The Android manifest file, named AndroidManifest.xml, is an XML file that must be included at the top level of any Android project. If you use Eclipse with the ADT plug-in, the Android project wizard will create the initial AndroidManifest.xml file with default values for the most important configuration settings. The Android system uses the information in this file to do the following:

• Install and upgrade the application package

• Display application details to users

• Launch application activities

• Manage application permissions

• Handle a number of other advanced application configurations, including acting as a service or content provider

You can edit the Android manifest file by using the Eclipse manifest file resource editor or by manually editing the XML.

The Eclipse manifest file resource editor organizes the manifest information into categories presented on five tabs:

• Manifest

• Application

• Permissions

• Instrumentation

• AndroidManifest.xml

Using the Manifest Tab

The Manifest tab (see Figure 5.1) contains package-wide settings, including the package name, version information, and minimum Android SDK version information. You can also set any hardware configuration requirements here.

Figure 5.1. The Manifest Tab of the Eclipse Manifest File Resource Editor

Using the Application Tab

The Application tab (see Figure 5.2) contains application-wide settings, including the application label and icon, as well as information about application components, such as activities, intent filters, and other application functionality, including configuration for service and content provider implementations.

Figure 5.2. The Application Tab of the Eclipse Manifest File Resource Editor

Using the Permissions Tab

The Permissions tab (see Figure 5.3) contains any permission rules required by the application. This tab can also be used to enforce custom permissions created for the application.

Figure 5.3. The Permissions Tab of the Eclipse Manifest File Resource Editor

Using the Instrumentation Tab

You can use the Instrumentation tab (see Figure 5.4) to declare any instrumentation classes for monitoring the application.

Figure 5.4. The Instrumentation Tab of the Eclipse Manifest File Resource Editor

Using the AndroidManifest.xml Tab

The Android manifest file is a specially formatted XML file. You can edit the XML manually in the AndroidManifest.xml tab of the manifest file resource editor (see Figure 5.5).

Figure 5.5. The AndroidManifest.xml Tab of the Eclipse Manifest File Resource Editor

Figure 5.5 shows the Android manifest file for the HelloKindle project you created in Chapter 1, “Getting Started with Kindle Fire,” which has fairly simple XML.

Note that the file has a single <manifest> tag, within which all the package-wide settings appear. Within this tag is one <application> tag, which defines the specific application with its single activity, called .HelloKindleActivity, with an Intent filter. In addition, the <uses-sdk> tag is set to target only API Level 9 (Android 2.3), for this example.

Now, let’s talk about each settings in more detail.

Configuring Basic Application Settings

If you use the Android project wizard in Eclipse to create a project, then an Android manifest file will be created for you by default. However, this is just a starting point. It is important to become familiar with how the Android Manifest file works; if your applications manifest file is configured incorrectly, then your application may not run properly.

In terms of the XML definition for the Android manifest file, it will always start with an XML header:

<?xml version="1.0" encoding="utf-8"?>

Many of the important settings your application requires are set using attributes and child tags of the <manifest> and <application> blocks. Now, let’s look at a few of the most common manifest file configurations.

Naming Android Packages

You define the details of the application within the scope of the <manifest> tag. This tag has a number of essential attributes, such as the application package name. Set this value using the package attribute, as follows:

<manifest

xmlns:android="http://schemas.android.com/apk/res/android"

package="com.androidbook.hellokindle"

android:versionCode="1"

android:versionName="1.0.1">

Versioning an Application

Manifest version information is used for two purposes:

• To organize and keep track of application features

• To manage application upgrades

For this reason, the <manifest> tag has two separate version attributes: a version name and a version code.

Setting the Version Name

The version name is the traditional versioning information, used to keep track of application builds. Smart versioning is essential when publishing and supporting applications. The <manifest> tag android:versionName attribute is a string value provided to keep track of the application build number. For example, the HelloKindle project has the version name 1.0.1. The format of the version name field is up to the developer. However, this field is visible to the user.

Setting the Version Code

The version code allows the Android platform to programmatically upgrade and downgrade an application. The <manifest> tag android:versionCode attribute is an whole number integer value that the Android platform and Android marketplaces use to manage application upgrades and downgrades. android:versionCode generally starts at a value of 1. This value must be incremented with each new version of the application deployed to users. The version code field is not visible to the user and need not stay in sync with the version name. For example, an update might have a version name of 1.0.2, but the version code would be incremented to 2.

Setting the Minimum Android SDK Version

Android applications can be compiled for compatibility with several different SDK versions. You use the <uses-sdk> tag to specify the minimum SDK required in order for the application to build and run properly. The android:minSdkVersion attribute of this tag is an integer representing the minimum Android SDK version required. Table 5.1 shows the Android SDK versions available for shipping applications.

Table 5.1 Relevant Android SDK Versions for the Kindle Fire

For example, in the HelloKindle project, you specified that the minimum SDK as Android 2.3.3 SDK (as API Level 10, which is also 2.3.4, which is what the Kindle Fire runs):

<uses-sdk

android:minSdkVersion="10"

android:targetSdkVersion="10" />

Each time a new Android SDK is released, you can find the SDK version number in the SDK release notes. This is often referred to as the API Level within the tools, especially the Android SDK and AVD Manager. For an up-to-date list of the available API Levels, see http://goo.gl/n0fUZ. The value need not be a number, as witnessed by the Honeycomb Preview SDK with an API Level of Honeycomb.

As of this writing, it’s unclear what major SDK updates Kindle Fire will receive. The user interface is already thoroughly customized and much different from any stock version of Android. For users, Kindle Fire doesn’t necessarily need a new version of the Android platform in the future, above and beyond bug fixes.

Naming an Application

The <application> tag android:label attribute is a string representing the application name. You can set this name to a fixed string, as in the following example:

<application android:label="My application name">

You can also set the android:label attribute to a string resource. In the HelloKindle project, you set the application name to the string resource as follows:

<application android:label="@string/app_name">

In this case, the resource string called app_name in the strings.xml file supplies the application name.

Providing an Icon for an Application

The <application> tag attribute called android:icon is a Drawable resource representing the application. There is a default icon (ic_launcher) by default. In the HelloKindle project, you could set a custom application icon to the Drawable resource you include in the project (such icon.png) as follows:

<application android:icon="@drawable/icon">

Providing an Application Description

The <application> tag android:description attribute is a string representing a short description of the application. You can set this name to a string resource:

<application

android:label="My application name"

android:description="@string/app_desc">

The Android system and application marketplaces use the application description to display information about the application to the user.

Setting Debug Information for an Application

The <application> tag android:debuggable attribute is a Boolean value that indicates whether the application can be debugged using a debugger, such as Eclipse. This value is automatically set when you do a debug build in Eclipse. If you manually turn it on, you must reset this value to false before you publish your application. If you forget, the publishing tools usually warn you to adjust this setting.

Setting Other Application Attributes

Numerous other settings appear on the Application tab, but they generally apply only in specific cases, such as when you want link secondary libraries or apply a theme other than the default to your application. There are also settings for handling how the application interacts with the Android operating system. For most applications, the default settings are acceptable.

You will spend a lot of time on the Application tab in the Application Nodes box, where you can register application components—most commonly, each time you register a new activity.

Defining Activities

Recall that Android applications comprise a number of different activities. Every activity must be registered within the Android manifest file by its class name before it can be run on the device. You will therefore need to update the manifest file each time you add a new activity class to an application.

Each activity represents a specific task to be completed, often with its own screen. Activities are launched in different ways, using the Intent mechanism. Each activity can have its own label (name) and icon, but uses the application’s generic label and icon by default.

Registering Activities

You must register each activity in the Application Nodes section of the Application tab. Each activity has its own <activity> tag in the resulting XML. For example, the following XML excerpt defines an activity class called HelloKindleActivity:

<activity android:name=".HelloKindleActivity" />

This activity must be defined as a class within the application package. If needed, you may specific the entire name, including package, with the activity class name. For example, to register a new activity in the HelloKindle project, follow these steps:

1. Open the HelloKindle project in Eclipse.

2. Right-click /src/com.kindlebook.hellokindle and choose New, Class. The New Java Class window opens.

3. Name your new class HelloKindleActivity2.

4. Click the Browse button next to the Superclass field and set the superclass to android.app.Activity. You may need to type several letters of the class/package name before it resolves and you can choose it from the list.

5. Click the Finish button. You see the new class in your project.

6. Make a copy of the main.xml layout file in the /res/layout resource directory for your new activity and name it second.xml. Modify the layout so that you know it’s for the second activity. For example, you could change the text string shown. Save the new layout file.

7. Open the HelloKindleActivity2 class. Right-click within the class and choose Source, Override/Implement Methods.

8. Check the box next to the onCreate(Bundle) method. This method is added to your class.

9. Within the onCreate() method, set the layout to load for the new activity by adding and calling the setContentView(R.layout.second) method. Save the class file.

10. Open the Android manifest file and click the Application tab of the resource editor.

11. In the Application Nodes section of the Application tab, click the Add button and choose the Activity element. Make sure that you are adding a top-level activity. The attributes for the activity are shown in the right side of the screen.

12. Click the Browse button next to the activity Name field. Choose the new activity you created: HelloKindleActivity2.

13. Save the manifest file. Switch to the AndroidManifest.xml tab to see what the new XML looks like.

You now have a new, fully registered HelloKindleActivity2 activity that you can use in your application.

Designating the Launch Activity

You can use an Intent filter to designate an activity as the primary entry point of the application. The Intent filter for launching an activity by default must be configured using an <intent-filter> tag with the MAIN action type and the LAUNCHER category. In the HelloKindle project, the Android project wizard set HelloKindleActivity as the primary launching point of the application:

<activity

android:name=".HelloKindleActivity"

android:label="@string/app_name" >

<intent-filter>

<action

android:name="android.intent.action.MAIN" />

<category

android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

This <intent-filter> tag instructs the Android system to direct all application launch requests to the HelloKindleActivity activity.

Managing Application Permissions

The Android platform is built on a Linux kernel and leverages its built-in system security as part of the Android security model. Each Android application exists in its own virtual machine and operates within its own Linux user account (see Figure 5.6).

Figure 5.6. Simplified Android Platform Architecture from a Security Perspective

Applications that want access to shared or privileged resources must declare those specific permissions in the Android manifest file. This security mechanism ensures that no application can change its behavior on-the-fly or perform any operations without the user’s permission.

Android applications can access their own private files and databases without any special permissions. However, if an application needs to access shared or sensitive resources, it must declare those permissions using the <uses-permission> tag within the Android manifest file. These permissions are managed on the Permissions tab of the Android manifest file resource editor.

For example, to give your application permission to access the network resources, use the following steps:

1. Open the HelloKindle project in Eclipse.

2. Open the Android manifest file and click the Permissions tab of the resource editor.

3. Click the Add button and choose Uses Permission. The Name attribute for the permission is shown in the right side of the screen as a drop-down list.

4. Choose android.permission.INTERNET from the drop-down list.

5. Save the manifest file. Switch to the AndroidManifest.xml tab to see what the new XML looks like.

You have now registered the Internet permission. Your application will be able to access the network APIs, including non-networking APIs that can read from Internet URLs, within the Android SDK without causing security exceptions to be thrown.

Table 5.2 lists some of the most common permissions used by Android applications.

Table 5.2. Common Permissions Used by Kindle Fire Applications

During the application installation process, the user is shown exactly what permissions the application uses. The user must agree to install the application after reviewing these permissions. For a complete list of the permissions used by Android applications, see the android.Manifest.permission class documentation.

Managing Other Application Settings

In addition to the features already discussed in this chapter, a number of other specialized features can be configured in the Android manifest file. For example, if your application requires a hardware keyboard or a touch screen, you can specify these hardware configuration requirements in the Android manifest file.

You must also declare any other application components—such as whether your application acts as a service provider, content provider, or broadcast receiver—in the Android manifest file.

Summary

The Android manifest file (AndroidManifest.xml) exists at the root of every Android project. It is a required component of any application. The Android manifest file can be configured using the manifest file editor built into Eclipse by the ADT plug-in, or you can edit the manifest file XML directly. The file uses a simple XML schema to describe what the application is, what its components are, and what permissions it has. The Android platform uses this information to manage the application and grant its activities certain permissions on the Android operating system.

Exercises

1. Review the complete list of available permissions for Android applications in the Android SDK documentation. You can do this with your local copy of the documentation or online at the Android Developer website (http://goo.gl/II3Uv).

2. Edit the Android manifest file for the HelloKindle application again. Add a second permission (any will do, this is just for practice) to the application. Look up what that permission is used for in the documentation, as discussed in the previous exercise.

3. Add another Activity class to the HelloKindle application and register it within Android manifest. Take this exercise a step further and make this new Activity your application’s default launch activity with the proper intent filter. (More than one activity can be a launcher activity. Each one with the launcher category will appear in the application list with an icon. This is not typical, so you may want to move the intent filter rather than copy it.) Save your changes and run your application.

6. Designing an Application Framework

It’s time to put the skills you learned so far to use and write some code. In this chapter, you design an Android application prototype—the basic framework upon which you will build a full application. Taking an iterative approach, you will add many exciting features to this application over the course of this book. So, let’s begin.

Designing an Android Trivia Game

Social trivia-style games are always popular. They are also an application category where you can, from a development perspective, explore many different features of the Android SDK. So, let’s implement a fairly simple trivia game, and by doing so, learn all about designing an application user interface, working with text and graphics, and, eventually, connecting with other users.

We need a theme for our game. How about reading? In our soon-to-be-viral game, users will be asked whether or not they’ve read a particular book. If they answer yes, they’ll get a point. If they answer no, they’ll get an opportunity to buy the book to read and improve their score.

The user with the highest score is the most well read and cultured. Let’s call the game Have You Read That?.

Determining High-Level Game Features

First, we need to roughly sketch out what we want this application to do. Imagine what features a good application should have and what features a trivia application will need. In addition to the game question screen, the application will likely need the following:

• A splash sequence that displays the app name, version, and developer

• A way to view scores

• An explanation of the game rules

• A way to store game settings

You also need a way to transition between these different features. One way to do this is to create a traditional main menu screen that the user can use to navigate throughout the application.

Reviewing these requirements, we find that we need six primary screens within the Have You Read That? application:

• Startup screen

• Main menu screen

• Game play screen

• Settings screen

• Scores screen

• Help screen

These six screens make up the core user interface for the Have You Read That? application.

Determining Activity Requirements

Each screen of the Have You Read That? application will have its own Activity class. Figure 6.1 shows the six activities required, one for each screen.

Figure 6.1. Rough Design of the Activity Workflows in the Have You Read That? Application

A good design practice is to implement a base Activity class with shared components, which we’ll simply call QuizActivity. You will employ this practice as you define the activities needed by the Have You Read That? game:

• QuizActivity—Derived from android.app.Activity, this is the base class. Here, you define application preferences and other application-wide configuration and shared functionality.

• QuizSplashActivity—Derived from QuizActivity, this class represents the splash screen.

• QuizMenuActivity—Derived from QuizActivity, this class represents the main menu screen.

• QuizHelpActivity—Derived from QuizActivity, this class represents the help screen.

• QuizScoresActivity—Derived from QuizActivity, this class represents the scores screen.

• QuizSettingsActivity—Derived from QuizActivity, this class represents the settings screen.

• QuizGameActivity—Derived from QuizActivity, this class represents the game screen.

Determining Screen-Specific Game Features

Now, it’s time to define the basic features of each activity in the Have You Read That? application.

Defining Splash Screen Features

The splash screen serves as the initial entry point for the Have You Read That? game. Its functionality should be encapsulated within the QuizSplashActivity class. This screen should do the following:

• Display the name and version of the application

• Display an interesting graphic or logo for the game

• Transition automatically to the main menu screen after a period of time

Figure 6.2 shows a hand-drawn mockup of the splash screen.

Figure 6.2. The Have You Read That? Splash Screen

Defining Main Menu Screen Features

The main menu screen serves as the main navigational screen in the game. This screen displays after the splash screen and requires the user to choose where to go next. Its functionality should be encapsulated within the QuizMenuActivity class. This screen should do the following:

• Automatically display after the splash screen

• Allow the user to choose Play Game, Settings, Scores, or Help

Figure 6.3 shows a hand-drawn mockup of the main menu screen.

Figure 6.3. The Have You Read That? Main Menu Screen

Defining Help Screen Features

The help screen tells the user how to play the game. Its functionality should be encapsulated within the QuizHelpActivity class. This screen should do the following:

• Display help text to the user and enable the user to scroll through text

• Provide a method for the user to suggest new questions

Figure 6.4 shows a hand-drawn mockup of the help screen.

Figure 6.4. The Have You Read That? Help Screen

Defining Scores Screen Features

The scores screen allows the user to view game scores. Its functionality should be encapsulated within the QuizScoresActivity class. This screen should do the following:

• Display top score statistics

• Show the latest score if the user is coming from the game screen

Figure 6.5 shows a hand-draw mockup of the scores screen.

Figure 6.5. The Have You Read That? Scores Screen

Defining Settings Screen Features

The settings screen allows users to edit and save game settings, including username and other important features. Its functionality should be encapsulated within the QuizSettingsActivity class. This screen should do the following:

• Allow the user to input game settings

• Allow the user to invite friends to play

Figure 6.6 shows a hand-drawn mockup of the basic settings screen.

Figure 6.6. The Have You Read That? Settings Screen

Defining Game Screen Features

The game screen displays the trivia quiz. Its functionality should be encapsulated within the QuizGameActivity class. This screen should do the following:

• Display a series of yes/no questions

• Handle input and keep score and state of the quiz

• Transition to the scores screen when the user finishes playing

Figure 6.7 shows a hand-drawn mockup of the game screen.

Figure 6.7. The Have You Read That? Game Screen

Implementing an Application Prototype

Now that you have a rough idea what the Have You Read That? application will do and how it will look, it’s time to start coding. This involves the following steps:

1. Creating a new Android project in Eclipse

2. Adding some application resources, including strings and graphics

3. Creating a layout resource for each screen

4. Implementing a Java class (derived from the Activity class) for each screen

5. Creating a set of application-wide preferences for use in all activities

Reviewing the Accompanying Source Code

Because of length limitations and other practical reasons, we cannot provide full code listings in every chapter of this book—they would take more than an chapter to review and be incredibly repetitive. Instead, we provide inline code excerpts based on the Android topic at hand and provide the complete Java source code project for each chapter (denoted by the project name, package name, and application icon) on the accompanying book CD, as well as online at the publisher’s website (http://www.informit.com/title/9780672335693) and the authors’ website (http://goo.gl/fYC7v).

These source files are not meant to be the “answers” to a test. The full source code is vital for providing context and complete implementations of the topics discussed in each chapter. We expect readers will follow along with the source code for a given chapter and, if they feel inclined, they can build their own incarnation of the Have You Read That? application in parallel. The full source code helps give context to developers less familiar with Java or mobile topics. Also, there may be times when the source code does not exactly match the code provided in the book—this is normally because we strip many comments, error checking, and exception handling from book code, again for readability and length.

For example, for Chapter 6 code, the source code Eclipse project name is HYRT_Chapter6, with a package name of com.kindlebook.hyrt.chapter6, and an icon that clearly indicates the chapter number (6). This allows you to keep multiple projects in Eclipse and install multiple applications on a single device without conflicts or naming clashes. However, if you are building your own version in parallel, you likely will only have one version-one Eclipse project and one application you revise and improve in each chapter, using the downloaded project for reference.

Creating a New Android Project

You can begin creating a new Android project for your application by using the Eclipse Android project wizard.

The project has the following settings:

• Project name—HYRT (Note: For this chapter’s source code, this chapter’s project is named BTDT_Hour6.)

• Build target—API Level 10 (Android Open Source Project as vendor)

• Application name—Have You Read That?

• Package name—com.kindlebook.hyrt (Note: For this chapter’s source code, the package is actually named com.kindlebook.hyrt.chapter6.)

• Create activity—QuizSplashActivity

Using these settings, you can create the basic Android project. However, you need to make a few adjustments.

Adding Project Resources

The Have You Read That? project requires some additional resources. Specifically, you need to add a Layout file for each activity and a text string for each activity name, and you need to change the application icon to something more appropriate.

Adding String Resources

Begin by modifying the strings.xml resource file. Delete the hello string and create six new string resources—one for each screen. For example, create a string called help with a value of "Help Screen". When you are done, the strings.xml file should look like this:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string

name="app_name">Have You Read That?</string>

<string

name="help">Help Screen</string>

<string

name="menu">Main Menu Screen</string>

<string

name="splash">Splash Screen</string>

<string

name="settings">Settings Screen</string>

<string

name="game">Game Screen</string>

<string

name="scores">Scores Screen</string>

</resources>

Adding Layout Resources

Next, you need layout resource files for each activity. Begin by renaming the main.xml layout to splash.xml. Then, copy the splash.xml file five more times, resulting in one layout for each activity: game.xml, help.xml, menu.xml, scores.xml, and settings.xml.

You may notice that there is an error in each Layout file. This is because the TextView control in the layout refers to the @string/hello string, which no longer exists. For each layout file, you need to use the Eclipse layout editor to change the String resource loaded by the TextView control. For example, game.xml needs to replace the reference to @string/hello with the new string you created, called @string/game. Now, when each layout loads, it displays the screen it is supposed to represent.

Adding Drawable Resources

While you are adding resources, you should change the icon for your application to something more appropriate. To do this, create a 48x48 pixel PNG file called ic_launcher.png (ic for icon, launcher for the launcher screen) and add this resource file to the /drawable-mdpi resource directory. This replaces the default ic_launcher.png file.

For the Kindle Fire source code, only the /drawable-mdpi directory matches the density of the Kindle Fire screen. However, even if you created four differently sized icons to support different types of device screens and placed them in the four main drawable resource directories (/drawable-ldpi, /drawable-mdpi, /drawable-hdpi, and /drawable-xhdpi), only a single reference to the icon is required. Just make sure that all the icons are named identically. This enables the Android operating system to choose the most appropriate icon version for the device. Note that if you don’t create the other three icons because you’re only targeting the Kindle Fire, Android Lint will give warnings about the missing icons.

Launcher Icons on Kindle Fire

Applications displayed on the Kindle Fire home screen do not use standard launcher icons. Instead, the large icons come from an Amazon web service tied to the images you upload to Amazon Appstore. When the application is not installed by downloading it via Amazon’s Appstore, these images are not available. In this scenario, the home screen uses the launcher icon supplied in the application package, as described here.

Implementing Application Activities

To implement a base Activity class, simply copy the source file called QuizSplashActivity.java. Name this new class file QuizActivity and save the file. This class should look simple for now:

package com.kindlebook.hyrt;

import android.app.Activity;

public class QuizActivity extends Activity {

public static final String GAME_PREFERENCES = "GamePrefs";

}

You will add to this class later. Next, update the QuizSplashActivity class to extend from the QuizActivity class instead of directly from the Activity class.

Creating the Rest of the Application Activities

Now, perform the same steps five more times, once for each new activity: QuizMenuActivity, QuizHelpActivity, QuizScoresActivity, QuizSettingsActivity, and QuizGameActivity. Note the handy way that Eclipse updates the class name when you copy a class file. You can also create class files by right-clicking the package name com.kindlebook.hyrt and choosing New Class. Eclipse presents a dialog where you can fill in class file settings.

Note that there is an error in each Java file. This is because each activity is trying to load the main.xml layout file—a resource which no longer exists. You need to modify each class to load the specific layout associated with that activity. For example, in the QuizHelpActivity class, modify the setContentView() method to load the layout file you created for the help screen, as follows:

setContentView(R.layout.help);

You need to make similar changes to the other activity files, such that each call to setContentView() loads the corresponding layout file.

Updating the Android Manifest File

You now need to make some changes to the Android manifest file. First, modify the application icon resource to point at the @drawable/ic_launcher icon you created. Second, you need to register all of your new activities in the manifest file so that they will run properly. Finally, verify that you have QuizSplashActivity set as the default activity to launch.

Creating Application Preferences

The Have You Read That? application needs a simple way to store some basic state information and user data. You can use Android’s shared preferences (android.content.SharedPreferences) to add this functionality.

You can access shared preferences, by name, from any activity within the application. Therefore, declare the name of your set of preferences in the base class QuizActivity so that they are easily accessible to all subclasses:

public static final String GAME_PREFERENCES = "GamePrefs";

Here are the steps to take to save shared preferences:

1. Use the getSharedPreferences() method to retrieve an instance of a SharedPreferences object within your Activity class.

2. Create a SharedPreferences.Editor object to modify preferences.

3. Make changes to the preferences by using the editor.

4. Commit the changes by using the commit() method in the editor.

You don’t need to do this now; we’ll add preferences when we need them.

Saving Specific Shared Preferences

Each preference is stored as a key/value pair. Preference values can be the following types:

• Boolean

• Float

• Integer

• Long

• String

After you decide what preferences you want to save, you need to get an instance of the SharedPreferences object and use the Editor object to make the changes and commit them. In the following sample code, when placed within your Activity class, illustrates how to save two preferences—the user’s name and age:

import android.content.SharedPreferences;

// ...

SharedPreferences settings =

getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);

SharedPreferences.Editor prefEditor = settings.edit();

prefEditor.putString("UserName", "JaneDoe");

prefEditor.putInt("UserAge", 22);

prefEditor.commit();

You can also use the shared preferences editor to clear all preferences by using the clear() method and remove specific preferences by name by using the remove() method.

Retrieving Shared Preferences

Retrieving shared preference values is even simpler than creating them because you don’t need an editor. The following example shows how to retrieve shared preference values within your Activity class:

SharedPreferences settings =

getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);

if (settings.contains("UserName") == true) {

// We have a user name

String user = Settings.getString("UserName", "Default");

}

You can use the SharedPreferences object to check for a preference by name, retrieve strongly typed preferences, or retrieve all the preferences and store them in a map.

Although you have no immediate needs for shared preferences yet in Have You Read That?, you now have the infrastructure set up to use them as needed within any of the activities within your application. This will be important later when you implement each activity in full in subsequent hours.

Running the Game Prototype

You are almost ready to run and test your application. But first, you need to create a debug configuration for your new project within Eclipse.

Creating a Debug Configuration

Each new Eclipse project requires a debug configuration. Be sure to set the preferred AVD for the project to one that is compatible with the Google APIs and within the API Level target range you set in your application (check the Manifest file if you are unsure). If you do not have one configured appropriately, simply click the Android SDK and AVD Manager button in Eclipse. From here, determine which AVDs are appropriate for the application and create new ones, as necessary.

Launching the Prototype in the Emulator

It’s time to launch the Have You Read That? application in the Android emulator. You can do this by using the little bug icon in Eclipse or by clicking the Run button on the debug configuration you just created.

As you see in Figure 6.8, the application does very little so far. It has a pretty icon, which a user can click to launch the default activity, QuizSplashActivity. This activity displays its TextView control, informing you that you have reached the splash screen. There is no real user interface to speak of yet for the application, and you still need to wire up the transitions between the different activities. However, you now have a solid framework upon which to build. In the next few hours, you will flesh out the different screens and begin to implement game functionality.

Figure 6.8. The Splash Screen for Have You Read That?

Exploring the Prototype Installation

The Have You Read That? application does little so far, but you can use tools on the Android emulator to peek at all you’ve done so far:

• Application Manager—This is helpful for determining interesting information about an application. In the emulator, navigate to the home screen, click the Menu button and choose Settings, Applications, Manage applications, and then choose the Have You Read That? application from the list of applications. Here, you can see some basic information about the application, including storage and permissions used, and information about the cache and so on. You can also kill the app or uninstall it.

• Dev Tools—This tool helps you inspect the application in more detail. In the emulator, pull up the application drawer, launch the Dev Tools application, and choose Package Browser. Navigate to the package name, com.kindlebook.hyrt. This tool reads information out of the manifest and allows you to inspect the settings of each activity registered, among other features.

Of course, you can also begin to investigate the application by using the DDMS perspective of Eclipse. For example, you could check out the application directory for the com.kindlebook.hyrt package on the Android file system. You could also step through the code of QuizSplashActivity.

Summary

In this chapter, you built a basic prototype on which you can build in subsequent chapters. You designed a prototype and defined its requirements in some detail. Then, you created a new Android project, configured it, and created an activity for each screen. You also added custom layouts and implemented shared preferences for the application.

Exercises

1. Add a log message to the onCreate() method of each Activity class in your Have You Read That? application prototype. For example, add an informational log message such as “In Activity QuizSplashActivity” to the QuizSplashActivity class.

2. Add an additional application preference string to the application prototype: lastLaunch. In the onCreate() method of QuizSplashActivity class, make the following changes: Whenever this method runs, read the old value the lastLaunch preference and print its value to the log output. Then, update the preference with the current date and time.

Hints: The default Date class (java.util.Date) constructor can be used to get the current date and time, and the SimpleDateFormat class (java.text.SimpleDateFormat) can be used to format date and time information in various string formats. See the Android SDK for complete details on these classes.

3. Sketch out an alternate design for the Have You Read That? application. Consider options, such as not including a main menu screen. Look over similar applications in the Android Market for inspiration. You can post links to alternative designs for the application on our book website (http://goo.gl/gPguA) or email them directly to us at androidwirelessdev+hyrt@gmail.com.

Developer's Library

ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS

Android™ Wireless Application Development, Third Edition

Volume I: Android Essentials

Lauren Darcey, Shane Conder

ISBN-13: 978-0-321-81383-1

The iOS 5 Developer's Cookbook, Third Edition

Erica Sadun

ISBN-13: 978-0-321-83207-8

The Android Developer's Cookbook

James Steele, Nelson To

ISBN-13: 978-0-321-74123-3

Other Developer's Library Titles

Developer’s Library books are available at most retail and online bookstores. For more information or to order direct, visit our online bookstore at informit.com/store

Online editions of all Developer’s Library titles are available by subscription from Safari Books Online at safari.informit.com.

Developer’s Library

informit.com/devlibrary