1. Introduction to Android


Objectives

In this chapter you’ll be introduced to:

Image The history of Android and the Android SDK.

Image Google Play Store for downloading apps.

Image The Android packages used in this book to help you create Android apps.

Image A quick refresher of object-technology concepts.

Image Key software for Android app development, including the Android SDK, the Java SDK and the Android Studio Integrated Development Environment (IDE).

Image Important Android documentation.

Image Test-driving an Android tip-calculator app in Android Studio.

Image Characteristics of great Android apps.


1.1 Introduction

Welcome to Android app development! We hope that working with Android How to Program will be an informative, challenging, entertaining and rewarding experience for you.

The Android portion of this book is geared toward people who know Java object-oriented programming. If you do not know Java or another object-oriented programming language, the appendices provide a friendly introduction to Java and the object-oriented programming techniques you’ll need to develop Android apps. We use only complete working Android apps, so if you have object-oriented programming experience in another language, such as C#, Objective-C/Cocoa or C++ (with class libraries), you should be able to master the material quickly, learning a good amount of Java and Java-style object-oriented programming as you learn Android app development.

App-Driven Approach

We use an app-driven approach—new features are discussed in the context of complete working Android apps, with one app per chapter. For each app, we first describe it, then have you test-drive it. Next, we briefly overview the key Android Studio IDE (Integrated Development Environment), Java and Android SDK (Software Development Kit) technologies we use to implement the app. For apps that require it, we walk through designing the GUI using Android Studio. Then we provide the complete source-code listing, using line numbers, syntax shading and code highlighting to emphasize the key portions of the code. We also show one or more screenshots of the running app. Then we do a detailed code walkthrough, emphasizing the new programming concepts introduced in the app. You can download the source code for all of the book’s apps from

1.2 Android—The World’s Leading Mobile Operating System

Android device sales are growing quickly, creating enormous opportunities for Android app developers.

• The first-generation Android phones were released in October 2008. As of June 2015, Android had 82.8% of the global smartphone market share, compared to 13.9% for Apple and 2.6% for Microsoft.1

1. http://www.idc.com/prodserv/smartphone-os-market-share.jsp.

• Billions of apps have been downloaded from Google Play and more than one billion Android devices were shipped worldwide in 2014.2

2. http://www.cnet.com/news/android-shipments-exceed-1-billion-for-first-time-in-2014/.

• According to PC World, approximately 230 million tablets shipped in 2014 of which 67.3% were Android tablets, compared to 27.6% for iOS and 5.1% for Microsoft Windows.3

3. http://www.pcworld.com/article/2896196/windows-forecast-to-gradually-grab-tablet-market-share-from-ios-and-android.html.

• Android devices now include smartphones, tablets, e-readers, robots, jet engines, NASA satellites, game consoles, refrigerators, televisions, cameras, health-care devices, smartwatches, automobile in-vehicle “infotainment” systems (for controlling the radio, GPS, phone calls, thermostat, etc.) and more.4

4. http://www.businessweek.com/articles/2013-05-29/behind-the-internet-of-things-isandroid-and-its-everywhere.

• A recent report says that mobile app revenue (across all mobile platforms) is expected to reach reach $99 billion by 2019.5

5. http://www.telecompetitor.com/mobile-app-forecast-calls-for-revenue-of-99-billion-by-2019/.

1.3 Android Features

Openness and Open Source

One benefit of developing Android apps is the openness of the platform. The operating system is open source and free. This allows you to view Android’s source code and see how its features are implemented. You can contribute to Android by reporting bugs:

or by participating in the Open Source Project discussion groups

Numerous open-source Android apps from Google and others are available on the Internet (Fig. 1.1). Figure 1.2 shows you where you can get the Android source code, learn about the philosophy behind the open-source operating system and get licensing information.

Image

Fig. 1.1 | Open-source Android app and library resource sites.

Image

Fig. 1.2 | Resources and source code for the open-source Android operating system.

The openness of the platform spurs rapid innovation. Unlike Apple’s proprietary iOS, which is available only on Apple devices, Android is available on devices from dozens of original equipment manufacturers (OEMs) and through numerous telecommunications carriers worldwide. The intense competition among OEMs and carriers benefits customers.

Java

Android apps are developed with Java—one of the world’s most widely used programming languages. Java was a logical choice for the Android platform, because it’s powerful, free, open source and used by millions of developers. Experienced Java programmers can quickly dive into Android development, using Google’s Android APIs (Application Programming Interfaces) and others available from third parties.

Java is object oriented and has access to extensive class libraries that help you quickly develop powerful apps. GUI programming in Java is event driven—in this book, you’ll write apps that respond to various user-initiated events such as screen touches. In addition to directly programming portions of your apps, you’ll also use the Android Studio IDE to conveniently drag and drop predefined objects such as buttons and textboxes into place on your screen, and label and resize them. Using Android Studio, you can create, run, test and debug Android apps quickly and conveniently.

Multitouch Screen

Android smartphones wrap the functionality of a mobile phone, Internet client, MP3 player, gaming console, digital camera and more into a handheld device with full-color multitouch screens. With the touch of your fingers, you can navigate easily between using your phone, running apps, playing music, web browsing and more. The screen can display a keyboard for typing e-mails and text messages and entering data in apps (some Android devices also have physical keyboards).

Gestures

The multitouch screens allow you to control the device with gestures involving one touch or multiple simultaneous touches (Fig. 1.3).

Image

Fig. 1.3 | Some common Android gestures.

Built-in Apps

Android devices come with several default apps, which may vary, depending on the device, the manufacturer or the mobile service carrier. Some apps commonly included are Phone, Contacts, Messenger, Browser, Calculator, Calendar, Clock and Photos.

Web Services

Web services are software components stored on one computer that can be accessed by an app (or other software component) on another computer over the Internet. With web services, you can create mashups, which enable you to rapidly develop apps by quickly combining complementary web services, often from different organizations and possibly other forms of information feeds. For example, 100 Destinations

combines the photos and tweets from Twitter with the mapping capabilities of Google Maps to allow you to explore countries around the world through the photos of others.

Programmableweb

provides a directory of over 14,000 APIs and mashups, plus how-to guides and sample code for creating your own mashups. Figure 1.4 lists some popular web services. We use OpenWeatherMap.org’s weather web services in Chapter 7.

Image

Fig. 1.4 | Some popular web services (http://www.programmableweb.com/category/all/apis).

1.4 Android Operating System

The Android operating system was developed by Android, Inc., which was acquired by Google in 2005. In 2007, the Open Handset Alliance

was formed to develop, maintain and evolve Android, driving innovation in mobile technology and improving the user experience while reducing costs.

In this section, we walk through the evolution of the Android operating system, showing its versions and their key functionality. The Android marketplace is fragmented—many devices still use older Android versions—so it’s helpful for you to be aware of the features introduced in each version.

Android Version Naming Convention

Each new version of Android is named after a dessert, going in alphabetical order (Fig. 1.5).

Image

Fig. 1.5 | Android version numbers and the corresponding names.

1.4.1 Android 2.2 (Froyo)

Android 2.2 (also called Froyo, released in May 2010) introduced external storage, allowing you to store apps on an external memory device rather than just in the Android device’s internal memory. It also introduced the Android Cloud to Device Messaging (C2DM) service. Cloud computing allows you to use software and data stored in the “cloud”—i.e., accessed on remote computers (or servers) via the Internet and available on demand—rather than having it stored on your desktop, notebook computer or mobile device. Cloud computing gives you the flexibility to increase or decrease computing resources to meet your resource needs at any given time, making it more cost effective than purchasing expensive hardware to ensure that you have enough storage and processing power for occasional peak levels. Android C2DM allows app developers to send data from their servers to their apps installed on Android devices, even when the apps are not currently running. The server notifies the apps to contact it directly to receive updated app or user data.6 C2DM is now deprecated in favor of Google Cloud Messaging, which was introduced in 2012.

6. http://code.google.com/android/c2dm/.

For information about additional Android 2.2 features—OpenGL ES 2.0 graphics capabilities, the media framework and more—visit

1.4.2 Android 2.3 (Gingerbread)

Android 2.3 (Gingerbread), released later in 2010, added more user refinements, such as a redesigned keyboard, improved navigation capabilities, increased power efficiency and more. It also added several developer features for communications (e.g., technologies that make it easier to make and receive calls from within an app), multimedia (e.g., new audio and graphics APIs) and gaming (e.g., improved performance and new sensors, such as a gyroscope for better motion processing).

One of the most significant new features in Android 2.3 was support for near-field communication (NFC)—a short-range wireless connectivity standard that enables communication between two devices within a few centimeters. NFC support and features vary by Android device. NFC can be used for payments (for example, touching your NFC-enabled Android device to a payment device on a soda machine), exchanging data such as contacts and pictures, pairing devices and accessories and more. For more Android 2.3 developer features, see

1.4.3 Android 3.0 through 3.2 (Honeycomb)

Android 3.0 (Honeycomb) included user-interface improvements specifically for large-screen devices (e.g., tablets), such as a redesigned keyboard for more efficient typing, a visually appealing 3D user interface, easier navigation between screens within an app and more. New Android 3.0 developer features included:

• fragments, which describe portions of an app’s user interface and can be combined into one screen or used across multiple screens

• a persistent Action Bar at the top of the screen providing users with options for interacting with apps

• the ability to add large-screen layouts to existing apps designed for small screens to optimize your app for use on different screen sizes

• a visually attractive and more functional user interface, known as “Holo” for its holographic look and feel

• a new animation framework

• improved graphics and multimedia capabilities

• ability to use multicore processor architectures for enhanced performance

• increased Bluetooth support (e.g., enabling an app to determine if there are any connected devices such as headphones or a keyboard)

• and an animation framework for animating user-interface or graphics objects.

For a list of Android 3.0 user and developer features and platform technologies, go to

1.4.4 Android 4.0 through 4.0.4 (Ice Cream Sandwich)

Android 4.0 (Ice Cream Sandwich), released in 2011, merged Android 2.3 (Gingerbread) and Android 3.0 (Honeycomb) into one operating system for use on all Android devices. This allowed you to incorporate into your smartphone apps Honeycomb’s features that previously were available only on tablets—the “Holo” user interface, a new launcher (used to customize the device’s home screen and launch apps) and more—and easily scale your apps to work on different devices. Ice Cream Sandwich also added several APIs for improved communication between devices, accessibility for users with disabilities (e.g., vision impairments), social networking and more (Fig. 1.6). For a complete list of Android 4.0 APIs, see

Image

Fig. 1.6 | Some Android Ice Cream Sandwich developer features (http://developer.android.com/about/versions/android-4.0.html).

1.4.5 Android 4.1–4.3 (Jelly Bean)

Android Jelly Bean, released in 2012, focused on many behind-the-scenes platform improvements, such as better performance, accessibility, support for international users and more. Other new features included support for enhanced Bluetooth connectivity (Bluetooth LE was introduced in Android 4.3), external displays, support for multiple users on one tablet, restricted user profiles, improved security, appearance enhancements (e.g., resizable app widgets, lock screen widgets, and expandable notifications), optimized location and sensor capabilities, better media capabilities (audio/video), and more seamless switching between apps and screens (Fig. 1.7). In addition, Google introduced new APIs that are developed separately from Android platform versions:

• Google Cloud Messaging—a cross-platform solution that enables developers to deliver messages to devices

• Google Play Services—a set of APIs for incorporating Google functionality into your apps.

For the Jelly Bean features list, see

Image

Fig. 1.7 | Some Android Jelly Bean features (http://developer.android.com/about/versions/jelly-bean.html).

1.4.6 Android 4.4 (KitKat)

Android 4.4 KitKat, released in October 2013, includes several performance improvements that make it possible to run the operating system on all Android devices, including older, memory-constrained devices, which are particularly popular in developing countries.7

7. http://techcrunch.com/2013/10/31/android-4-4-kitkat-google/.

Enabling more users to update to KitKat reduced the “fragmentation” of Android versions in the market, which has been a challenge for developers who previously had to design apps to run across multiple versions of the operating system, or limit their potential market by targeting their apps to a specific version of the operating system.

Android KitKat also includes security and accessibility enhancements, improved graphics and multimedia capabilities, memory-use analysis tools and more. Figure 1.8 lists some of the key KitKat features. For a complete list, see

Image

Fig. 1.8 | Some Android KitKat features (http://developer.android.com/about/versions/kitkat.html).

1.4.7 Android 5.0 and 5.1 (Lollipop)

Android Lollipop—released in November 2014—was a major update with thousands of API enhancements for phones and tablets, and new capabilities that enable developers to create apps for wearables (e.g., smart watches), TVs and cars. One of the biggest changes was material design—a complete user-interface redesign (also used in Google’s web apps). Other features included: a new Android runtime, notification enhancements (enabling users to interact with a notification without leaving the current app), networking enhancements (Bluetooth, Wi-Fi, cellular and NFC), high-performance graphics (OpenGL ES 3.1 and the Android Extension Pack), better audio capabilities (capture, multichannel mixing, playback and support for USB peripherals), enhanced camera capabilities, screen sharing, new sensor support, enhanced accessibility features, multiple SIM card support and more. Figure 1.9 lists some of the key Lollipop features. For a complete list, see

Image

Fig. 1.9 | Some Android Lollipop features (http://developer.android.com/about/versions/lollipop.html).

1.4.8 Android 6 (Marshmallow)

Android Marshmallow, released in September 2015, is the current version of Android at the time of this writing. Some new features include Now on Tap (for getting Google Now information in the context of an app), Doze and App Standby (for saving battery), a new permissions model to make apps easier to install, fingerprint authentication, better data protection, better text-selection support, 4K display support, new audio and video capabilities, new camera capabilities (flashlight and image-reprocessing APIs) and more. Figure 1.10 lists some of the key Lollipop features. For a complete list, see

1.5 Downloading Apps from Google Play

At the time of this writing, there were over 1.6 million apps in Google Play, and the number is growing quickly.8 Figure 1.11 lists some popular free and fee-based apps in various categories. You can download apps through the Play Store app installed on your Android device. You also can log into your Google Play account at

8. http://www.statista.com/statistics/266210/number-of-available-applications-inthe-google-play-store/.

then specify the Android device on which to install the app. It will then download via the device’s Wi-Fi or 3G/4G connection. In Chapter 10, Google Play and App Business Issues, we discuss additional app stores, offering your apps for free or charging a fee, app pricing and more.

Image

Fig. 1.11 | Some popular Android apps in Google Play.

1.6 Packages

Android uses a collection of packages, which are named groups of related, predefined classes. Some of the packages are Android specific, some are Java specific and some are Google specific. These packages allow you to conveniently access Android OS features and incorporate them into your apps. The Android packages help you create apps that adhere to Android’s unique look-and-feel conventions and style guidelines,

Figure 1.12 lists many of the packages we discuss in this book. For a complete list of Android packages, see

Several of the packages we use are from the Android Support libraries, which enable you to use newer Android features in apps that run on current and older platforms. For an overview of the key features in the Android Support libraries, visit:

Image
Image

Fig. 1.12 | Android and Java packages used in this book, listed with the chapter in which they first appear. We discuss additional packages in Volume 2.

1.7 Android Software Development Kit (SDK)

The Android SDK provides the tools you’ll need to build Android apps. It gets installed with Android Studio. See the Before You Begin section (after the Preface) for details on downloading the software you’ll need to develop Android apps, including Java SE 7 and Android Studio.

Android Studio

Android Studio9 was announced at the Google I/O developer conference in 2013 and is now Google’s preferred Android IDE. The IDE includes:

9. Android Studio is based on the JetBrains IntelliJ IDEA Java IDE (http://www.jetbrains.com/idea/).

• GUI designer

• code editor with support for syntax coloring and line numbering

• auto-indenting and auto-complete (i.e., type hinting)

• debugger

• version control system

• refactoring support

and more.

The Android Emulator

The Android emulator, included in the Android SDK, allows you to run Android apps in a simulated environment within Windows, Mac OS X or Linux, without using an actual Android device. The emulator displays a realistic Android user-interface window. It’s particularly useful if you do not have access to Android devices for testing. You should certainly test your apps on a variety of Android devices before uploading them to Google Play.

Before running an app in the emulator, you’ll need to create an Android Virtual Device (AVD), which defines the characteristics of the device on which you want to test, including the hardware, system image, screen size, data storage and more. If you want to test your apps for multiple Android devices, you’ll need to create separate AVDs to emulate each unique device, or use Google’s Cloud Test Lab

which enables you to test on many different devices.

You can reproduce on the emulator most of the Android gestures (Fig. 1.13) and controls (Fig. 1.14) using your computer’s keyboard and mouse. The gestures on the emulator are a bit limited, since your computer probably cannot simulate all the Android hardware features. For example, to test GPS apps in the emulator, you’ll need to create files that simulate GPS readings. Also, although you can simulate orientation changes (to portrait or landscape mode), simulating particular accelerometer readings (the accelerometer allows the device to respond to up/down, left/right and forward/backward acceleration) requires features that are not built into the emulator. The emulator can, however, use sensor data from an actual Android device connected to the computer, as described at

Figure 1.15 lists Android functionality that’s not available on the emulator. You can install your app on an Android device to test these features. You’ll start creating AVDs and using the emulator to develop Android apps in Chapter 2’s Welcome app.

Image

Fig. 1.13 | Android gestures on the emulator.

Image

Fig. 1.14 | Android hardware controls in the emulator (for additional controls, go to http://developer.android.com/tools/help/emulator.html).


Android functionality not available on the emulator

• Making or receiving real phone calls (the emulator allows simulated calls only)

• Bluetooth

• USB connections

• Device-attached headphones

• Determining network connected state

• Determining battery charge or power charging state

• Determining SD card insert/eject

• Direct support for sensors (accelerometer, barometer, compass, light sensor, proximity sensor)—it is possible, however, to use sensor data from a USB-connected device


Fig. 1.15 | Android functionality not available in the emulator (http://developer.android.com/tools/devices/emulator.html#limitations).

1.8 Object-Oriented Programming: A Quick Refresher

Android uses object-oriented programming techniques, so in this section we review the basics of object technology. We use all of these concepts in this book.

Building software quickly, correctly and economically remains an elusive goal at a time when demands for new and more powerful software are soaring. Objects, or more precisely—as we’ll see in Chapter 3—the classes objects come from, are essentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile objects, people objects, etc. Almost any noun can be reasonably represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and communicating). Software developers are discovering that using a modular, object-oriented design-and-implementation approach can make software development groups much more productive than they could be with earlier popular techniques like “structured programming”—object-oriented programs are often easier to understand, correct and modify.

1.8.1 The Automobile as an Object

To help you understand objects and their contents, let’s begin with a simple analogy. Suppose you want to drive a car and make it go faster by pressing its accelerator pedal. What must happen before you can do this? Well, before you can drive a car, someone has to design it. A car typically begins as engineering drawings, similar to the blueprints that describe the design of a house. These drawings include the design for an accelerator pedal. The pedal hides from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, and the steering wheel hides the mechanisms that turn the car. This enables people with little or no knowledge of how engines, braking and steering mechanisms work to drive a car easily.

Just as you cannot cook meals in the kitchen of a blueprint, you cannot drive a car’s engineering drawings. Before you can drive a car, it must be built from the engineering drawings that describe it. A completed car has an actual accelerator pedal to make it go faster, but even that’s not enough—the car won’t accelerate on its own (hopefully!), so the driver must press the pedal to accelerate the car.

1.8.2 Methods and Classes

Let’s use our car example to introduce some key object-oriented programming concepts. Performing a task in a program requires a method. The method houses the program statements that actually perform its tasks. The method hides these statements from its user, just as the accelerator pedal of a car hides from the driver the mechanisms of making the car go faster. A class houses the methods that perform the class’s tasks. For example, a class that represents a bank account might contain one method to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is. A class is similar in concept to a car’s engineering drawings, which house the design of an accelerator pedal, steering wheel, and so on.

1.8.3 Instantiation

Just as someone has to build a car from its engineering drawings before you can actually drive a car, 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 instantiation. An object is then referred to as an instance of its class.

1.8.4 Reuse

Just as a car’s engineering drawings can be reused many times to build many cars, 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. Reuse also helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning. Just as the notion of interchangeable parts was crucial to the Industrial Revolution, reusable classes are crucial to the software revolution that has been spurred by object technology.

1.8.5 Messages and Method Calls

When you drive a car, pressing its gas pedal sends a message to the car to perform a task—that is, to go faster. Similarly, you send messages to an object. Each message is a method call that tells a method of the object to perform its task. For example, a program might call a particular bank-account object’s deposit method to increase the account’s balance.

1.8.6 Attributes and Instance Variables

A car, besides having capabilities to accomplish tasks, also has attributes, such as its color, its number of doors, the amount of gas in its tank, its current speed and its record of total miles driven (i.e., its odometer reading). Like its capabilities, the car’s attributes are represented as part of its design in its engineering diagrams (which, for example, include an odometer and a fuel gauge). As you drive an actual car, these attributes are carried along with the car. Every car maintains its own attributes. For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars.

An object, similarly, has attributes that it carries along as it’s used in a program. These attributes are specified as part of the object’s class. For example, a bank-account object has a balance attribute that represents the amount of money in the account. Each bank-account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class’s instance variables.

1.8.7 Encapsulation

Classes encapsulate (i.e., wrap) attributes and methods into objects—an object’s attributes and methods are intimately related. 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. This information hiding is crucial to good software engineering.

1.8.8 Inheritance

A new class of objects can be created quickly and conveniently by inheritance—the new class absorbs the characteristics of an existing one, possibly customizing them and adding unique characteristics of its own. In our car analogy, a “convertible” certainly is an object of the more general class “automobile,” but more specifically, the roof can be raised or lowered.

1.8.9 Object-Oriented Analysis and Design (OOAD)

How will you create the code for your programs? Perhaps, like many programmers, you’ll simply turn on your computer and start typing. This approach may work for small programs, but what if you were asked to create a software system to control thousands of automated teller machines for a major bank? Or suppose you were asked to work on a team of 1,000 software developers building the next U.S. air traffic control system? For projects so large and complex, you should not simply sit down and start writing programs.

To create the best solutions, you should follow a detailed analysis process for determining your project’s requirements (i.e., defining what the system is supposed to do) and developing a design that satisfies them (i.e., deciding how the system should do it). Ideally, you’d go through this process and carefully review the design (and have your design reviewed by other software professionals) before writing any code. If this process involves analyzing and designing your system from an object-oriented point of view, it’s called an object-oriented analysis and design (OOAD) process. Languages like Java are object oriented. Programming in such a language, called object-oriented programming (OOP), allows you to implement an object-oriented design as a working system.

1.9 Test-Driving the Tip Calculator App in an Android Virtual Device (AVD)

In this section, you’ll run and interact with your first Android app using an Android Virtual Device and, if you have one, an actual Android device. The Tip Calculator (Fig. 1.16(a))—which you’ll build in Chapter 3—calculates and displays for a restaurant bill the tip amount and the total bill amount. As you enter each digit of the bill amount by touching the numeric keypad, the app calculates and displays the tip and total bill for a tip percentage that you specify with the app’s SeekBar—we use 15% by default (Fig. 1.16(a)). You can select a tip percentage in the range 0–30% by moving the SeekBar’s thumb—this updates the tip percentage TextView and displays the updated tip and bill total in the TextViews below the SeekBar (Fig. 1.16(b)).

Image

Fig. 1.16 | Tip Calculator when the app first loads, then after the user enters the bill amount and changes the tip percentage.

1.9.1 Opening the Tip Calculator App’s Project in Android Studio

To open the Tip Calculator app’s project, perform the following steps:

1. Checking your setup. If you have not done so already, perform the steps specified in the Before You Begin section.

2. Opening Android Studio. Use the Android Studio shortcut

Image

to open the IDE. On Windows, the shortcut will appear in your Start menu or Start screen. On OS X, the shortcut is located in your Applications folder. On Linux, the shortcut’s location depends on where you extract the ZIP file containing the Android Studio files. Once you open Android Studio for the first time, the Welcome to Android Studio window appears (Fig. 1.17).

Image

Fig. 1.17 | Welcome to Android Studio window.

3. Opening the Tip Calculator app’s project. In Android Studio, when another project is already open, you can select File > Open... to navigate to that project's location and open it, or in the Welcome to Android Studio Window (Fig. 1.17), you can click Open an existing Android Studio Project to open the Open File or Project dialog (Fig. 1.18). Navigate to the book’s examples folder, select the TipCalculator folder and click Choose (Mac) or OK (Windows/Linux). Android Studio stores the Android SDK’s path in the project settings for each project you create. When you open our projects on your system, you’ll receive an error message if the SDK on your system is in a different location from ours. Simply click the OK button in the error dialog that appears, and Android Studio will update the project settings to use the SDK on your system. At this point, the IDE opens the project and displays its contents in the Project window (Fig. 1.19) at the IDE’s left side. If the Project window is not visible, you can view it by selecting View > Tool Windows > Project.

Image

Fig. 1.18 | Open File or Project dialog.

Image

Fig. 1.19 | Project window for the Tip Calculator project.

1.9.2 Creating Android Virtual Devices (AVDs)

As we discussed in the Before You Begin section, you can test apps for multiple Android devices by creating Android Virtual Devices (AVDs) that emulate each unique device.10 In this section you’ll create Android 6 AVDs for the devices we used to test this book’s apps—the Google’s Nexus 6 phone and the Nexus 9 tablet. To create these AVDs, perform the following steps:

10. At the time of this writing, when you set up Android Studio, it configures an AVD that emulates a Google Nexus 5 phone running Android 6.0 (Marshmallow). You’ll still need to perform Section 1.9.2’s steps to create the additional AVDs you need for testing.

1. In Android Studio, select Tools > Android > AVD Manager to display the Android Virtual Device Manager window (Fig. 1.20).

Image

Fig. 1.20 | Android Virtual Device Manager window.

2. Click Create Virtual Device... to open the Virtual Device Configuration window (Fig. 1.21). By default the CategoryPhone” is selected, but you may also create AVDs for Tablet, Wear and TV. For your convenience, Google provides many preconfigured devices that you can use to quickly create AVDs. Select Nexus 6, then click Next.

3. Select the system image for the virtual device you wish to create—in this case, the one with the Android platform Release Name value Marshmallow, the API Level value 23, the ABI (application binary interface) value x86 and the Target value Android 6.0 (with Google APIs), then click Next. This Target creates an Android AVD for Android 6 that also includes support for Google Play Services APIs.

4. For the AVD Name, specify Nexus 6 API 23.

5. Click the Show Advanced Settings button in the lower-left of the Virtual Device Configuration window, then scroll to the bottom of the advanced settings and uncheck the Enable Keyboard Input option and click Finish to create the AVD.

6. Repeat Steps 1–6 to create a Nexus 9 tablet AVD named Nexus 9 API 23—you’ll use this tablet AVD in Chapter 2.

Image

Fig. 1.21 | Virtual Device Configuration window.

If you leave the Enable Keyboard Input option checked in Step 5 above, you can use your computer’s keyboard to enter data into apps running in the AVD. However, this prevents the soft keyboard shown in the screen captures from displaying.

Each AVD you create has many other options specified in its config.ini file. To more precisely match a particular device’s hardware configuration, you can modify config.ini as described at:

1.9.3 Running the Tip Calculator App on the Nexus 6 Smartphone AVD

To test-drive the Tip Calculator app, perform the following steps:

1. Checking your setup. If you have not done so already, perform the steps specified in the Before You Begin section.

2. Launching the Nexus 6 AVD. For this test-drive, we’ll use the Nexus 6 smartphone AVD that you configured in Section 1.9.2. To launch the Nexus 6 AVD, select Tools > Android > AVD Manager to display the Android Virtual Device Manager dialog (Fig. 1.22). Click the Launch this AVD in the emulator button (Image) in the row for the Nexus 6 API 23 AVD. An AVD can take some time to load—do not attempt to execute the app until the AVD finishes loading. When it’s done loading, the AVD will display the lock screen. On an actual device, you unlock it by swiping up with your finger. You perform the swipe gesture on an AVD by placing the mouse over the AVD’s “screen” and dragging up with the mouse. Figure 1.23 shows the AVD after you unlock it.

Image

Fig. 1.22 | Android Virtual Device Manager dialog.

Image

Fig. 1.23 | Nexus 6 AVD home screen after you unlock the AVD.

3. Launching the Tip Calculator app. In Android Studio, select Run > Run 'app' or click the Run 'app' button (Image) on the Android Studio toolbar. This will display a Device Chooser dialog (Fig. 1.24) with the currently running AVD already selected. Click OK to run the Tip Calculator in the AVD (Fig. 1.25) that you launched in Step 2.11 As an alternative to opening the Android Virtual Device Manager dialog in Step 2, you can click the Run 'app' button (Image) on the Android Studio toolbar and the Device Chooser dialog will appear. You can then use the Launch emulator option at the bottom of the dialog to select an AVD to launch, and in which to run the app.

11. The keypad in Fig. 1.25 may differ, based on your AVD’s or device’s Android version or whether you’ve installed and selected a custom keyboard. We configured our AVD to display the dark keyboard for better contrast in our screen captures. To do so: Touch the home (Image) icon on your AVD or device. On the home screen, touch the launcher (Image) icon, then open the Settings app. In the Personal section, touch Language and Input. On an AVD, touch Android Keyboard (AOSP). On a device, touch Google Keyboard (the standard Android keyboard). Touch Appearance & layouts, then touch Theme. Touch Material Dark to change to the keyboard with the dark background.

Image

Fig. 1.24 | Device Chooser for selecting AVD or device on which to test an app.

4. Exploring the AVD. At the AVD screen’s bottom are various soft buttons that appear on the device’s touch screen. You touch these to interact with apps and the Android OS. In an AVD touches are performed by clicking with the mouse. The down button (Image) dismisses the keypad. When there is no keypad on the screen the back button (Image) appears instead. Touching this button takes you back to an app’s prior screen, or back to a prior app if you’re in the current app’s initial screen. The home button (Image) returns you to the device’s home screen. The recent apps button (Image) allows you to view the recently used apps list, so that you can switch back to recent apps quickly. At the screen’s top is the app’s app bar, which displays the app’s name and may contain other app-specific soft buttons—some may appear on the app bar and the rest in the app’s options menu, which appears in the app bar at the top of the screen as Image. The number of options on the app bar depends on the size of the device—we discuss this in Chapter 5.

Image

Fig. 1.25 | Tip Calculator app running in the AVD.

5. Entering a Bill Total. Enter the bill total 56.32 by touching numbers on the numeric keypad. If you make a mistake, press the delete button (Image) in the bottom-right corner of the keypad to erase the last digit you entered. Even though the keypad contains a decimal point, the app is configured so that you may enter only the digits 0–9. Each time you touch a digit or delete one, the app reads what you’ve entered so far and converts it to a number—if you delete all the digits the app redisplays Enter Amount in the TextView at the top of the app. The app divides the value by 100 and displays the result in the blue TextView. The app then calculates and updates the tip and total amounts that are displayed. We use Android’s locale-specific currency-formatting capabilities to display monetary values formatted for the device’s current locale. For the U.S. locale, as you enter the four digits 5, 6, 3 and 2, the bill total is displayed successively as $0.05, $0.56, $5.63 and $56.32, respectively.

6. Selecting a Custom Tip Percentage. The SeekBar allows you to select a custom percentage, and the TextViews in the right column below the SeekBar display the corresponding tip and the total bill. Drag the SeekBar thumb to the right until the custom percentage reads 25%. As you drag the thumb, the SeekBar value continuously changes. The app updates the tip percentage, the tip amount and the bill total accordingly for each SeekBar value until you release the thumb. Figure 1.26 shows the app after you’ve entered the bill amount and selected the tip percentage.

Image

Fig. 1.26 | Tip Calculator after entering the bill amount and selecting a 25% tip.

7. Returning to the home screen. You can return to the AVD’s home screen by tapping the home (Image) button on the AVD.

Troubleshooting AVD Startup

If you have trouble executing an Android Virtual Device, it might be that too much of your computer’s memory is allocated to the AVD. To reduce AVD’s memory size:

1. In Android Studio, select Tools > Android > AVD Manager to open the Android Virtual Device Manager window.

2. You’ll see a list of existing AVDs. For the AVD you’d like to reconfigure, click the pencil icon (Image) in the Actions column.

3. In the Virtual Device Configuration window, click Show Advanced Settings, and scroll to the Memory and Storage section.

4. Decrease value for RAM from the default 1536 MB (1.5 GB) down to 1 GB.

5. Click Finish and close the Android Virtual Device Manager window.

If you still cannot run the AVD, repeat these steps and reduce the memory to 768 MB.

1.9.4 Running the Tip Calculator App on an Android Device

If you have an Android device, you can easily execute an app on it for testing purposes.

1. Enabling the developer options on the device. First, you must enable debugging on the device. To do so, go to the device’s Settings app, then select About phone (or About tablet), locate the Build number (at the bottom of the list) and tap it seven times until you see You are now a developer on the screen. This will enable an entry named Developer options in the Settings app.

2. Enabling debugging on the device. Return to the Settings app’s main screen, select Developer options and ensure that USB debugging is checked—this is the default when you first enable the developer options on the device.

3. Connecting your device. Next, use the USB cable that came with your device to connect the device to your computer. If you’re a Windows user, recall from the Before You Begin section that you might need to install a USB driver for your device. See the following web pages for details:

4. Running Tip Calculator on the Android device. In Android Studio, select Run > Run 'app' or click the Run 'app' button (Image) on the Android Studio toolbar. This will display the Device Chooser dialog that you saw in Fig. 1.24. Select your device from the list of running AVDs and devices. Click OK to run the Tip Calculator on the AVD or device you selected.

Test-Drives for the Book’s Apps

To get a broad sense of the capabilities that you’ll learn in this book, check out the test-drives of the book’s apps in Chapters 29.

Preparing to Distribute Apps

When you build apps for distribution via app stores like Google Play, you should test the apps on as many actual devices as you can. Remember that some features can be tested only on actual devices. If you don’t have Android devices available to you, create AVDs that simulate the various devices on which you’d like your app to execute—the AVD Manager provides many preconfigured AVD templates. When you configure each AVD to simulate a particular device, look up the device’s specifications online and configure the AVD accordingly. In addition, you can modify the AVD’s config.ini file as described in the section Setting hardware emulation options at

This file contains options that are not configurable via the Android Virtual Device Manager. Modifying these options allows you to more precisely match the hardware configuration of an actual device.

1.10 Building Great Android Apps

With over 1.6 million apps in Google Play,12 how do you create an Android app that people will find, download, use and recommend to others? Consider what makes an app fun, useful, interesting, appealing and enduring. A clever app name, an attractive icon and an engaging description might lure people to your app on Google Play or one of the many other Android app marketplaces. But once users download the app, what will make them use it regularly and recommend it to others? Figure 1.27 shows some characteristics of great apps.

12. http://www.statista.com/statistics/266210/number-of-available-applications-inthe-google-play-store/.


Characteristics of great apps

Great Games

• Entertaining and fun.

• Challenging.

• Progressive levels of difficulty.

• Show your scores and use leaderboards to record high scores.

• Provide audio and visual feedback.

• Offer single-player, multiplayer and networked versions.

• Have high-quality animations.

• Offloading input/output and compute-intensive code to separate threads of execution to improve interface responsiveness and app performance.

• Innovate with augmented reality technology—enhancing a real-world environment with virtual components; this is particularly popular with video-based apps.

Useful Utilities

• Provide useful functionality and accurate information.

• Increase personal and business productivity.

• Make tasks more convenient (e.g., maintaining a to-do list, managing expenses).

• Make the user better informed.

• Provide topical information (e.g., the latest stock prices, news, severe-storm warnings, traffic updates).

• Use location-based services to provide local services (e.g., coupons for local businesses, best gas prices, food delivery).

General Characteristics

• Up-to-date with the latest Android features, but compatible with multiple Android versions to support the widest possible audience.

• Work properly.

• Bugs are fixed promptly.

• Follow standard Android app GUI conventions.

• Launch quickly.

• Are responsive.

• Don’t require excessive memory, bandwidth or battery power.

• Are novel and creative.

• Enduring—something that your users will use regularly.

• Use professional-quality icons that will appear in Google Play and on the user’s device.

• Use quality graphics, images, animations, audio and video.

• Are intuitive and easy to use (don’t require extensive help documentation).

• Accessible to people with disabilities (http://developer.android.com/guide/topics/ui/accessibility/index.html).

• Give users reasons and a means to tell others about your app (e.g., you can give users the option to post their game scores to Facebook or Twitter).

• Provide additional content for content-driven apps (e.g., game levels, articles, puzzles).

• Localized (Chapter 2) for each country in which the app is offered (e.g., translate the app’s text and audio files, use different graphics based on the locale, etc.).

• Offer better performance, capabilities and ease-of-use than competitive apps.

• Take advantage of the device’s built-in capabilities.

• Do not request excessive permissions.

• Are designed to run optimally across a broad variety of Android devices.

• Future-proofed for new hardware devices—specify the exact hardware features your app uses so Google Play can filter and display it in the store for only compatible devices (http://android-developers.blogspot.com/2010/06/future-proofing-your-app.html).


Fig. 1.27 | Characteristics of great apps.

1.11 Android Development Resources

Figure 1.28 lists some of the key documentation from the Android Developer site. As you dive into Android app development, you may have questions about the tools, design issues, security and more. There are several Android developer newsgroups and forums where you can get the latest announcements or ask questions (Fig. 1.29). Figure 1.30 lists several websites where you’ll find Android development tips, videos and resources.

Image

Fig. 1.28 | Key online documentation for Android developers.

Image

Fig. 1.29 | Android newsgroups and forums.

Image

Fig. 1.30 | Android development tips, videos and resources.

1.12 Wrap-Up

This chapter presented a brief history of Android and discussed its functionality. We provided links to some of the key online documentation and to the newsgroups and forums you can use to connect with the developer community and get your questions answered. We discussed features of the Android operating system. We introduced the Java, Android and Google packages that enable you to use the hardware and software functionality you’ll need to build a variety of Android apps. You’ll use many of these packages in this book. We also discussed Java programming and the Android SDK. You learned the Android gestures and how to perform each on an Android device and on the emulator. We provided a quick refresher on basic object-technology concepts, including classes, objects, attributes, behaviors, encapsulation, information hiding, inheritance and more. You test-drove the Tip Calculator app on the Android emulator for both smartphone and tablet AVDs.

In Chapter 2, you’ll build your first Android app in Android Studio. The app will display text and an image. You’ll also learn about Android accessibility and internationalization.

Self-Review Exercises

1.1 Fill in the blanks in each of the following statements:

a) In 2007, the __________ was formed to develop, maintain and evolve Android, driving innovation in mobile technology and improving the user experience while reducing costs.

b) The __________ IDE allows you to create, run and debug Android apps.

c) Multitouch screens allow you to control your Android device with __________ involving one touch or multiple simultaneous touches.

d) With web services, you can create __________, which enable you to rapidly develop apps by quickly combining complementary web services, often from different organizations and possibly other forms of information feeds.

e) Android uses a collection of __________, which are named groups of related, predefined classes.

f) The __________, included in the Android SDK, allows you to run Android apps in a simulated environment within Windows, Mac OS X or Linux.

g) 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).

h) A program unit called a(n) __________ houses the methods that perform its tasks.

i) You send messages to an object. Each message is a(n) __________ that tells a method of the object to perform its task.

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.

b) The openness of the Android platform discourages innovation.

c) 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.

d) Attributes are specified by the class’s methods.

e) 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.

1.3 Fill in the blanks in each of the following statements (based on Section 1.8):

a) Objects have the property of __________—although objects communicate with one another, they’re normally not allowed to know how other objects are implemented.

b) The __________ that objects come from are essentially reusable software components; they include attributes and behaviors.

c) The process of analyzing and designing a system from an object-oriented point of view is called __________.

d) With __________, new classes of objects are derived by absorbing characteristics of existing classes, then adding unique characteristics of their own.

e) The size, shape, color and weight of an object are considered __________ of the object’s class.

f) A class that represents a bank account might contain one __________ to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is.

g) You must build an object of a class before a program can perform the tasks that the class’s methods define—this process is called __________.

h) The balance of a bank account class is an example of a(n) __________ of that class.

i) Your project’s requirements define what the system is supposed to do and your design specifies __________ the system should do it.

Answers to Self-Review Exercises

1.1

a) Open Handset Alliance.

b) Android Development Tools (ADT).

c) gestures.

d) mashups.

e) packages.

f) Android emulator.

g) attributes.

h) class.

i) method call.

1.2

a) False. The operating system is open source and free.

b) False. The openness of the platform spurs rapid innovation.

c) True.

d) False. Attributes are specified by the class’s instance variables.

e) True.

1.3

a) information hiding.

b) classes.

c) object-oriented analysis and design (OOAD).

d) inheritance.

e) attributes.

f) method.

g) instantiation.

h) attribute.

i) how.

Exercises

1.4 Fill in the blanks in each of the following statements:

a) Android apps are developed with __________—one of the world’s most widely used programming language, a logical choice because it’s powerful, free and open source.

b) GUI programming in Java is __________ driven, so you’ll write apps that respond to various user interactions such as screen touches and keystrokes.

c) Touching the screen and holding your finger in position is called a(n) __________.

d) Touching the screen, then moving your finger in one direction and releasing it is called a(n) __________.

e) Before running an app in the emulator, you'll need to create a(n) __________, which defines the characteristics of the device on which you want to test, including the hardware, system image, screen size, data storage and more.

f) Performing a task in a program requires a(n) __________ which houses the program statements that actually perform its tasks.

g) 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 __________.

h) __________ helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning.

i) Classes __________ (i.e., wrap) attributes and methods into objects—an object’s attributes and methods are intimately related.

j) A new class of objects can be created quickly and conveniently by __________—the new class absorbs the characteristics of an existing one, possibly customizing them and adding unique characteristics of its own.

k) Unlike actual buttons on a device, __________ buttons appear on the device’s touch screen.

l) __________ was the complete user-interface redesign that Google introduced with Android 5.0.

m) Among its many new features, Android 6.0 introduced a new __________ to make apps easier to install.

1.5 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++.

b) You can reproduce on the emulator most of the Android gestures and controls using your computer’s keyboard and mouse.

c) Objects, or more precisely the classes objects come from, are essentially reusable software components.

1.6 One of the most common objects is a wrist watch. Discuss how each of the following terms and concepts applies to the notion of a watch: object, attributes, behaviors, class, inheritance (consider, for example, an alarm clock), messages, encapsulation and information hiding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.37.136