Android How to Program
By Paul J. Deitel
Email: Richard@qwconsultancy.com
1
Introduction to Android
Objectives In this chapter you’ll be introduced to: ■
The history of Android and the Android SDK.
■
The Android Market for apps.
■
A review of basic objecttechnology concepts.
■
Key software for Android app development, including the Android SDK, the Java SDK and Eclipse integrated development environment (IDE).
■
Important Android documentation.
■
Test-driving an Android app that enables you to draw on the screen.
■
The Deitel online Android Resource Centers.
2
Chapter 1
Introduction to Android
Self -Review Exercises 1.1
Fill in the blanks in each of the following statements: —a 34-company consortium initially and many a) In November 2007, the more now—was formed to develop Android, driving innovation in mobile technology and improving the user experience while reducing costs. ANS: Open Handset Alliance. Plugin, you can create, run, test and debug Android b) Using Eclipse with the apps quickly and conveniently, and you can visually design your user interfaces. ANS: Android Development Tools (ADT). involvc) Multitouch screens allow you to control your Android device with ing one touch or multiple simultaneous touches. ANS: gestures. d) You can create , which enable you to rapidly develop apps by combining the complementary web services of several organizations, possibly with information feeds of various types (such as RSS, Atom, XML, JSON and others). ANS: mashups. contains APIs for audio focus, auto-scanning files to the mee) The Andriod dia database (e.g., audio and video files), detecting sound loading completion, autopause and auto-resume of audio playback, and more. ANS: Media framework. , which are named groups of related, pref) Android uses a collection of defined classes. ANS: packages. gives access to Android content providers. g) The package ANS: android.provider. , included in the Android SDK, allows you to run Android apps in a h) The simulated environment within Windows, Mac OS X or Linux. ANS: Android emulator. i) Almost any noun can be reasonably represented as a software object in terms of (e.g., name, color and size) and behaviors (e.g., calculating, moving and communicating). ANS: attributes. houses the methods that perform its tasks. j) A program unit called a ANS: class. that tells a method of k) You send messages to an object. Each message is a the object to perform its task. ANS: method call.
1.2
State whether each of the following is true or false. If false, explain why. a) One benefit of developing Android apps is that the operating system is proprietary to Google. ANS: False. The operating system is open source and free. b) The openness of the Android platform discourages innovation. ANS: False. The openness of the platform spurs rapid innovation. c) The Android Development Tools (ADT) Plugin for Eclipse—an extension to the Eclipse IDE—allows you to create, run and debug Android apps, export them for distribution (e.g., upload them to Android Market), and more. ANS: True. d) You can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves time and effort. ANS: True.
Exercises
3
e) Attributes are specified by the class’s methods. ANS: False. Attributes are specified by the class’s instance variables. f) Objects may communicate with one another, but they’re normally not allowed to know how other objects are implemented—implementation details are hidden within the objects themselves. ANS: True.
Exercises 1.3
Fill in the blanks in each of the following statements: —the world’s most widely used programa) Android apps are developed with ming language, a logical choice because it’s powerful, free and open source. ANS: Java. -driven, you’ll write apps that respond to varb) GUI programming in Java is ious user interactions such as screen touches and keystrokes. ANS: event. . c) Touching the screen and holding your finger in position is called a ANS: long press. d) Touching and quickly flicking your finger across the screen in the direction you’d like . to move is called a ANS: fling. framework to add drag-and-drop capabilities in an app. e) Use the ANS: DragEvent. f) ANS:
g) As a marketing strategy, many app developers offer basic versions of their apps for free so users can determine whether they like them, then purchase more feature-rich ver” strategy. sions.This is called the “ ANS: lite. , which deh) Before running an app in the emulator, you'll need to create an fines the characteristics of the device on which you want to test, including the hardware, system image, screen size, data storage and more. ANS: Android Virtual Device. which houses the program statei) Performing a task in a program requires a ments that actually perform its tasks. ANS: method. j) You must build an object of a class before a program can perform the tasks that the . class’s methods define. The process of doing this is called ANS: instantiation. helps you build more reliable and effective systems, because existing classes k) and components often have gone through extensive testing, debugging and performance tuning. ANS: Reuse. (i.e., wrap) attributes and methods into objects—an object’s attril) Classes butes and methods are intimately related. ANS: encapsulate. —the m) A new class of objects can be created quickly and conveniently by new class absorbs the characteristics of an existing one, possibly customizing them and adding unique characteristics of its own. ANS: inheritance.
4
Chapter 1
Introduction to Android
n) Unlike actual buttons on a device, buttons appear on the device’s touch screen. ANS: soft. o) Colors are defined using the RGBA color scheme in which the red, green, blue and components are specified by integers in the range 0–255. ANS: alpha. 1.4
State whether each of the following is true or false. If false, explain why. a) The vast majority of Android development is done in C++. ANS: False. The vast majority of Android development is done in Java. b) Microsoft Visual Studio is the recommended integrated development environment for Android development, though developers may also use a text editor and command-line tools to create Android apps. ANS: False. Eclipse is the recommended integrated development environment for Android development, though developers may also use a text editor and command-line tools to create Android apps. c) You can reproduce on the emulator most of the Android gestures and controls using your computer’s keyboard and mouse. ANS: True. d) Objects, or more precisely the classes objects come from, are essentially reusable software components. ANS: True.
Android Market and App Business Issues
2 Objectives In this chapter you’ll be introduced to: ■
Characteristics of great Android apps.
■
User interface guidelines for designing your apps.
■
Registering for Android Market.
■
Submitting your apps to Android Market.
■
Pricing your apps and the benefits of free vs. paid apps.
■
In-app billing.
■
Launching Android Market from within an app.
■
Marketing and monetizing your apps.
■
Other Android app stores.
■
Other popular mobile and Internet app platforms to which you can port your apps.
■
Android humor.
2
Chapter 2
Android Market and App Business Issues
Self Review Exercises 2.1
Fill in the blanks in each of the following statements: is a reverse chronological history of all of the activities, allowing the a) The user to navigate to the previous activity using the Back button. ANS: activity stack. b) Selecting the Context menu from within a message in the Messaging app (by touching —within the message on a touchscreen) brings and holding—also called up a menu of options specific to that message, including Select all, Select text, Cut all, Copy all, Paste and Input method. ANS: long pressing. merchant account. c) To sell your apps on Android Market, you’ll need a ANS: Google Checkout d) Before uploading your app to a device, to Android Market or to other app marketplaces, that you must digitally sign the .apk file (Android app package file) using a identifies you as the author of the app. ANS: digital certificate. allows you to manage your account and your apps, e) The Android Market check users’ star ratings for your apps (0 to 5 stars), track the overall number of installs of each app and the number of active installs (installs minus uninstalls). ANS: Developer Console.
2.2
State whether each of the following is true or false. If false, explain why. a) Android provides four generalized screen sizes (small, normal, large and extra large) and densities (low, medium, high and extra high), making it easier for you to design apps that work on multiple screens. ANS: True. b) A splash screen usually resembles the app’s user interface—often just an image of the background elements of the GUI. ANS: True. c) When an app works perfectly using the emulator on your computer, it will run on your Android device. ANS: False. Although the app might work perfectly using the emulator on your computer, problems could arise when running it on a particular Android device. d) You might use a licensing policy to limit how often the app checks in with the server, how many simultaneous device installs are allowed, and what happens when an unlicensed app is identified. ANS: True. e) The title of your app as it will appear in Android Market must be unique among all Android apps. ANS: False. The title of your app as it will appear in Android Market does not need to be unique among all Android apps. f) According to a study by app store analytics firm Distimo (www.distimo.com/), the average price of paid Android apps is around $36.20. ANS: False. According to the study, the average price of paid Android apps is around $3.62 (the median is $2.72). g) According to Google, apps that use in-app billing earn profoundly more revenue than paid apps alone. ANS: True.
Exercises
3
h) If you choose to sell your apps through other app marketplaces, several third-party mobile payment providers can enable you to build in-app purchase into your apps using APIs from mobile payment providers. ANS: True.
Exercises 2.3
Fill in the blanks in each of the following statements: are displays of timely information on the user’s Home screen, such as the a) current weather, stock prices and news. ANS: Widgets. are reusable components used to build an app’s user interface. They perb) form actions such as searching, viewing information and dialing a phone number. A separate one is often associated with each different screen of an app. ANS: Activities. menu—accessed through the device’s Menu button—provides actions c) The and operations for the app’s current screen. ANS: Options. —an image that will be displayed d) If your app takes a while to load, use a when the icon is tapped on the screen so that the user sees an immediate response while waiting for the app to load. ANS: splash screen. file, referred to as the manifest, provides information needed to run e) The your app in Android and to filter it properly in Android Market. ANS: AndroidManifest.xml. is an agreement through which you license your software to the user. f) An It typically stipulates terms of use, limitations on redistribution and reverse engineering, product liability, compliance with applicable laws and more. ANS: End User License Agreement (EULA). , which is installed with the ADT Plugin for Eclipse, helps you debug g) The your apps running on actual devices. ANS: Dalvik Debug Monitor Service (DDMS). is the number one reason why h) According to a recent study by AdMob, users purchase a paid app. ANS: upgrading from the “lite” version.
2.4
State whether each of the following is true or false. If false, explain why. a) You must design your app for every possible screen size and density. ANS: False. You do not need (nor would you want to try) to design your app for every possible screen size and density. b) Use a BroadcastReceiver to easily share data from your app with other apps on the device. ANS: False. Use a ContentProvider to easily share data from your app with other apps on the device. c) The functionality of these sensors—accelerometer, barometer, compass, light sensor and proximity sensor—is not available on the emulator. ANS: True.
4
Chapter 2
Android Market and App Business Issues
d) You should “obfuscate” any apps you upload to Android Market to encourage reverse engineering of your code. ANS: False. You should “obfuscate” any apps you upload to Android Market to prevent reverse engineering of your code and further protect your apps. The ProGuard tool— which runs when you build your app in release mode—shrinks the size of your .apk file and optimizes and obfuscates the code. e) According to AdMob (www.admob.com/), Android users who purchase apps download an average of five apps per month. ANS: True. f) There are now more free apps for Android than iPhone. ANS: True. g) Approximately 90% of apps on Android Market are free, and they comprise the vast majority of downloads. ANS: False. Approximately 57% of apps on Android Market are free, and they comprise the vast majority of downloads. h) According to comScore, YouTube and Facebook each account for 10% of all time spent online worldwide. ANS: False. According to comScore, YouTube accounts for 10% of all time spent online worldwide and Facebook accounts for a remarkable 17%.
3 Objectives In this chapter you’ll: ■
Learn the basics of the Eclipse IDE for writing, running and debugging your Android apps.
■
Create an Eclipse project to develop a new app.
■
Design a GUI visually (without programming) using the ADT (Android Development Tools) visual layout editor.
■
Edit the properties of GUI components.
■
Build a simple Android app and execute it on an Android Virtual Device (AVD).
Welcome App
Self Review Exercises
2
Self Review Exercises 3.1
Fill in the blanks in each of the following statements: a) Layout files are considered app resources and are stored in the project’s folder. GUI layouts are placed within that folder’s layout subfolder. ANS: res. so that it disb) When designing an Android GUI, you typically want it to be plays properly on various devices. ANS: scalable. indicates that a resource should not be scaled c) The Android pixel density regardless of screen density. ANS: nodpi. d) To change the background color to white, locate the Background property in the Prop. erties window and set its value to ANS: #FFFFFF. your app by creating additional XML resource files for e) You can easily string resources in other languages. ANS: localize. and f) The two measurement units for density independent pixels are . ANS: dp and dip. g) Setting the android:layout_width and android:layout_height attributes to indicates that the view should be just large enough to fit its content, including its padding values that specify the spacing around the content. ANS: wrap_content. h) To run an app in an Android Virtual Device (AVD), right click the app’s root node in window and select Run As > Android Application. Eclipse in the ANS: Package Explorer.
3.2
State whether each of the following is true or false. If false, explain why. a) (True/False) The Eclipse IDE and the ADT (Android Development Tools) Plugin are the most popular tools for creating and testing Android apps. ANS: True. b) (True/False) A LinearLayout always arranges GUI components in a line horizontally. ANS: False. LinearLayout arranges GUI components in a line horizontally or vertically. c) (True/False) The layout RelativeLayout arranges components relative to one another or relative to their parent container. ANS: True. d) (True/False) Android also supports alpha (transparency) values in the range 0–100, where 0 represents completely transparent and 100 represents completely opaque. ANS: False. Android also supports alpha (transparency) values in the range 0–255, where 0 represents completely transparent and 255 represents completely opaque. e) (True/False) Setting the android:layout_centerHorizontal attribute to "yes" centers the component horizontally in the layout. ANS: False. Setting the android:layout_centerHorizontal attribute to "true" centers the component horizontally in the layout.
3
Chapter 3
Welcome App
Exercises 3.3
Fill in the blanks in each of the following statements: allows you to build GUIs using drag-and-drop techniques. a) The ADT’s ANS: Visual Layout Editor. b) For an Android app that you create with Eclipse, the GUI layout is stored in an XML , by default. file called ANS: main.xml. (layout) with a black c) The default GUI for a new Android app consists of a background. ANS: LinearLayout. (layout) allocates space for a single component. You can add more d) The than one component to this layout, but each will be displayed from the layout’s upperleft corner. The last component added will appear on top. ANS: FrameLayout. e) Your project’s res folder contains three subfolders for images—drawable-hdpi (high density), drawable-mdpi (medium density) and drawable-ldpi (low density). These densities. folders store images with different ANS: pixel. , f) If you wish to use alpha values, you can specify the color in the format where the first two hexadecimal digits represent the alpha value. ANS: #AARRGGBB. g) The documentation for supporting multiple screen sizes recommends that you use density-independent pixels for the dimensions of GUI components and other screen elefor font sizes. ments and ANS: scale-independent pixels h) One density-independent pixel is equivalent to one pixel on a screen with 160 dpi (dots per inch). On a screen with 240 dpi, each density-independent pixel will be scaled by a . factor of ANS: 240/160 (i.e., 1.5). i) On a screen with 120 dpi, each density-independent pixel is scaled by a factor of . So, the same component that’s 100 density-independent pixels wide will be 75 actual pixels wide. ANS: 120/160 (i.e., .75). j) Specifying the value match_parent for both the android:layout_width and android:layout_height attributes, causes the layout to occupy the entire width and element—that is, the one in which this layout is nested. height of layout’s ANS: parent. attribute to "center" centers the text in the TextView. k) Setting the ANS: android:gravity. and XML codl) Android development is a combination of GUI design, and ing. ANS: Java.
3.4
State whether each of the following is true or false. If false, explain why. a) (True/False) For images to render nicely, a high-pixel-density device needs lower-resolution images than a low-pixel-density device. ANS: False. For images to render nicely, a high-pixel-density device needs higher-resolution images than a low-pixel-density device.
Exercises
4
b) (True/False) Every color can be created from a combination of red, green and blue components called RGB values—each is an integer in the range 0–256. ANS: False. Every color can be created from a combination of red, green and blue components called RGB values—each is an integer in the range 0–255. c) (True/False) It’s considered a good practice to “externalize” strings, string arrays, images, colors, font sizes, dimensions and other app resources so that you, or someone else on your team, can manage them separately from your application’s code. ANS: True. d) (True/False) You can use the Visual Layout Editor to create a working Android app without writing any code. ANS: True. 3.5 (Scrapbooking App) Find four open source images of famous landmarks using websites such as Flickr. Create an app in which you arrange the images in a collage. Add text that identifies each landmark.
4 Objectives In this chapter you’ll: ■
Design a GUI using a TableLayout.
■
Use the ADT Plugin’s Outline window in Eclipse to add GUI components to a TableLayout.
■
Directly edit the XML of a GUI layout to customize properties that are not available through the Visual Layout Editor and Properties window in Eclipse.
■
Use TextView, EditText and SeekBar GUI components.
■
Use Java object-oriented programming capabilities, including classes, anonymous inner classes, objects, interfaces and inheritance to create an Android app.
■
Programmatically interact with GUI components to change the text that they display.
■
Use event handling to respond to user interactions with an EditText and a SeekBar.
Tip Calculator App
Self-Review Exercises
2
Self-Review Exercises 4.1
Fill in the blanks in each of the following statements: —often called a text box or text field in other GUI technologies—is a a) An subclass of TextView that can display text and accept text input from the user. ANS: EditText.
b) Use a
to arrange GUI components into rows and columns.
ANS: TableLayout.
c) When working with more complex layouts like TableLayouts, it’s difficult to see the nested structure of the layout and to place components in the correct nested locations window makes these tasks easier beusing the Visual Layout Editor. The cause it shows the nested structure of the GUI. So, in a TableLayout, you can select the appropriate row and add a GUI component to it. ANS: Outline.
d) Class
of package android.os represents an app’s state information.
ANS: Bundle.
of package android.text to respond to events e) You implement interface when the user interacts with an EditText component. ANS: TextWatcher.
f) A separate is typically associated with each screen of an app. ANS: activity. is called by the system when an Activity is starting—that is, g) The method when its GUI is about to be displayed so that the user can interact with the Activity. ANS: onCreate. h) As you build your app’s GUI and add resources (such as strings in the strings.xml file or GUI components in the main.xml file) to your app, the ADT Plugin tools generate that contains nested static classes representing each type of a class named resource in your project’s res folder. ANS: R.
i) Class (nested in class R)—contains constants for any drawable items, such as images, that you put in the various drawable folders in your app’s res folder. ANS: R.drawable.
j) Class
(nested in class R)—contains constants for each String in the
strings.xml file. ANS: R.string
k) Once the layout is inflated, you can get references to the individual widgets using Acmethod. This method takes an int constant for a specific view tivity’s (that is, a GUI component) and returns a reference to it. ANS: findViewById. and l) You use a TableLayout to arrange the GUI components into . ANS: rows, columns. 4.2
State whether each of the following is true or false. If false, explain why. a) Android requires that you use the GUI component’s class name in each component’s Id property in the XML layout and in each component’s variable name in the Java code. ANS: True. b) You can force an EditText to display a cursor so that the user can’t manipulate the text. ANS: False. You can prevent an EditText from displaying a cursor so that the user can’t manipulate the text.
3
Chapter 4
Tip Calculator App
c) Each component’s Relative weight determines how it should be sized relative to other components. ANS: False. Each component’s Layout weight determines how it should be sized relative to other components. d) As with all Java programs, Android apps have a main method. ANS: False. Android apps don’t have a main method. e) An active (or running) activity is visible on the screen and “has the focus”—that is, it’s in the background. This is the activity the user is interacting with. ANS: False. An active (or running) activity is visible on the screen and “has the focus”— that is, it’s in the foreground. This is the activity the user is interacting with. f) A stopped activity is visible on the screen and is likely to be killed by the system when its memory is needed. ANS: False. A stopped activity is not visible on the screen and is likely to be killed by the system when its memory is needed. g) Method onCreate typically initializes the Activity’s instance variables and GUI components. This method should be as simple as possible so that the app loads quickly. In fact, if the app takes longer than five seconds to load, the operating system will display an ANR (Application Not Responding) dialog—giving the user the option to forcibly terminate the app. ANS: True.
Exercises 4.3
Fill in the blanks in each of the following statements: folda) String literals should be placed in the strings.xml file in the app’s er—especially if you intend to localize your app for use with multiple languages. ANS: res/values. b) You can control whether or not the user can give the focus to an EditText by setting its property. ANS: Focusable.
c) A component’s ponents.
specifies its relative importance with respect to other com-
ANS: Layout weight.
d) Class app.
of package android.app provides the basic lifecycle methods of an
ANS: Activity. of package android.text allows you to change the content and e) Interface markup of text in a GUI. ANS: Editable. of package android.widget to respond to the f) You implement interface user moving the SeekBar’s thumb. ANS: SeekBar.OnSeekBarChangeListener
g) Android apps have four types of components—activities, services, content providers . and ANS: broadcast receivers. h) Throughout its life an activity can be in one of several states—active (or running), . The activity transitions between these states in response to varpaused or ious events. ANS: stopped.
Exercises
4
i) The method is called by the system when the configuration of the device changes during the app’s execution—for example, when the user rotates the device or slides out a keyboard on a device with a hard keyboard. ANS: onSaveInstanceState. (nested in class R)—contains constants for the GUI components in j) Class your XML layout files. ANS: R.id. k) Method setContentView uses a received constant to load the corresponding XML document, which is then parsed and converted into the app’s GUI. This process is known the GUI. as ANS: inflating. 4.4
State whether each of the following is true or false. If false, explain why. a) By default, a Seekbar allows you to select values from 0 to 255. ANS: False. By default, a Seekbar allows you to select values from 0 to 100. b) A GUI component can span multiple columns in a TableLayout. ANS: True. c) If you’ve installed multiple Android SDKs, the ADT Plugin selects the oldest one as the default for design purposes in the Graphical Layout tab—regardless of the SDK you selected when you created the project. ANS: False. If you’ve installed multiple Android SDKs, the ADT Plugin selects the most recent one as the default for design purposes in the Graphical Layout tab—regardless of the SDK you selected when you created the project. d) Every Activity subclass must override the Construct method. ANS: False. Every Activity subclass must override the onCreate method. e) A paused activity is visible on the screen and has the focus. ANS: False. A paused activity is visible on the screen but doesn’t have the focus. f) Time-consuming initializations should be done in a onCreate method instead of the background process. ANS: False. Time-consuming initializations should be done in a background process instead of the onCreate method. g) You use TableRows to create the rows in a TableLayout. ANS: True. h) You override the onStart method to initialize the app when it’s launched. ANS: False. You override the onCreate method to initialize the app when it’s launched.
5
Favorite Twitter® Searches App
Objectives In this chapter you’ll: ■
Enable users to interact with an app via Buttons.
■
Use a ScrollView to display objects that do not fit on the screen.
■
Create GUI components dynamically in response to user interactions by inflating an XML layout.
■
Store key/value pairs of data associated with an app using SharedPreferences.
■
Modify key/value pairs of data associated with an app using SharedPreferences.Editor.
■
Create AlertDialogs with an AlertDialog.Builder.
■
Programmatically open a website in a web browser by using an Intent.
■
Programmatically hide the soft keyboard.
■
Learn about the file AndroidManifest.xml.
2
Chapter 5
Favorite Twitter® Searches App
Self-Review Exercises 5.1
Fill in the blanks in each of the following statements: are typically used to launch activities—they indicate an aca) (Self Review) tion to be performed and the data on which that action is to be performed. ANS: Intents. to handle the events that occur b) (Self Review) We implement interface when the user touches a button on an AlertDialog. ANS: OnClickListener. c) (Self Review) Lengthy data access should never be done in the UI thread; otherwise, the dialog—typically after five seconds of inactivity. app will display an ANS: Application Not Responding (ANR). d) (Self Review) An Intent is a description of an action to be performed with associated . ANS: data. Intents specify an exact Activity class to run in the same e) (Self Review) app. ANS: Explicit. f) (Self Review) When you create the project for each Android app in Eclipse, the ADT file (also known as the app’s manifest), Plugin creates and configures the which describes information about the app. ANS: AndroidManifest.xml. attribute specifies the app’s name. g) (Self Review) The ANS: android:label. element, which specifies h) (Self Review) Within the activity element is the the types of intents the Activity can respond to. ANS: intent-filter.
5.2
State whether each of the following is true or false. If false, explain why. a) (Self Review) (True/False) Extensive input/output should be performed on the UI thread, otherwise that would affect your app’s responsiveness. ANS: False. Extensive input/output should not be performed on the UI thread, since that would affect your app’s responsiveness. b) (Self Review) (True/False) A benefit of defining dimensions as resources is that you can use density-independent pixel (dp or dip) and scale-independent pixel (sp) values, which Android automatically converts to the appropriate pixel values for a given device. ANS: True. c) (Self Review) (True/False) You call toArray (with an empty String array as an argument) on the Set object to convert the Set into an array of Strings. ANS: True.
Exercises 5.3
Fill in the blanks in each of the following statements: is a ViewGroup that can contain other Views (like a layout) and a) (Exercise) A that lets users scroll through content too large to display on the screen. ANS: ScrollView. inflates an XML layout file, thus creating the components d) (Exercise) The specified in the XML. ANS: LayoutInflater.
Exercises
3
e) (Exercise) A layout fills the entire screen if the Layout width and Layout height prop. erties have the value ANS: match_parent. method is called by the system when the app loads, if the f) (Exercise) The app’s process was killed by the operating system while the app was in the background, and the app is then restored, each time the configuration changes, such as when the user rotates the device or opens/closes a physical keyboard. ANS: onCreate. (a static method of class Arrays from package java.util) g) (Exercise) sorts the array in its first argument. ANS: Arrays.sort. objects to configure and create AlertDialogs for dish) (Exercise) You use playing messages to the user. ANS: AlertDialog.Builder. 5.4
State whether each of the following is true or false. If false, explain why. a) (Exercise) (True/False) An Algorithm specifies an action to be performed and the data to be acted upon—Android uses Algorithms to launch the appropriate activities. ANS: False. An Intent specifies an action to be performed and the data to be acted upon— Android uses Intents to launch the appropriate activities. b) (Exercise) (True/False) You implement interface View.OnClickListener of package android.view to specify the code that should execute when the user touches a Button. ANS: True. c) (Exercise) (True/False) The first argument passed to Intent’s constructor is the data to be operated on. ANS: False. The first argument passed to Intent’s constructor is a constant describing the action we wish to perform. d) (Exercise) (True/False) With an explicit Intent, we allow the system to launch the most appropriate Activity based on the type of data. ANS: False. With an implicit Intent, we allow the system to launch the most appropriate Activity based on the type of data. e) (Exercise) (True/False) If you don’t provide your own icon, the app uses the icon that’s supplied by the ADT Plugin when you create the app’s project. ANS: True. f) (Exercise) (True/False) The category element value "android.application.category.LAUNCHER" indicates that this activity should be listed in the application launcher with other apps on the device. ANS: False. The category element value "android.intent.category.LAUNCHER" indicates that this activity should be listed in the application launcher with other apps on the device.
6
Flag Quiz Game App
Objectives In this chapter you’ll: ■
Store String arrays in strings.xml.
■
Store a set of images in subfolders of the assets folder.
■
Use an AssetManager to get a list of all assets in an app.
■
Use random-number generation to vary flag choices.
■
Use a Drawable to display a flag image in an ImageView.
■
Use a tweened animation to shake the displayed flag when the user specifies an incorrect answer.
■
Use a Handler to schedule a future action.
■
Use an ArrayList to hold collections of items and a HashMap to hold name–value pairs.
■
Override Activity’s onCreateOptionsMenu method to create a Menu and MenuItems that enable the
user to configure the app’s options. ■
Use Android’s logging mechanism to log error messages.
2
Chapter 6
Flag Quiz Game App
Self-Review Exercises 6.1
Fill in the blanks in each of the following statements: (package android.cona) Files in the assets folders are accessed via an tent.res), which can provide a list of all of the file names in a specified subfolder of assets and can be used to access each asset. ANS: AssetManager. animation moves a View within its parent. b) A ANS: translate. c) By default, animations in an animation set are applied in parallel, but you can use the attribute to specify the number of milliseconds into the future at which an animation should begin. This can be used to sequence the animations in a set. ANS: android:startOffset. d) To access the app’s assets folder’s contents, a method should get the app’s AssetManager by calling method (inherited indirectly from class ContextWrapper). ANS: getAssets. is a set of styles that specify the appearance of a GUI’s components. e) A ANS: theme.
6.2
State whether each of the following is true or false. If false, explain why. a) We use AnimationUtils static method loadAnimation to load an animation from an XML file that specifies the animation’s options. ANS: True. b) Android does not provide a logging mechanism for debugging purposes. ANS: False. When exceptions occur, you can log them for debugging purposes with Android’s built-in logging mechanism, which uses a circular buffer to store the messages for a short time. c) ImageView attribute android:adjustViewBounds specifies whether or not the ImageView maintains the aspect ratio of its Drawable. ANS: True. d) You load color and String array resources from the colors.xml and strings.xml files into memory by using the Activity’s Resources object. ANS: True.
Exercises 6.3
Fill in the blanks in each of the following statements: is called to a) When the user selects an item from a Menu, Activity method respond to the selection. ANS: onOptionsItemSelected. (package android.os) object to execute a Runb) To delay an action, we use a nable after a specified delay. ANS: Handler. c) We also specify the number of times an animation should repeat with Animation methand perform the animation by calling View method startAnimation od (with the Animation as an argument) on the ImageView. ANS: setRepeatCount. is a collection of animations which make up a larger animation. d) An ANS: animation set. animations which allow you to animate any property of e) Android supports any object. ANS: property.
3 f) For the android:fromXDelta attribute, specifying the value -5%p indicates that the View should move to the by 5% of the parent’s width (indicated by the p). ANS: left. attribute of the application element to apply a theme to the g) We use the application’s GUI. ANS: android:theme. 6.4
State whether each of the following is true or false. If false, explain why. h) You can use the android:screenOrientation attribute to specify that an app should always appear in landscape mode (that is, a vertical orientation). ANS: False. You can use the android:screenOrientation attribute to specify that an app should always appear in portrait mode (that is, a vertical orientation). i) You specify the number of times an animation should repeat with Animation method repeatCount. ANS: False. You specify the number of times an animation should repeat with Animation method setRepeatCount.
7 Objectives In this chapter you’ll: Create a simple game app that’s easy to code and fun to play. ■ Create a custom SurfaceView subclass and use it to display the game’s graphics from a separate thread of execution. ■ Draw graphics using Paints and a Canvas. ■ Play sounds in respone to various game events. ■ Manually perform frame-byframe animations using a game loop that accounts for varying frame rates across devices. ■ Override Activity’s onTouchEvent to process touch events when the user touches the screen or drags a finger on the screen. ■ Use a GestureDetector to recognize more sophisticated user touch motions, such as double taps. ■ Perform simple collision detection. ■ Add sound to your app using a SoundPool and the AudioManager. ■ Override three additional Activity lifecycle methods. ■
Cannon Game App
2
Chapter 7
Cannon Game App
Self-Review Exercises 7.1
Fill in the blanks in each of the following statements: . a) You can create a custom view by extending class View or ANS: one of its subclasses. b) To process simple touch events for an Activity, you can override class Activity’s onTouchEvent method then use constants from class (package android.view) to test which type of event occurred and process it accordingly. ANS: MotionEvent. , which conc) Each SurfaceView subclass should implement the interface tains methods that are called when the SurfaceView is created, changed (e.g., its size or orientation changes) or destroyed. ANS: SurfaceHolder.Callback. d) The d in a format specifier indicates that we’re formatting a decimal integer and the f in a format specifier indicates that we’re formatting a value. ANS: floating-point. folder. e) Sound files are stored in the app’s ANS: res/raw. folder and manage them with a Soundf) You add sound effects to an app’s Pool. ANS: res/raw.
7.2
State whether each of the following is true or false. If false, explain why. a) (True/False) One use of onStop is to suspend a game play so that it does not continue executing when the user cannot interact with it. ANS: False. One use of onPause is to suspend a game play so that it does not continue executing when the user cannot interact with it. b) (True/False) The Android documentation recommends that games use the music audio stream to play sounds. ANS: True. c) (True/False) In Android, it’s important to maximize the amount of work you do in the GUI thread to ensure that the GUI remains responsive and does not display ANR (Application Not Responding) dialogs. ANS: False. In Android, it’s important to minimize the amount of work you do in the GUI thread to ensure that the GUI remains responsive and does not display ANR (Application Not Responding) dialogs. d) (True/False) A Canvas draws on a View’s Bitmap. ANS: True. e) (True/False) Format Strings that contain multiple format specifiers must number the format specifiers for localization purposes. ANS: True. f) (True/False) There are seven sound streams identified by constants in class AudioManager, but the documentation for class SoundPool recommends using the stream for playing music (AudioManager.STREAM_MUSIC) for sound in games. ANS: True. g) (True/False) Custom component class names must be fully qualified in the XML layout element that represents the component. ANS: True.
Exercises 7.3
Fill in the blanks in each of the following statements:
Exercises
3
a) Method is called for the current Activity when another activity receives the focus, which sends the current activity to the background. ANS: onPause. method is called. b) When an Activity is shut down, its ANS: onDestroy. allows an app to react to more sophisticated user interactions such as c) A flings, double-taps, long presses and scrolls. ANS: GestureDetector. method to specify that the game’s volume can be d) We use the Activity’s controlled with the device’s volume keys and should be the same as the device’s music playback volume. The method receives a constant from class AudioManager (package android.media). ANS: setVolumeControlStream. e) Games often require complex logic that should be performed in separate threads of execution and those threads often need to draw to the screen. For such cases, Android pro—a subclass of View to which any thread can draw. vides class ANS: SurfaceView. is called for the current Activity when another activity receives f) Method the focus. ANS: onPause. 7.4
State whether each of the following is true or false. If false, explain why. a) (True/False) Class SurfaceHolder also provides methods that give a thread shared access to the Canvas for drawing, because only one thread at a time can draw to a SurfaceView. ANS: False. Class SurfaceHolder also provides methods that give a thread exclusive access to the Canvas for drawing, because only one thread at a time can draw to a SurfaceView. b) (True/False) A MotionEvent.ACTION_TOUCH indicates that the user touched the screen and indicates that the user moved a finger across the screen (MotionEvent.ACTION_MOVE). ANS: False. A MotionEvent.ACTION_DOWN indicates that the user touched the screen and indicates that the user moved a finger across the screen (MotionEvent.ACTION_MOVE). c) (True/False) When a View is inflated, its constructor is called and passed a Context and an AttributeSet as arguments. ANS: True. d) (True/False) SoundPool method start receives three arguments—the application’s Context, a resource ID representing the sound file to load and the sound’s priority. ANS: False. SoundPool method load receives three arguments—the application’s Context, a resource ID representing the sound file to load and the sound’s priority. e) (True/False) When a game loop controls a game based on the amount of time that has elapsed between animation frames, the game will operate at different speeds as appropriate for each device. ANS: False. When a game loop controls a game based on the amount of time that has elapsed between animation frames, the game will operate at the same overall speed on all devices.
8 Objectives In this chapter you’ll: ■
Create a simple gamepp that’s easy to code and fun to play.
■
Goup animations that move and resize ImageViews with ViewPropertyAnimators.
■
Respond to animation lifecycle events with an AnimatorListener.
■
Process click events for ImageViews and touch events for the screen.
■
Use the thread-safe ConcurrentLinkedQueue
collection from the java.util.concurrent
package to allow concurrent access to a collection from multiple threads. ■
Use an Activity’s default SharedPreferences file.
SpotOn Game App
2
Chapter 8
SpotOn Game App
Self-Review Exercises 8.1
Fill in the blanks in each of the following statements: View animations display a sequence of images. a) ANS: Frame. b) You can listen for property-animation lifecycle events by implementing the interface , which defines methods that are called when an animation starts, ends, repeats or is canceled. ANS: AnimatorListener. configures animations for commonly animated View properties—alpha c) A (transparency), rotation, scale, translation (moving relative to the current location) and location. ANS: ViewPropertyAnimator. d) Class ViewPropertyAnimator was added to Android 3.1 to simplify property animation . for Views and to allow animation of multiple properties in ANS: parallel.
8.2
State whether each of the following is true or false. If false, explain why. a) (True/False) The property animation class PropertyAnimator calculates property values over time, but you must specify an AnimatorUpdateListener in which you programmatically modify the target object’s property values. ANS: False. The property animation class ValueAnimator calculates property values over time, but you must specify an AnimatorUpdateListener in which you programmatically modify the target object’s property values. b) (True/False) Android 3.1 added the utility class ViewPropertyAnimator to simplify property animation for Views and to allow multiple properties to be animated in sequence. ANS: False. Android 3.1 added the new utility class ViewPropertyAnimator to simplify property animation for Views and to allow multiple properties to be animated in parallel. c) (True/False) When an Activity begins executing, its onCreate method is called. This is followed by calls to the Activity’s onPause then onResume methods. Method onResume is also called when an Activity in the background returns to the foreground. ANS: False. When an Activity begins executing, its onCreate method is called. This is followed by calls to the Activity’s onStart then onResume methods. Method onResume is also called when an Activity in the background returns to the foreground.
Exercises 8.3
State whether each of the following is true or false. If false, explain why. a) (True/False) Property animations can be used to animate any property of any object. ANS: True. b) (True/False) You can use the ConcurrentLinkedQueue class from package java.util.concurrent and the Queue interface to maintain thread-safe lists of objects that can be accessed from multiple threads of execution in parallel. ANS: True.
8.4
Fill in the blanks in each of the following statements: View animations allow you to change limited aspects of a View’s appeara) ance, such as where it’s displayed, its rotation and its size. ANS: Tweened.
Exercises
3
b) With animation (package android.animation), you can animate any property of any object—the mechanism is not limited to Views. ANS: property. uses the target object’s set methods to modify the c) ValueAnimator subclass object’s animated properties as their values change over time. ANS: ObjectAnimator. d) You can use the ConcurrentLinkedQueue class (from package java.util.concurrent) lists of objects that can be accessed and the Queue interface to maintain from multiple threads of execution in parallel. ANS: thread-safe. e) Setting the attribute android:hardwareAccelerated to "true" allows the app to use , if available, for performance. hardware accelerated ANS: graphics. f) In addition, a ViewPropertyAnimator provides methods for setting an animation’s du(to respond to animation lifecycle events) and TimeInterpolator ration, (to determine how property values are calculated throughout the animation). ANS: AnimatorListener.
9
Doodlz App
Objectives In this chapter you’ll: ■
Detect when the user touches the screen, moves a finger across the screen and removes a finger from the screen.
■
Process multiple screen touches so the user can draw with multiple fingers at once.
■
Use a SensorManager to detect accelerometer motion events to clear the screen when the user shakes the device.
■
Use an AtomicBoolean object to allow multiple threads to access a boolean value in a thread-safe manner.
■
Use a Paint object to specify the color and width of a line.
■
Use Path objects to store each line’s data as the user draws the lines and to draw those lines with a Canvas.
■
Use a Toast to briefly display a message on the screen.
Self-Review Exercises
2
Self-Review Exercises 9.1
Fill in the blanks in each of the following statements: . a) Android 3.0’s look-and-feel is called the ANS: holographic theme. b) You use the SensorManager to register the sensor changes that your app should receive that will handle those sensor-change events. and to specify the ANS: SensorEventListener. c) A Path object (package android.graphics) represents a geometric path consisting of . line segments and ANS: curves. d) We use the type of the touch event to determine whether the user has touched the or lifted a finger from the screen. screen, ANS: dragged across the screen. method to stop listening for accelerometer e) Use class SensorManager’s events. ANS: unregisterListener. to process accelerometer events. f) Override SensorEventListener method ANS: onSensorChanged. method to close a dialog. g) Use Dialog’s ANS: dismiss. method is called. h) When a View needs to be redrawn, it’s ANS: onDraw. method returns an int representing the MotionEvent i) MotionEvent’s type, which you can use with constants from class MotionEvent to determine how to handle each event. ANS: getActionMasked. is called when the user moves one or more fingers j) The utility method across the screen. ANS: touchMoved. receives as arguments the Context on which the Toast is k) Toast method displayed, the message to display and the duration for which the Toast will be displayed. ANS: makeText.
9.2
State whether each of the following is true or false. If false, explain why. a) (True/False) We use the standard SeekBar thumb in our apps, but you can customize it by setting the SeekBar’s android:seekBar attribute to a drawable resource, such as an image. ANS: False. We use the standard SeekBar thumb in our apps, but you can customize it by setting the SeekBar’s android:thumb attribute to a drawable resource, such as an image. b) (True/False) You unregister the accelerometer event handler when the app is sent to the foreground. ANS: False. You unregister the accelerometer event handler when the app is sent to the background. c) (True/False) Call the inherited View method validate to indicate that the View needs to be redrawn. ANS: False. Call the inherited View method invalidate to indicate that the View needs to be redrawn.
3
Chapter 9
Doodlz App
d) (True/False)
If
the
action
is
MotionEvent.ACTION_DOWN
or
Motion-
Event.ACTION_POINTER_DOWN, the user touched the screen with the same finger.
ANS: False.
If
the
action
is
MotionEvent.ACTION_DOWN
or
Motion-
Event.ACTION_POINTER_DOWN, the user touched the screen with a new finger.
e) (True/False) Resetting the Path erases its corresponding painted line from the screen, because those lines have already been drawn to the bitmap that’s displayed to the screen. ANS: False. Resetting the Path does not erase its corresponding painted line from the screen, because those lines have already been drawn to the bitmap that’s displayed to the screen.
Exercises 9.3
Fill in the blanks in each of the following statements: that allows apps to detect movement. a) Most Android devices have an ANS: accelerometer. (package android.widget) displays a message for a short time, then disb) A appears from the screen. ANS: Toast. monitors the accelerometer to detect device movement. c) The ANS: sensorManager. constant represents the acceleration due to gravity on d) SensorManager’s earth. ANS: GRAVITY_EARTH. e) We register to receive accelerometer events using SensorManager’s registerListener method, which receives three arguments: the SensorEventListener object that will respond to the events, a Sensor representing the type of sensor data the app wishes to re. ceive and ANS: a rate at which sensor events should be delivered to the app method to enable anti-aliasing which smooths the f) We pass true to Paint’s edges of the lines. ANS: setAntiAlias. sets paintLine’s stroke width to the specified number of pixels. g) Method ANS: setLineWidth. —that is, having multiple fingers touching the screen. h) Android supports ANS: multitouch. is called when the user lifts a finger from the screen. i) The utility method The method receives the ID of the finger (lineID) for which the touch just ended as an argument. ANS: touchEnded.
9.4
State whether each of the following is true or false. If false, explain why. a) (True/False) In Android, sensor events are handled in the GUI thread. ANS: False. In Android, sensor events are handled in a separate thread of execution from GUI events. b) (True/False) The alpha component specifies the Color’s transparency with 0 representing completely transparent and 100 representing completely opaque. ANS: False. The alpha component specifies the Color’s transparency with 0 representing completely transparent and 255 representing completely opaque.
Exercises
4
c) (True/False) For accelerometer events, the SensorEvent parameter values array contains three elements representing the acceleration (in meter/second2 ) in the x (left/ right), y (up/down) and z (forward/backward) directions. ANS: True. d) (True/False) Method onProgressChanged is called once when the user drags a SeekBar’s thumb. ANS: False. Method onProgressChanged is called frequently when the user drags a SeekBar’s thumb. e) (True/False) To get the finger’s unique ID that persists across MotionEvents until the user removes that finger from the screen, we’ll use MotionEvent’s getID method, passing the finger index as an argument. ANS: False. To get the finger’s unique ID that persists across MotionEvents until the user removes that finger from the screen, we’ll use MotionEvent’s getPointerID method, passing the finger index as an argument. f) (True/False) The system MotionEvent passed from onTouchEvent contains touch information for multiple moves on the screen if they occur at the same time. ANS: True. g) (True/False) Toast method setLocation specifies where the Toast will appear. The constant Gravity.CENTER indicates that the Toast should be centered over the coordinates specified by the method’s second and third arguments. Toast method show displays the Toast. ANS: False. Toast method setGravity specifies where the Toast will appear. The constant Gravity.CENTER indicates that the Toast should be centered over the coordinates specified by the method’s second and third arguments. Toast method show displays the Toast. h) (True/False) Use a ToastMessage to display a message that automatically disappears after a short period of time. ANS: True.
10 Objectives In this chapter you’ll: ■
Extend ListActivity to create an Activity that consists of a ListView by default.
■
Create multiple Activity subclasses to represent the app’s tasks and use explicit Intents to launch them.
■
Create and open SQLite databases using a SQLiteOpenHelper, and insert, delete and query data in a SQLite database using a SQLiteDatabase object
■
Use a SimpleCursorAdapter to bind database query results to a ListView’s items.
■
Use a Cursor to manipulate database query results.
■
Use multithreading to perform database operations outside the GUI thread and maintain application responsiveness.
■
Define styles containing common GUI attributes and values, then apply them to multiple GUI components.
■
Create XML menu resources and inflate them with a MenuInflater.
Address Book App
2
Chapter 10
Address Book App
Self-Review Exercises 10.1
Fill in the blanks in each of the following statements: is called when the Activity is no longer visible to the a) Activity method user—typically because another Activity has started or returned to the foreground. ANS: onStop. method. b) You obtain the MenuInflater by calling Activity’s ANS: getMenuInflater.
10.2
State whether each of the following is true or false. If false, explain why. a) (True/False) The AndroidManifest.xml file describes an app’s components. ANS: True. b) (True/False) SQLite (www.sqlite.org) is the world’s most widely deployed database engine. ANS: True. c) (True/False) It’s good practice to perform long running operations or operations that block execution until they complete (e.g., file and database access) in the GUI thread. ANS: False. It’s good practice to perform long running operations or operations that block execution until they complete (e.g., file and database access) outside the GUI thread. d) (True/False) Each menu resource XML file contains a root menu element with nested item elements that represent each MenuItem. ANS: True. e) (True/False) SimpleCursorAdapter is a subclass of CursorAdapter that’s designed to simplify mapping Cursor columns directly to TextViews or ImagesViews defined in your XML layouts. ANS: True. f) (True/False) When an Activity is stopped, it will call deactivate on any Cursors it’s currently managing. When the Activity resumes, it will call requery on its Cursors. When the Activity is destroyed, it will automatically call close to release all resources held by any managed Cursors. ANS: True. g) (True/False) It’s considered good practice to ensure that Cursor method moveToFirst returns false before attempting to get data from the Cursor. ANS: False. It’s considered good practice to ensure that Cursor method moveToFirst returns true before attempting to get data from the Cursor. h) (True/False) It’s good practice to release resources like database connections when they are not being used so that other activities can use the resources. ANS: True.
Exercises 10.3
Fill in the blanks in each of the following statements: a) SQLite database query results are managed via a android.database).
(package
ANS: Cursor
b) When we need a database operation’s results in the GUI thread, we’ll use an (package android.os) to perform the operation in one thread and receive the results in the GUI thread. ANS: AsyncTask.
Exercises
3
c) Method is called each time an Activity returns to the foreground, including when the Activity is first created. ANS: onResume. d) Activity method getIntent returns the Intent that launched the Activity. We use , which returns a Bundle that contains any key– that to call Intent method value pairs that were added to the Intent as extras. ANS: getExtras. e) The Cursor returned by method query contains all the table rows that match the meth. od’s arguments—the so-called ANS: result set. 10.4
State whether each of the following is true or false. If false, explain why. a) (True/False) Each Activity must be described in the app’s manifest. ANS: True. b) (True/False) Resource files that define menus are placed in the app’s res/menu folder (which you must create) and are added to the project like other resource files, but in the New Android XML File dialog you select Menu as the resource type. ANS: True. c) (True/False) A key benefit of using an SyncTask is that it handles the details of creating threads and executing its methods on the appropriate threads for you, so that you do not have to interact with the threading mechanism directly. ANS: False. A key benefit of using an AsyncTask is that it handles the details of creating threads and executing its methods on the appropriate threads for you, so that you do not have to interact with the threading mechanism directly. d) (True/False) A deactivated Cursor consumes more resources than an active one, so it’s good practice to align your Cursor’s lifecycle with its parent Activity if the Cursor is not shared among multiple Activity objects. ANS: False. A deactivated Cursor consumes less resources than an active one, so it’s good practice to align your Cursor’s lifecycle with its parent Activity if the Cursor is not shared among multiple Activity objects. e) (True/False) Allowing your Activity to manage the Cursor’s lifecycle also ensures that the Cursor will be closed when it’s no longer needed. ANS: True.
11
Route Tracker App
Objectives In this chapter you’ll: ■
Test an app that uses GPS location data in the Android Emulator and use the Eclipse DDMS perspective to send sample GPS data to the emulator.
■
Use the external Maps API framework and the MapActivity and MapView classes to display Google Maps™ generated by Google web services.
■
Get a Google Maps™ API key unique to your development computer.
■
Use location services and the LocationManager class to receive information on the device’s position and bearing (direction).
■
Display the user’s route using an Overlay on a MapView and GPS location data received in the form of Location objects.
■
Orient a map to the user’s current bearing.
■
Use the PowerManager to keep the device awake.
Self-Review Exercisess
2
Self-Review Exercisess 11.1
Fill in the blanks in each of the following statements: provides access to the device’s location services. a) Class ANS: LocationManager. b) To determine when the device has a GPS fix—that is, the device has “locked onto” enough GPS satellites to receive GPS data for tracking—we implement the interface. ANS: GpsStatus.Listener. (package android.view) provide’s access to the device’s screen dic) Class mensions. ANS: Display. : indicates that this app requires Internet access to downd) The permission load map and satellite images. ANS: android.permission.INTERNET. to programmatically zoom in and out of a map and to change e) You use a the geographic location appearing centered in the MapView. ANS: MapController
f)
MapController’s
method moves the center of the map to the given Geo-
Point using a smooth animation.
ANS: animateTo.
g)
MapController’s
method moves the center of the map to the given Geo-
Point using a smooth animation.
ANS: animateTo.
11.2
State whether each of the following is true or false. If false, explain why. a) (True/False) To create your own app using the Google Maps API, you’ll need to obtain a unique API key from Google. ANS: True. b) (True/False) If you’d like your app to use most of the screen to display maps, you can hide the title bar by using one of the standard Android themes, which can be specified with the attribute android:theme in the activity element. A theme changes the lookand-feel of an app’s GUI. ANS: True. c) (True/False) Shared Android services include those that allow an app to change power settings, obtain location data, control whether a device is allowed to sleep, and more. ANS: True. d) (True/False) MapViews support gestures to zoom and pan the map—any additional functionality must be added programmatically. ANS: True. e) (True/False) LocationManager’s getBestProvider method returns a String representing the name of the location provider that best meets the given Criteria. The true argument indicates that only an enabled provider should be returned. ANS: True. f) (True/False) Class PowerManager enables the app to control a device’s power state so that, for example, the app can record location data even if the screen is off. ANS: True.
3
Chapter 11
Route Tracker App
Exercises 11.3
Fill in the blanks in each of the following statements: a) To access a nonstandard library—that is, one that’s not included with the core Android APIs, such as the Google Maps API—you must indicate the library’s name in the app’s element nested in the application element. manifest with a ANS: uses-library. b) To access shared Android services, you must request permission to use them in the manelements nested in the root manifest element. When a user ifest file with prepares to install an app, the operating system tells the user which permissions are being requested and asks the user to confirm whether they should be granted. If not, the app will not be installed. ANS: uses-permission. c) To display data on a MapView, such as the line representing the route in this app, you and override its draw method. create a subclass of ANS: Overlay. d) Once you have a location provider, you can request updates from it and have them delivered to a LocationListener. The updates are delivered to the listener as objects that represent the device’s geographic location—these include latitude and longitude data, the time they were recorded and, depending on the location provider, may also include altitude and speed data (some devices don’t have sensors for these). ANS: Location. method to get the location e) Many GPS-based apps use LocationManager’s that was last reported when the device previously had a GPS fix (such as during a previous execution of the app). ANS: getLastKnownLocation. f) Class LocationManager provides access to the device’s location services and chooses the object. best location provider based on the requirements you specify in a To determine when the device has a GPS fix, you implement the GpsStatus.Listener interface. ANS: Criteria.
11.4
State whether each of the following is true or false. If false, explain why. a) (True/False) Apps must be signed with a digital certificate before they can be installed on a device. When you’re building and testing apps, the ADT Plugin handles this automatically by creating a debug certificate and using it to sign your apps. ANS: True. b) (True/False) Depending on your device, several location providers may be supported— LocationManager provides capabilities for choosing the best one based on your app’s requirements, which you specify in a Requirements object. ANS: False. Depending on your device, several location providers may be supported—LocationManager provides capabilities for choosing the best one based on your app’s requirements, which you specify in a Criteria object. c) (True/False) An app that changes the power settings can negatively affect the device’s battery life when the app is executing, so class PowerManager should be used frequently. ANS: False. An app that changes the power settings can negatively affect the device’s battery life when the app is executing, so class PowerManager should be used sparingly. d) (True/False) The permission android.permission.WAKE_LOCK indicates that this app needs access to the PowerManager to prevent the device from sleeping while the app is tracking a route. ANS: True.
Exercises
4
e) (True/False) High-accuracy GPS data uses less power. If your app doesn’t require such accuracy, you can choose Criteria.ACCURACY_COARSE. ANS: False. High-accuracy GPS data uses more power. If your app doesn’t require such accuracy, you can choose Criteria.ACCURACY_COARSE. f) (True/False) A GeoPoint consists of a latitude and longitude measured in degrees. ANS: False. A GeoPoint consists of a latitude and longitude measured in microdegrees (millionths of a degree).
12
Slideshow App
Objectives In this chapter you’ll: ■
Use Intents and content providers to allow the user to select pictures and music from a device’s Gallery and media library, respectively.
■
Launch Intents that return results.
■
Use a MediaPlayer to play music from the device’s media library during the slideshow.
■
Customize a ListActivity’s layout.
■
Use the view holder pattern to improve performance when using complex ListView-item layouts.
■
Create a custom GUI for an AlertDialog to allow a user to enter information,
■
Load images as Bitmaps using a BitmapFactory.
■
Use a TransitionDrawable to gradually transition between two BitmapDrawables that contain images.
Self-Review Exercises
2
Self-Review Exercises 12.1
Fill in the blanks in each of the following statements: enables an Activity to be notified when another Aca) Activity method tivity completes execution and to receive results back from the completed Activity. ANS: startActivityForResult. method to inb) When the ArrayAdapter’s data set changes, you can call its dicate that the Adapter’s underlying data set has changed. ANS: notifyDataSetChanged. images to save memory; This helps prevent out-of-memory errors, c) You which can be common when manipulating many Bitmaps. ANS: downsample. d) Intent with Intent’s ACTION_GET_CONTENT constant indicates that the Intent allows the user to select content that’s stored . ANS: on the device. " to allows the user to select any type e) An Intent that uses the MIME type " of audio on the device. ANS: audio/*. if the MediaPlayer cannot be prepared—for examf) Method prepare will ple, if it’s currently playing a media clip. ANS: throw an exception. method moves the audio playback to the specified g) Calling MediaPlayer’s time in milliseconds. ANS: seekTo.
12.2
State whether each of the following is true or false. If false, explain why. a) (True/False) Several BroadcastReceivers are built into Android for access to data such as images, audio, video, contact information and more. ANS: False. Several content providers are built into Android for access to data such as images, audio, video, contact information and more. b) (True/False) Setting the android:singleLine attribute to false allows only a single line of text in an element. ANS: False. Setting the android:singleLine attribute to true allows only a single line of text in an element.
Exercises 12.3
Fill in the blanks in each of the following statements: that enable apps to save and retrieve data and to make data a) Android uses accessible across applications. ANS: content providers. b) When you scroll in a ListView, as items scroll off the screen, Android reuses those list items for the new ones that are scrolling onto the screen. You can take advantage of the existing GUI components in the reused list items to increase a ListView’s performance pattern. of your ListViews. To do this, use the ANS: view-holder. (package android.graphics) creates Bitmap objects. c) A ANS: BitmapFactory. d) In general, you should wrap calls to startActivity and startActivityForResult in a try statement, so you can catch the exception if there is no Activity to handle the . ANS: Intent.
3
Chapter 12
Slideshow App
e) State information is saved in onSaveInstanceState and loaded in when the Activity goes to the background and returns to the foreground, respectively. ANS: onCreate. 12.4
State whether each of the following is true or false. If false, explain why. a) (True/False) Creating custom ListView items is a cost effective runtime operation, even for large lists with complex list-item layouts. ANS: False. Creating custom ListView items is an expensive runtime operation, especially for large lists with complex list-item layouts. b) (True/False) Method onActivityResult is called when a sub-Activity started by the startActivityForResult method finishes executing. ANS: True. c) (True/False) Calling MediaPlayer’s setLooping method with the argument true loops playback if the music’s duration is longer than the total slideshow duration. ANS: False. Calling MediaPlayer’s setLooping method with the argument true loops playback if the music’s duration is shorter than the total slideshow duration. d) (True/False) Use the view-holder pattern to boost the performance of ListViews with complex list-item layouts. ANS: True.
13 Objectives In this chapter you’ll: ■
Use an Intent and content resolvers to allow the user to select videos from the device’s media library.
■
Use the device’s rear-facing camera to take new pictures to add to the slideshow.
■
Use SurfaceView, SurfaceHolder and Camera objects to display a photo preview with various color effects.
■
Use an VideoView to play videos.
■
Use Serializable objects to save and load slideshows.
■
Use ObjectOutputStream and FileOutputStream to save slideshows to a device.
■
Load slideshows from the device with ObjectInputStream and FileInputStream.
Enhanced Slideshow App
2
Chapter 13
Enhanced Slideshow App
Self-Review Exercises 13.1
Fill in the blanks in each of the following statements: to play videos. a) Use a ANS: VideoView.
b) To use an object with the serialization mechanism, implement the face Serializable. ANS: tagging. can determine when a video finishes playing. c) A ANS: MediaPlayer.OnCompletionListener. 13.2
inter-
State whether each of the following is true or false. If false, explain why. a) A serialized object is represented as a sequence of bytes that includes the object’s data and information about the object’s type. ANS: True. b) (True/False) Objects of a class that implements Serializable are tagged as being Serializable objects—that is, any object of a class that implements Serializable can be serialized. ANS: True. c) (True/False) The VideoView maintains its own MediaPlayer to play the video. ANS: True. d) (True/False) The Context class provides methods for accessing the file system. ANS: True. e) (True/False) When the SurfaceView is created, changed or destroyed, its SurfaceHolder’s Callback methods are called. ANS: True.
Exercises 13.3
Fill in the blanks in each of the following statements: a) To use an object with the serialization mechanism, the object’s class must implement interface, which is a tagging interface. the ANS: Serializable. —that is, the type informab) A serialized object can be read from a file and tion and bytes that represent the object and its data can be used to recreate the object graph in memory. This is accomplished with an ObjectInputStream that reads the bytes from a specified InputStream. ANS: deserialized. method returns the deserialized object as type Obc) ObjectOutputStream’s ject. To use it in an app, you must cast the object to the appropriate type. ANS: readObject. method is called each time the d) The SurfaceHolder.Callback interface’s size or format of the SurfaceView changes—typically when the device is rotated and when the SurfaceView is first created and displayed. ANS: surfaceChanged. method. e) Read and deserialize objects with an ObjectInputStream’s ANS: readObject.
Exercises 13.4
3
State whether each of the following is true or false. If false, explain why. a) (True/False) You can use a MediaPlayer.OnFinishListener to determine when a video finishes playing so we can continue playing. ANS: False. You can use a MediaPlayer.OnCompletionListener to determine when a video finishes playing so we can continue playing. b) (True/False) Camera’s static open method can get a Camera object that allows the app to use the device’s rear facing camera. ANS: True.
4
Chapter 13
Enhanced Slideshow App
Exercises
5
6
Chapter 13
Enhanced Slideshow App
14 Objectives In this chapter you’ll: ■
Use WeatherBug® web services to get the current conditions and five-day forecast for a specified city and process that data using an Android 3.x JsonReader.
■
Use various types of Fragments to create reusable components and make better use of the screen real estate in a tablet app.
■
Implement tabbed navigation using the Android 3.x ActionBar.
■
Create a companion app widget that can be installed on the user’s home screen.
■
Broadcast changes of the app’s preferred city to the companion app widget.
Weather Viewer App
2
Chapter 14
Weather Viewer App
Self-Review Exercises 14.1
Fill in the blanks in each of the following statements: . a) A ListFragment is a Fragment containing a ANS: ListView. allows b) A FragmentTransaction (package android.app) obtained from the the Activity to add, remove and transition between Fragments. ANS: FragmentManager. c) We extend class AppWidgetProvider (package android.appwidget), a subclass of (package android.content), to create an app widget and allow it to receive notifications from the system when the app widget is enabled, disabled, deleted or updated. ANS: BroadcastReceiver
d) You can force an item to appear in the ActionBar by using the always value of attribute but you risk overlapping menu items by doing so. ANS: android:showAsAction. 14.2
State whether each of the following is true or false. If false, explain why. a) (True/False) Fragments were introduced in Android 3.x and cannot be used with earlier versions of Android. ANS: False. Though fragments were introduced in Android 3.x, there’s a compatibility package that enables you to use them with earlier versions of Android. b) (True/False) The action bar can display the app’s options menu, navigation elements (such as tabbed navigation) and other interactive GUI components. ANS: True. c) (True/False) Unlike activities, services need not be registered in the manifest. ANS: False. Like activities, all services must be registered in the manifest; otherwise, they cannot be executed. d) (True/False) JSON (JavaScript Object Notation)—a simple way to represent JavaScript objects as numbers—is an alternative to XML for passing data between the client and the server. ANS: False. JSON (JavaScript Object Notation)—a simple way to represent JavaScript objects as strings—is an alternative to XML for passing data between the client and the server. e) (True/False) Arrays are represented in JSON with curly braces in the following format: { value1, value2, value3 } ANS: False. Arrays are represented in JSON with square brackets.
f) (True/False) Class JsonReader provides methods for reading booleans, doubles, ints, longs and Strings. ANS: True. g) (True/False) A PendingIntent cannot be passed across processes. ANS: False. A PendingIntent can be passed across processes. h) (True/False) Use Fragments to create reusable components and make better use of the screen real estate in a tablet app. ANS: True.
Exercises 14.3
Fill in the blanks in each of the following statements:
Exercises
3
a) An Activity’s (package android.content.res) can be used to determine the current orientation. ANS: Configuration. (package android.util) to read JSON objects. b) Use a(n) ANS: JsonReader. c) The attribute android:showAsAction defines how a menu item should appear in the Acspecifies that this item should be visible in the ActiontionBar. The value Bar if there’s room to lay it out completely. ANS: ifRoom. d) We get the name from the next name–value pair in a JSON object by calling JsonReader’s method. ANS: nextName. e) You use a FragmentManager to manage the Fragments and a to add, remove and transition between Fragments. ANS: FragmentTransaction. 14.4
State whether each of the following is true or false. If false, explain why. a) (True/False) Fragments are a key feature of Android 3.x. ANS: True. b) (True/False) The base class of all fragments is BaseFragment (package android.app). ANS: False. The base class of all fragments is Fragment (package android.app). c) (True/False) Like an Activity, each Fragment has a life cycle. ANS: True. d) (True/False) Fragments can be executed independently of a parent Activity. ANS: False. Fragments must be hosted in a parent Activity—they cannot be executed independently. e) (True/False) It’s common practice to allow a user to launch an app by touching the app’s companion widget on the device’s home screen. ANS: True. f) (True/False) Each object in JSON is represented as a list of property names and values contained in curly braces, in the following format: { "propertyName1" : value1, "propertyName2'": value2 } ANS: True.
g) (True/False) Each value in a JSON array can be a string, a number, a JSON representation of an object, true, false or null. ANS: True. h) (True/False) When updating an app widget from an AppWidgetProvider, you update the app widget’s Views directly. ANS: False. When updating an app widget from an AppWidgetProvider, you do not update the app widget’s Views directly. You use an object of type RemoteViews.