100% found this document useful (1 vote)
307 views

Android Development

The document provides an overview of a course on Mobile Application Development. It discusses the course objectives which are to understand Android operating systems and components, and develop Android applications using services and tools. The course outcomes are listed as creating data sharing between apps, developing published apps using services, and demonstrating skills using Android development tools. The document then outlines 5 units that make up the course, covering topics like basic widgets, layouts, menus, storing data, and communicating via SMS and email.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
307 views

Android Development

The document provides an overview of a course on Mobile Application Development. It discusses the course objectives which are to understand Android operating systems and components, and develop Android applications using services and tools. The course outcomes are listed as creating data sharing between apps, developing published apps using services, and demonstrating skills using Android development tools. The document then outlines 5 units that make up the course, covering topics like basic widgets, layouts, menus, storing data, and communicating via SMS and email.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

MAD

COMPUTER SCIENCE & ENGINEERING


ANNAMACHARYA INSTITUTE OF
TECHNOLOGY AND
SCIENCES(AUTONOMOUS),TIRUPATI
MOBILE APPLICATION DEVELOPMENT

Course Objectives:
To understand fundamentals of android operating systems.
Illustrate the various components, layouts and views in creating android
applications
To understand fundamentals of android programming.
Course Outcomes:
Create data sharing with different applications and sending and intercepting
SMS.
Develop applications using services and publishing android applications.
To demonstrate their skills of using Android software development tools
Unit 1: Introduction to Android:
The Android 4.1 jelly Bean SDK, Understanding the Android Software Stack, installing the Android SDK,
Creating Android Virtual Devices, Creating the First Android Project,Using the Text view Control, Using
the Android Emulator, The Android Debug Bridge(ADB), Launching Android Applications on a Handset.
Unit 2: Basic Widgets:
Understanding the Role of Android Application Components, Understanding the Utility of Android API,
Overview of the Android Project Files, Understanding Activities, Role of the Android Manifest File,
Creating the User Interface, Commonly Used Layouts and Controls, Event Handling, Displaying
Messages Through Toast, Creating and Starting an Activity, Using the Edit Text Control, Choosing
Options with Checkbox, Choosing Mutually Exclusive Items Using Radio Buttons
Unit 3: Building Blocks for Android Application Design:
Introduction to Layouts, Linear Layout, Relative Layout, Absolute Layout, Using Image View, Frame
Layout, Table Layout, Grid Layout, Adapting to Screen orientation. Utilizing Resources and Media
Resources, Creating Values Resources, Using Drawable Resources, Switching States with Toggle
Buttons, Creating an Images Switcher Application, Scrolling Through Scroll View, playing Audio, Playing
Video,Displaying Progress with Progress Bar, Using Assets.
Unit 4: Using Selection widgets and Debugging:
Using List View, Using the Spinner control, Using the GridView Control,
Creating an Image Gallery Using the Vi1ewPager Control, Using the Debugging
Tool: Dalvik Debug Monitor Service(DDMS), Debugging Application, Using the
Debug Perspective.
Displaying And Fetching Information Using Dialogs and Fragments: What
Are Dialogs?, Selecting the Date and Time in One Application, Fragments,
Creating Fragments with java Code, Creating Special Fragments

Unit 5: Building Menus and Storing Data:


Creating Interface Menus and Action Bars, Menus and Their Types, Creating
Menus Through XML, Creating Menus Through Coding, Applying a Context
Menu to a List View, Using the Action Bar, Replacing a Menu with the Action
Bar, Creating a Tabbed Action Bar, Creating a Drop-Down List Action Bar
Using Databases:
Using the SQLiteOpenHelperclasss, Accessing Databases with the ADB,
Creating a Data Entry Form,
Communicating with SMS and Emails:
Understanding Broadcast Receivers, Using the Notification System, Sending
SMS Messages with Java Code, Receiving SMS Messages, Sending Email,
Working With Telephony Manager.

Text Books
1. Android Programming by B.M Harwani, Pearson Education, 2013.
References Text Books:
1. Android application Development for Java Programmers, James C Sheusi,Cengage
Learning
2. Android In Action by w.Frank Ableson, Robi Sen, Chris King, C. Enrique Ortiz.,
Dreamtech.
3. Professional Android 4 applications development, Reto Meier, Wiley India,2012.
4. Beginning Android 4 applications development, Wei- Meng Lee, Wiley
India,2013

1
UNIT-1
Chapter 1. Introduction to Android

Android is Google’s open source and free Java-based platform for mobile development.
It enables developers to build real-world mobile applications using the Android software
development kit (SDK) and publish them to the Android market. Android comes with several
application programming interfaces (APIs) that make the task of developing full-featured
applications easy. You can even use a camera, accelerometer, or GPS in an Android
application. Moreover, Android is cross-compatible—it can run on Android
phone/tablet/devices of different screen sizes and resolutions. Using Android, you can develop
applications for a wide variety of devices, including phones, e-book readers, netbooks, and
GPS units. Android was initially developed by Android, Inc., a small Palo Alto, California,
company. Google bought this company in July 2005 and released the Android SDK in
November 2007. Periodically, Google releases Android SDK updates. At the time of this
writing, the latest version is 4.1.
Note
Android offers support for Bluetooth, EDGE, 3G, Wi-Fi, Camera, GPS, compass, and accelerometer.

THE ANDROID 4.1 JELLY BEAN SDK


The Android 4.1 Jelly Bean SDK was released with new features for developers in July 2012.
It improves the beauty and simplicity of Android 4.0 and is a major platform release that adds
a variety of new features for users and app developers. A few of the big features of this release
include the following:
• Project Butter—Makes the Jelly Bean UI faster and more responsive. Also CPU Touch
Responsiveness is added, which increases CPU performance whenever the screen is touched.
It uses the finger’s speed and direction to predict where it will be located after some
milliseconds, hence making the navigation faster.
• Faster speech recognition—Speech recognition is now faster and doesn’t require any
network to convert voice into text. That is, users can dictate to the device without an Internet
connection.
• Improved notification system—besides text, the notifications includes pictures and lists too.
Notifications can be expanded or collapsed through a variety of gestures, and users can block
notifications if desired. The notifications also include action buttons that enable users to call
directly from the notification menu rather replying to email.
• Supports new languages—Jelly Bean includes support for several languages including
Arabic, Hebrew, Hindi, and Thai. It also supports bidirectional text.
• Predictive keyboard—On the basis of the current context, the next word of the message is
automatically predicted.
• Auto-arranging Home screen—Icons and widgets automatically resize and realign as per
the existing space.
• Helpful for visually impaired users—The Gesture Mode combined with voice helps
visually impaired users to easily navigate the user interface.
• Improved Camera app—The Jelly Bean Camera app includes a new review mode of the
captured photos. Users can swipe in from the right of the screen to quickly view the captured
photos. Also, users can pinch to switch to a new film strip view, where they can swipe to delete
photos.
• Better communication in Jelly Bean—two devices can communicate with Near Field
Communication (NFC); that is, two NFC-enabled Android devices can be tapped to share data.
Also, Android devices can be paired to Bluetooth devices that support the Simple Secure
Pairing standard by just tapping them together.
• Improved Google Voice search—Jelly Bean is equipped with a question and answer search
method that helps in solving users’ queries similar to Apple’s popular Siri.
• Face Unlock—unlocks the device when the user looks at it. It also prevents the screen from
blacking out. Optionally “blink” can be used to confirm that a live person is unlocking the
device instead of a photo.
• Google Now—provides users “just the right information at just the right time.” It displays
cards to show desired information automatically. For example, the Places card displays nearby
restaurants and shops while moving; the Transit card displays information on the next train or
bus when the user is near a bus stop or railway station; the Sports card displays live scores or
upcoming game events; the Weather card displays the weather conditions at a user’s current
location, and so on.
• Google Play Widgets—Provides quick and easy access to movies, games, magazines, and
other media on the device. It also suggests new purchases on Google Play.
• Faster Google Search—Google Search can be opened quickly, from the lock screen and
from the system bar by swiping up and also by tapping a hardware search key if it is available
on the device.
• Supports antipiracy—this feature supports developers in the sense that the applications are
encrypted with a device-specific key making it difficult to copy and upload them to the Internet.

UNDERSTANDING THE ANDROID SOFTWARE STACK


The Android software stack consists of a Linux kernel and a collection of C/C++ libraries that
are exposed through an application framework for application development.
The Android software stack consists of four main layers, as shown in Figure 1.1.
Figure 1.1. Android software stack

The following list gives a brief description of each of the layers in the software stack:
• Linux kernel— the kernel on which Android is based contains device drivers for various
hardware components of an Android device, including Display, Camera, Keypad, Wi-Fi, Flash
Memory, and Audio.
• Libraries— the next layer on top of the Linux kernel is the libraries that implement different
Android features. A few of these libraries are listed here:
• WebKit library—Responsible for browser support.
• FreeType library—Responsible for font support.
• SQLite library—Provides database support.
• Media libraries—Responsible for recording and playback of audio and video formats.
• Surface Manager Library— Provides graphics libraries that include SGL and OpenGL for
2D and 3D graphics support.
• Android runtime— the engine at the same layer as the libraries. It provides a set of core
Android libraries and a Dalvik virtual machine that enable developers to write Android
applications using Java. The core Android libraries provide most of the functionality available
in the core Java libraries, as well as the Android-specific libraries. Dalvik VM is explained in
detail later in this chapter.
• Application framework— provides the classes that enable application developers to develop
Android applications. It manages the user interface, application resources, and abstraction for
hardware access.
• Application layer—displays the application developed and downloaded by users, along with
the built-in applications provided with the Android device itself.
INSTALLING THE ANDROID SDK
For developing native Android applications that you can publish on the Google Play
marketplace, you need to install the following four applications:
• The Java Development Kit (JDK) can be downloaded from
http://oracle.com/technetwork/java/javase/downloads/index.html.
• The Eclipse IDE can be downloaded from http://www.eclipse.org/downloads/.
• The Android Platform SDK Starter Package can download from
http://developer.android.com/sdk/index.html.
• The Android Development Tools (ADT) Plug-in can be downloaded from
http://developer.android.com/sdk/eclipse-adt.html. The plug-in contains project templates and
Eclipse tools that help in creating and managing Android projects.
The Android SDK is not a full development environment and includes only the core SDK
Tools, which are used to download the rest of the SDK components. This means that after
installing the Android SDK Tools, you need to install Android platform tools and the other
components required for developing Android applications. Go
to http://developer.android.com/sdk/index.html and download the package by selecting the
link for your operating system. For Windows users, the provided .exe file is named installer_r18-
windows.exe. After downloading the file, double-click it to initiate the installation process. The
Android SDK Manager window opens. The dialog boxes that you see from now on are from
the Windows installer, and the screens may vary from other operating systems’ installers.
The first screen is a Welcome screen. Select the Next button to move to the next screen.
Because the Android SDK requires the Java SE Development Kit for its operation, it checks
for the presence of JDK on your computer. If JDK is already installed, you see the screen shown
later in Figure 1.4. If the JDK is not found, it displays a button with the
caption Visit java.oracle.com, which you can use to download and install JDK.
On selecting the button, you are taken to
http://www.oracle.com/technetwork/java/javase/downloads/index.html. This site shows links
to download Java Platform, Standard Edition, Java SE Development Kit (JDK) bundles, and
additional resources. The latest version of Java available at the time of this writing is JDK
version 1.7. Select the JDK link that suits your platform (Windows, Linux, or Mac) and double-
click the downloaded file to begin JDK installation. You will probably see a Security Warning
dialog box, asking whether you want to run or cancel the execution of the file. Select
the Run button to initiate JDK installation. The first screen that you see is a Java Setup Wizard
Welcome screen. Select the Next button to see the Custom Setup dialog box for selecting optional
JDK features that you want to install, as shown in Figure.
Figure 1.2. The Custom Setup dialog box

Three categories of features (Development Tools, Source Code, and Public JRE) are displayed,
and you can select from the respective drop-down lists to choose the list of features in the
category you want to install. The dialog box also asks for a drive location where you want to
install the JDK. The default location displayed is C:\Program Files\Java\jdk1.7.0_04\, but you can
use the Change button to select another location. Keep the default settings and click
the Next button to continue. The selected program features are installed, followed by a dialog
box that prompts for the destination folder to install the Java runtime environment (JRE), as
shown in Figure 1.3.
Figure 1.3. Dialog box prompting for the JRE installation location

The dialog box displays the default location for installing the JRE ( C:\Program Files\Java\jre7).
Use the Change button to place the program elsewhere. Keep the default location and select
the Next button to continue. The Java files are copied and installed on your machine. If the
installation is successful, a confirming dialog box is displayed. Select Finish to exit the wizard.
After Java installation, the Android SDK Tools Setup Wizard automatically resumes.
If Java is already installed on your computer before beginning with Android SDK installation,
the wizard detects its presence and displays the version number of the JDK found on the
machine, as shown in Figure 1.4.
Figure 1.4. Dialog box informing you that the JDK is already installed on the computer

Select the Next button. You get a dialog box asking you to choose the users for which Android
SDK is being installed. The following two options are displayed in the dialog box:
• Install for anyone using this computer
• Install just for me
Select the Install for anyone using this computer option and click Next. The next dialog prompts you
for the location to install the Android SDK Tools, as shown in Figure 1.5. The dialog also
displays the default directory location for installing Android SDK Tools as C:\Program Files
(x86)\Android\android-sdk, which you can change by selecting the Browse button. Keep the default
directory for installing Android SDK Tools unchanged; then select the Next button to continue.
Figure 1.5. Dialog box to specify the Android SDK Tools installation location

The next dialog box asks you to specify the Start Menu folder where you want the program’s
shortcuts to appear, as shown in Figure 1.6.

Figure 1.6. Dialog box to select the Start menu shortcut folder

A default folder name appears called Android SDK Tools. If you do not want to make
a Start Menu folder, select the Do not create shortcuts check box. Let’s create the Start Menu folder by
keeping the default folder name and selecting the Install button to begin the installation of the
Android SDK Tools. After all the files have been downloaded and installed on the computer,
select the Next button. The next dialog box tells you that the Android SDK Tools Setup Wizard is
complete and the Android SDK Tools have successfully installed on the computer.
Select Finish to exit the wizard, as shown in Figure 1.7.

Figure 1.7. Successful installation of the Android SDK Tools dialog box

Note that the check box Start SDK Manager (to download system images) is checked by default.
It means that after the Finish button is clicked, the Android SDK Manager, one of the tools in
the Android SDK Tools package, will be launched. Android SDK is installed in two phases.
The first phase is the installation of the SDK, which installs the Android SDK Tools, and the
second phase is installation of the Android platforms and other components.

Adding Platforms and Other Components


In this step you see how to use the Android SDK Manager to download and install the
important SDK packages required for the development environment. The Android SDK
Manager (see Figure 1.8) that opens up shows the list of all the packages and their installation
status. The dialog box shows that the Android SDK Tools package is already installed on the
machine. To install any other package, you just need to check its check box. The Android SDK
Manager recommends a platform by checking the Android 4.1 (API 16) and Google USB
Driver package by default, which means the six components beneath the node will also be
checked.
Figure 1.8. Android SDK Manager showing the list of packages and their current status

You can check more packages and uncheck existing packages to determine which API
you want to install. Because you want to work with the latest Android API, leave the default
selected. Select all the packages listed under the Extras node as well, and choose the Install 7
packages button at the bottom to initiate installation. The next dialog box you see shows the list
of the packages that you have selected to install, the package description, and license terms.
You need to select the Accept All option, followed by the Install button to begin installation, as
shown in Figure 1.9.
Figure 1.9. Dialog box to accept the license terms for the selected packages and to begin installation

An Android SDK Manager Log window appears showing the downloading and installation
progress. It also shows the list of packages that have been loaded, Android SDK Platform tools
that have been downloaded and installed on the machine, and the ones that are still being
downloaded (see Figure 1.10—left). After you select the Close button, the next dialog window
is the ADB Restart window that provides information about updates and asks whether you want
to restart ADB, as shown in Figure 1.10 (right). Select the Yes button in the dialog to restart
ADB.

Figure 1.10. Android SDK Manager Log showing the status of different packages (left), and the ADB Restart
dialog box, prompting you to restart ADB (right)
You learn about ADB in detail later in this chapter. For now, it’s enough to know that
ADB (Android Debug Bridge) is a command-line tool popularly used to communicate with
emulator and Android devices.
The next dialog box is the Android SDK Manager, as shown in Figure 1.11. The dialog box
confirms that the Android SDK Platform tools, Android 4.1 (API16), and its components have
been successfully installed on your machine.

Figure 1.11. Android SDK Manager showing that all the desired packages have been successfully installed on the
machine

You don’t need the Android SDK Manager window for now, so you can go ahead and close
it.
An Android application is a combination of several small components that include Java
files, XML resource and layout files, manifest files, and much more. It would be very time-
consuming to create all these components manually. So, you can use the following applications
to help you:
• Eclipse IDE—An IDE that makes the task of creating Java applications easy. It provides a
complete platform for developing Java applications with compiling, debugging, and testing
support.
• Android Development Tools (ADT) plug-in—A plug-in that’s added to the Eclipse IDE
and automatically creates the necessary Android files so you can concentrate on the process of
application development.
Before you begin the installation of Eclipse IDE, first set the path of the JDK that you
installed, as it will be required for compiling the applications. To set the JDK path on Windows,
right-click on My Computer and select the Properties option. From the System Properties dialog box
that appears, select the Advanced tab, followed by the Environment Variables button. A dialog box,
Environment Variables, pops up. In the System variables section, double-click on the Path variable.
Add the full path of the JDK (C:\Program Files\Java\jdk1.7.0_04\bin\java.exe) to the path variable and
select OK to close the windows.

Installing Eclipse
Eclipse IDE is a multi-language software development platform commonly used for
developing Java applications. You can add plug-ins to extend its features for developing
applications in other languages. Eclipse can be downloaded from the following
URL: http://www.eclipse.org/downloads/. The Eclipse Classic and the Eclipse IDE for Java
Developers are recommended. Just remember that both the JDK and Eclipse must be for the
same version, either 32 bit or 64 bit. The latest version, Eclipse Classic 3.7, is available at the
time of this writing.
Note
To develop Android applications with Eclipse IDE, you need to extend its features by adding the Android
Development Tools (ADT) plug-in to it.
Eclipse is a self-contained executable file—that is, all you need to do to install Eclipse
is to unzip the downloaded file to any desired folder. To launch Eclipse, run the Eclipse.exe file.
Eclipse IDE starts by displaying its logo, followed by a Workspace Launcher dialog box, as shown
in Figure 1.12. The Workspace Launcher dialog prompts for the location of the workspace folder
where the Eclipse project files will be stored. A default location is displayed that you can
change by selecting the Browse button.
Figure 1.12. The first screen you see after launching Eclipse IDE, asking for the Workspace location to save
applications

The Use this as the default and do not ask again box can be checked if you don’t want Eclipse
to prompt for the workspace every time it is launched. I recommend not checking this box, as
it is better to have a separate workspace for each project to keep them organized. Select
the OK button to continue. When Eclipse finishes loading, an Eclipse Welcome screen is
displayed, as shown in Figure 1.13.

Figure 1.13. Eclipse Welcome screen

Select the curved-arrow icon at the top right of the screen to go to the Workbench, as shown
in Figure 1.14.
Figure 1.14. The Eclipse Workbench, showing windows and panels

You can see that all the windows in the Workbench (Package Explorer, Editor Window,
Debug window, and Task List), are blank at the moment. These windows update their content as
you develop Android applications. One more step is needed before you begin Android
application development: installing the Android Development Tools (ADT) plug-in.

Installing the Android Development Tools (ADT) Plug-in


Android Development Tools (ADT) is a plug-in for the Eclipse IDE that provides a
powerful, integrated environment to build Android applications. It makes the task of
developing Android applications easy. It integrates with Eclipse to add functionality for
creating, testing, debugging, and deploying Android applications.
Note
The ADT plug-in creates all the necessary base files required by the application.
To install the ADT plug-in, select the Help, Install New Software... option from the Eclipse
IDE. You see a dialog box asking for the location of the website from which you want to install
new software, as shown in Figure 1.15 (left). Select the Add button to add a website or
repository location. An Add Repository dialog box appears, as shown in Figure 1.15 (right). Enter
the name of the repository in the Name text box. Specify the name of the repository as ADT Plug-
in, although it can be any other address. In the Location
box, specify the location of the repository
as https://dl-ssl.google.com/android/eclipse/ and click OK.

Figure 1.15. The dialog box prompting for the location of the software installation website (left), and the dialog
box to add the new repository information (right)

Eclipse accesses the list of developer tools available at the specified site and displays
it, as shown inFigure 1.16. In the figure, you can see that an entry named Developer Tools is
displayed, along with four child nodes: Android DDMS, Android Development Tools, Android Hierarchy
Viewer, and Android Traceview. You need to install all four tools, so select the parent node,
Developer Tools (its child nodes will be auto-selected), and select the Next button.
Figure 1.16. Dialog box displaying the list of developer tools available in the added repository

You see a dialog box to Review Licenses for the ADT. Read the License Agreement,
select the I accept the terms of the license agreements radio button if you agree with the terms and
conditions, and select the Finish button, as shown in Figure 1.17.
Figure 1.17. Dialog box to review and accept/reject the license agreement

The ADT plug-in is then downloaded and installed in Eclipse. After installation of the
ADT plug-in, you get a Software Updates dialog box asking to restart Eclipse. To make the ADT
plug-in show up in the IDE, you need to restart Eclipse. Select the Restart Now button from
the Software Updates dialog box to make the installation changes take effect.
Note
If an older version of ADT is already installed in Eclipse, then instead of reinstalling, you just need to update
it. Select Help, Check for Updates option. A new version of ADT is displayed, and you can update the ADT
plug-in by copying and installing the new version.

Making the ADT Plug-in Functional


To make the ADT plug-in functional inside Eclipse, the plug-in needs to point to the
Android SDK. Launch the Eclipse IDE and select the Window, Preferences option. In
the Preferences dialog box, select the Android node (see Figure 1.18—left) and set the SDK
Location field to specify the path where the Android SDK is installed on your disk (see Figure
1.18—right).
Figure 1.18. (left) The Preferences window to specify the location of Android SDK installation, and (right) the
list of supportable platforms displayed after specifying the location of the Android SDK installation

On specifying the path of the Android SDK, a list of SDK Targets is displayed. You can
now develop and test Android applications against any of the displayed targets. You need to
select the Apply button and click OK to reload the SDK Targets and close the Preferences window.
Eclipse now has the ADT plug-ins attached.
The Android applications that you develop need to be tested and debugged before they
are loaded on the actual Android device. The Android SDK provides several virtual devices
that you can use to test and debug your applications.

CREATING ANDROID VIRTUAL DEVICES


An Android Virtual Device (AVD) represents a device configuration. There are many
Android devices, each with different configuration. To test whether the Android application is
compatible with a set of Android devices, you can create AVDs that represent
their configuration. For example, you can create an AVD that represents an Android device
running version 4.1 of the SDK with a 64MB SD card. After creating AVDs, you point the
emulator to each one when developing and testing the application. AVDs are the easiest way
of testing the application with various configurations.
To create AVDs in Eclipse, select the Window, AVD Manager Option. An Android Virtual Device
Manager dialog opens, as shown in Figure 1.19. The dialog box displays a list of existing AVDs,
letting you create new AVDs and manage existing AVDs. Because you haven’t yet defined an
AVD, an empty list is displayed.
Figure 1.19. The AVD Manager dialog

Select the New button to define a new AVD. A Create new Android Virtual Device (AVD) dialog box,
appears (see Figure 1.20—left). The fields are as follows:
• Name—used to specify the name of the AVD.
• Target—used to specify the target API level. Our application will be tested against the
specified API level.
• CPU/ABI—determines the processor that we want to emulate on our device.
• SD Card—used for extending the storage capacity of the device. Large data files such as
audio and video for which the built-in flash memory is insufficient are stored on the SD card.
• Snapshot—Enable this option to avoid booting of the emulator and start it from the last saved
snapshot. Hence, this option is used to start the Android emulator quickly.
• Skin—Used for setting the screen size. Each built-in skin represents a specific screen size.
You can try multiple skins to see if your application works across different devices.
• Hardware—used to set properties representing various optional hardware that may be
present in the target device.
Figure 1.20. (left) Dialog to create new AVD, and (right) specifications of new AVD, demoAVD

In the AVD, set the Name of the AVD to demoAVD, choose Android 4.1—API Level 16 for
the Target, set SD Card to 64 MiB, and leave the Default (WVGA800) for Skin. In the Hardware section,
three properties are already set for you depending on the selected target. The Abstracted LCD
density is set to 240; the Max VM application heap size is set to 48, and the Device RAM size is set
to 512. You can select these properties and edit their values, delete them, and add new properties
by selecting the New button. New properties can include Abstracted LCD density,DPad
support, Accelerometer, Maximum horizontal camera pixels, Cache partition size, Audio playback support,
and Track-ball support, among others. Finally, select the Create AVD button (see Figure 1.20—
right) to see how to create the virtual device called demoAVD.

Note
You learn about the API and its different levels in Chapter 2, “Basic Widgets.”

The new AVD, demoAVD, is created and displayed in the list of existing AVDs, as
shown in Figure 1.21.
Figure 1.21. The newly created AVD listed in the AVD Manager

Note
The larger the allocated SD Card space, the longer it takes to create the AVD. Unless it is really required,
keep the SD Card space as low as possible. I would recommend keeping this small, like 64MiB.

You now have everything ready for developing Android applications—the Android
SDK, the Android platform, the Eclipse IDE, the ADT plug-in, and an AVD for testing Android
applications. You can now create your first Android application.

CREATING THE FIRST ANDROID PROJECT


To create an application, open Eclipse and choose File, New, Android Application Projector
click the Android Project Creator icon on the Eclipse toolbar, or select the File, New, Other option. A
dialog box appears asking you to select the wizard you want to use for the new application.
Select Android Application Project and click Next. You see a dialog box asking for information
about the new Android application, as shown in Figure 1.22 (left). In the Application Name box,
enter the name of the application. Let’s name the application HelloWorldApp. TheProject
Name box shows the name of the project automatically by default. The project name assigned
is the same as the application name, that is, HelloWorldApp. You can change the project name if
desired. The Package Name box shows the default package name,com.example.helloworldapp. Let us
enter the package name ascom.androidunleashed.helloworldapp. The package name serves as a
unique identifier for the application. A package name may contain uppercase or lowercase
letters, numbers, and underscores. The parts of the package name may only begin with letters.
The package name must be unique across all packages installed on the Android system. We
use the syntaxcom.androidunleashed.project_name for the package names assigned to all the
applications in this book. Remember, once an application is published, you cannot change the
package name. If you change the application name, then it is considered to be a different
application.
Figure 1.22. Dialog box to specify the new project information (left), and configuring the launcher icon (right)

From the Build SDK drop-down, select the version of Android that represents the device
most commonly used by your target audience. Let’s select the Android 4.1 (API 16) as the target
platform. From the Minimum Required SDK select the minimum version of the Android platform
that is required by the application to run. That is, the application will not run if the device’s
API level is lower than the API level specified through this drop-down list. Select API 8: Android
2.2 (Froyo) from the Minimum Required SDK drop-down. It also means the application requires at
least API 8 to run. Because this is a new project, select the Create Project in Workspace check box.
By default, the Location where the application is stored on our disk drive is set to the workspace
specified when opening Eclipse for the first time. Click Next to move further.
The next dialog, Configure Launcher Icon (see Figure 1.22—right), is used for configuring
the icon for the application. The dialog shows three options—Image, Clipart, and Text—to define
the icon for our application. The Clipart option is selected by default showing one of the built-
in clipart. Select the Choose button to open the list of available clipart and then select one of
them as our application’s icon. We can also select the Image option to specify the custom image
to be used as our application’s icon. The Text option, when selected, displays a text box where
we can enter text to represent our application. Select the Font button to change the font of the
text and also to specify the font size and style. The dialog box also shows a Trim Surrounding
Blank Space check box that we can select to remove the extra blank space around the chosen
image, clipart, or text. A scrollbar is also provided to specify the padding around the icon. The
icon can be set to appear at the center of the assigned space or can be cropped to accommodate
the assigned space. The dialog also shows buttons to make the icon appear in a square or circle
shape. Also, two buttons, Background Color andForeground Color, are provided that display
different colors that can be used as the foreground and background color of the icon. After
defining the icon, click Next to move further.
Note
The Android Project Wizard automatically creates all the required files for the Android application.
The next dialog prompts us to select whether we want to create an activity. If we want
to create an activity, the dialog box asks whether we want to create
a BlankActivity or MasterDetailFlowactivity (see Figure 1.23—left). The BlankActivity option
creates a new blank activity, whereas theMasterDetailFlow option creates two master and detail
fragments and two activities. We discuss activities and fragments later. To keep things simple,
we go for blank activity for this application. Because, we want to create a blank activity, select
the Create Activity check box and theBlankActivity option from the list and then click Next. The
next dialog confirms the creation of the activity. The Android SDK assigns the default
name MainActivity to the newly created activity. Also, the layout file is assigned the default
name as activity_main. The Title assigned to the activity by default is MainActivity (see Figure
1.23—right). Let’s name the activityHelloWorldAppActivity. The layout filename and title name
automatically change to reflect the newly assigned activity name. The layout name
becomes activity_hello_world_app, and theTitle of the application also changes
to HelloWorldAppActivity. We can always change the auto-assigned layout filename and title of
the application. Keeping the auto-assigned layout filename and the title unchanged, create the
application by clicking Finish.

Figure 1.23. Dialog box to select the type of activity to create (left), and specifying information of the newly
created activity (right)

Note
The AVDs with newer SDKs can run applications that require older SDKs. The opposite is not true; that is,
an application that requires a newer SDK will not run on an AVD with an older SDK.
The application is created, and the Package Explorer shows the files automatically created
by the ADT plug-in, as shown in Figure 1.24.
Figure 1.24. The Package Explorer displaying all the directories, subdirectories, and files automatically created
for the application HelloWorldApp by ADT

You learn about the role of the different folders and their respective content in the next
chapter. For now, we concentrate on the two files that play important roles in almost all Android
applications:
• The XML file, activity_hello_world_app.xml, found in the res/layout folder—The file that
defines the user interface of the application. It contains controls such
as TextView, Button,EditText, and CheckBox that are arranged on the display. The definitions in this
file control how the user interacts with the application.
• The Java file, HelloWorldAppActivity.java, found in the src folder—The file where
action code of the controls defined in the layout file activity_hello_world_app.xml is written.
Different events that occur via the controls in the layout file are handled with Java code. The
data entered by the user is fetched and processed with this Java file.
The idea of separating the user interface from the action code is to isolate the
presentation layer from the business logic, allowing developers to change the user interface
without rewriting the code itself. As I talk about the XML and Java files, I will frequently use
several terms described in Table 1.1.

Table 1.1. Common Terms

Laying Out the Application


The screen of the application is defined by an XML file. The controls through which
the desired information is displayed to the user and through which the user interacts with the
application are defined in XML code. To define a screen of an application, you open
theactivity_hello_world_app.xml file, which is automatically created by the ADT plug-in in the
res/layoutfolder. You can create more layout files to represent different screens of an
application. All layout files are stored in the res/layout directory of the Android project. When
you double-click on the activity_hello_world_app.xml file, you see the graphical layout of the
application in the center window, as shown in Figure 1.25. The layout that you see is the default
created by the ADT plug-in. There are two tabs at the bottom of the panel: Graphical
Layout andactivity_hello_world_app.xml. The Graphical Layout tab shows the layout in theEclipse's
Visual Designer, and the activity_hello_world_app.xml tab shows the XML code of the layout file.

Figure 1.25. The layout file activity_hello_world_app.xml in the Visual Designer

Using the Visual Designer


The Visual Designer provided by Eclipse displays the layout file graphically. On the
left side of the display, the designer shows a list of controls categorized in different categories.
Through these controls, you can quickly design a screen. All you need to do is drag the desired
control from the left side and drop it on the layout file. You can also configure the controls by
settings their properties. The Properties panel is hidden by default. To make the Properties panel
visible, select the Window, Show View, Other, General, Properties option. After you select a control,
all its properties are displayed in the Properties panel.
Understanding the XML Version of the Layout File
The XML code of the layout file activity_hello_world_app.xml can be seen by selecting
theactivity_hello_world_app.xml tab at the bottom of the panel. The default code is shown inListing
1.1.

Listing 1.1. Default Code in the Layout File activity_hello_world_app.xml

<RelativeLayout #1
xmlns:android="http://schemas.android.com/apk/res/android" #2
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" #3
android:layout_height="match_parent">
<TextView #4
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello" #5
tools:context=".HelloWorldAppActivity" />
</RelativeLayout>

Statement #1 declares that all the controls are laid out


in RelativeLayout. The RelativeLayoutis the default layout and arranges the controls in relation to
the existing controls. Layouts are also known as containers, as they hold and arrange the controls
within them. You learn about the layouts in detail in Chapter 3, “Laying Out Controls in
Containers.”
Statement #2 defines the Android namespace. This attribute should always be set
to http://schemas.android.com/apk/res/android. Namespaces are for assigning unique
identifications to application elements, thus avoiding any collisions between element names.
Even if you define another element in an XML schema with a name already in use in the
Android API (to define its elements), collision will not occur, as they are defined in their
respective namespaces.
Statement #4 defines the most basic UI control, TextView, which is commonly used for
displaying information. In Android, the control that shows up on the screen and is used for
displaying information and handling events is known as a View. The TextView that you see in
the layout file (see Listing 1.1) is one of the most common views.
All the Views are placed inside a container. The most common attributes required for
laying out a screen view are layout_width and layout_height. These attributes are also known
as LayoutParams in the Android SDK. The layout_width and layout_height attributes specify the
width and height that aView can have. The two most common values
for layout_width and layout_height arematch_parent and wrap_content constants.
The match_parent value in statement #3 tells the Android system to fill as much space as
possible on the screen based on the available space of the parent layout. The wrap_content value
tells the Android system to take up only as much space as needed to show the View. As the
view’s content grows, the View’s viewable space also grows. Remember,
the layout_width and layout_height attributes are essential attributes, and if you don’t provide
values for these attributes, the Android application will crash when rendering the view. The
value of the attributes android:layout_centerHorizontal andandroid:layout_centerVertical are set
to "true" to make the TextView control’s text appear at the horizontal and vertical center of the
view.
Statement #5 requires that the text to be displayed via the TextView control must be
fetched from the strings resource file, strings.xml, defined in res/values folder. The text defined in
the helloresource in the strings.xml file is assigned to the TextView for display. For now, let’s leave
the resource files alone and talk about action code.

Note
For Android 2.2 and lower versions, match_parent was used as fill_parent. The optionfill_parent is deprecated
but is still supported for backward compatibility.

Defining Action Code Through Java


Recall that the Android application Java file is the Activity automatically created in
the src folder by the ADT plug-in. An Activity represents a screen of the application and enables
user interaction. While creating the application, you defined the Activity name
as HelloWorldAppActivity; hence the Java file is named HelloWorldAppActivity.java. The default
code in the Java activity fileHelloWorldAppActivity.java is shown in Listing 1.2.

Listing 1.2. Default Code in the Java Activity File HelloWorldAppActivity.java

package com.androidunleashed.helloworldapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class HelloWorldAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) { #1
super.onCreate(savedInstanceState); #2
setContentView(R.layout.activity_hello_world_app); #3
}

@Override
public boolean onCreateOptionsMenu(Menu menu) { #4
getMenuInflater().inflate(R.menu.activity_hello_world_app, menu);
return true;
}
}

The Java file is created and maintained in the


package com.androidunleashed.helloworldappthat you defined at the time of application creation.
The first statement of the code in Listing 1.2confirms it. The file imports the desired class files
and also inherits the Activity class. TheonCreate() method is invoked when the Activity is started.
It calls the onCreate() method of the super class (the Activity class) for initializing an activity.
In statement #1, the parameter Bundle savedInstanceState refers to a bundle used to pass
information between different activities.
Statement #2 is essential for activity initialization. If you don’t write this statement into
the Java file, you get a runtime exception.
Statement #3 defines the screen (user interface) of the activity HelloWorldAppActivity.
Basically, the user interface defined in the layout file activity_hello_world_app.xml is set as the
content of an activity file.
The parameter R.layout.activity_hello_world_app in the setContent() method refers to
the activity_hello_world_app.xml file of the project’s res/layout folder. The character R in the
parameter refers to the auto-generated R.java class file, which we discuss in the next chapter.
Statement #4 defines the onCreateOptionsMenu () method that is meant for dealing with
menus.
Let’s keep the existing default code
of activity_hello_world_app.xml andHelloWordlAppActivity.java and run the application to see the
output.
To run the application, you need to create an Eclipse launch configuration and choose a
virtual device on which to run the application. The Android ADT provides two options for
creatinglaunch configurations:
• Run configuration—Used to run an application on a given device
• Debug configuration—Used to debug an application while it’s running on a given device
To create an Eclipse launch configuration, select the Run, Debug Configurations option. A Debug
Configurations dialog box opens. Double-click the Android Application in the left pane (see Figure
1.26—left). The wizard inserts a new configuration named New_configuration, as shown
in Figure 1.26 (right).

Figure 1.26. (left) The Debug Configurations window, and (right) defining a new configuration through the
Debug Configurations window
Let’s rename the configuration to HelloWorldApp_configuration. You need to specify the Android
project name that you want to launch in the Project box. So, click the Browse button and choose
the Android project HelloWorldApp. From the Launch drop-down list in the Launch Action section,
select the Activity filecom.androidunleashed.helloworldapp.HelloWorldAppActivity option, followed by
theApply button (see Figure 1.27—left). Next, you need to define a device on which to run the
application. Select the Target tab in the same dialog box. You get the screen shown in Figure
1.27 (right).

Figure 1.27. (left) Creating a new configuration called HelloWorldApp_configuration, and (right) defining the
target AVD for the new configuration

The Deployment Target Selection Mode displays the following three options:
• Always prompt to pick device—allows you to choose the device or AVD to connect to when
using this launch configuration.
• Launch on all compatible devices/AVDs—deploys the application automatically on all the
compatible AVDs or devices available.
• Automatically pick compatible device—deploys the application on the AVDs that are
selected. If none of the AVDs are selected, the application is launched on the compatible AVDs
or devices available.
Select the third option, Automatically pick compatible device, followed by selecting the
demoAVD that we created earlier to deploy the application automatically on this virtual device
(seeFigure 1.27—right). We select the demoAVD check box because we want to test the
application against the Android 4.1 target. You can create more AVDs targeting other platforms
from the AVD Managerwindow, and all the defined AVDs automatically appear in this dialog
box, allowing you to select the desired target to test the application. After selecting the AVD,
select the Apply button, followed by Close button, to save the launch configuration file.

Running the Application


Once the launch configuration file has been made, you can run the Android application by
either selecting the Run icon from the Eclipse IDE toolbar, selecting the Run option from
the Run menu, or pressing the Ctrl+F11 keys. Before displaying the application output, the
emulator displays several boot screens. The first is shown in Figure 1.28 (left). The window’s
title bar contains the port number of your computer on which the emulator is running (5554)
and the AVD name (demoAVD). The second screen shows the Android logo, which is the same
logo Android OS users see when they boot their phones. The second screen shows that the
loading phase is complete and then displays the default locked Home screen, as shown
in Figure 1.28 (right).

Figure 1.28. (left) The first boot screen after running an application showing the Android logo, and (right) the
second boot screen showing the default locked Home screen

To unlock the Home screen, either select the Menu button on the emulator, press
the F2 key on your computer, or drag the lock to the right side and drop it over the other lock
that appears there, as shown in Figure 1.29 (left). After the emulator is unlocked, the Home
screen appears (see Figure 1.29—middle), followed by the output of the application, as shown
in Figure 1.29 (right).
Figure 1.29. (left) Dragging the lock to the right to unlock the Home screen, (middle) the emulator showing the
Home screen, and (right) the output of theHelloWorldApp application

You can see that the application’s title, HelloWorldAppActivity, appears in the title bar of
the emulator, and a text message, Hello world!, is displayed via the TextView control. The text to
theTextView is assigned via the strings resource file, strings.xml. The output of the application
confirms that the Activity is running correctly in the emulator.
If you feel that the screen shown by the emulator is too big, you can reduce it to the
actual device size by selecting the Window, AVD Manager option. From the Android Virtual Device
Managerdialog box that opens up (see Figure 1.30—left), select demoAVD and click
the Start button. Select theScale display to real size check box (see Figure 1.30—right) and then
click the Launchbutton to start the emulator.
Figure 1.30. (left) Select the AVD to scale to the real device size, and (right) setting options in the Launch
Options dialog.

Don’t close the emulator screen; let it stay active to save the emulator’s loading time
for running other applications. Whenever you run an application, the ADT checks for a running
emulator and deploys it if found.
The Dalvik Virtual Machine (Dalvik VM)
While running Android applications, the Android runtime provides the Dalvik virtual
machine that provides an environment to deploy and run Android applications. Dalvik VM is
the Android platform’s virtual machine written by Dan Bornstein, who named it after a town
in Iceland. Android applications run under this virtual machine. It is a specialized virtual
machine designed specifically for Android and optimized for mobile devices with limited
battery, memory, and computation capability. When you run an application, the Android SDK
accesses all the layout and variable information in the XML files, converts it into Java source
code, and places it in the R.java file. The Java code in the R.java class file is compiled into the
Java byte code files (.class files), which, with the help of a tool named dx(included in the
Android SDK), is converted into Dalvik byte code and stored in .dex format. The Dalvik Executable
(.dex) format is optimized for efficient storage and low memory consumption.
Android applications are not deployed in dex format. Instead, the dex code is bundled into an
APK file.
The Application Package (APK) File
The dex code that you get after converting the Java files is bundled with other required
data and resources, including the manifest file AndroidManifest.xml into an Application Package
(APK) file, which has an .apk extension. An APK file usually represents a single application and
is used to distribute an Android application and install it on a mobile device or emulator. Each
APK installed on an Android device is given its own unique ID that remains unchanged for as
long as the APK resides on that device. An APK must be signed with a certificate whose private
key is held by its developer.

Note
The Android Manifest file is an essential Android application configuration file. It contains the application
startup information and its different components. You learn about the Android Manifest file and its content
in detail in Chapter 2.

USING THE TEXTVIEW CONTROL


So far, our HelloWorldApp contains default code. We simply ran the application whose
default structure and code was created for us by the ADT plug-in. Now we learn to use
the TextView control, removing the default text and entering our own. You can assign text to
the TextView in two ways:
• Direct assignment to the TextView control as defined in the layout
fileactivity_hello_world_app.xml
• Indirectly through the Java Activity file HelloWorldAppActivity.java
Assigning the Text Directly in the Layout File
The text that you want to be displayed through the TextView control can be assigned to
it in its XML definition in the layout file activity_hello_world_app.xml. From the Package Explorer
window, open activity_hello_world_app.xml by double-clicking it in the res/layout folder.
Modifyactivity_hello_world_app.xml to appear as shown in Listing 1.3.

Listing 1.3. Code Written in the Layout File activity_hello_world_app.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello World!"
tools:context=".HelloWorldAppActivity" />
</RelativeLayout>

Notice that only the statement in bold has been modified. In the statement, android:text="Hello
World!", the android:text is an attribute that is used for assigning a text to the given control. The
text Hello World! is assigned to the TextView control through the android:text attribute. You learn
about more attributes later in this chapter. Let’s run the application to see the impact of
changing the TextView control’s text. You get the output shown in Figure 1.31 (left). The output
displays the text, Hello World!, that you assigned to the TextView control. To make the message
“Hello World!” appear at the top-left corner of the screen (see Figure 1.31—right), remove the
two attributesandroid:layout_centerHorizontal and android:layout_centerVertical from the<TextView> tag
in the preceding layout file followed by running the application.
Figure 1.31. (left) Text message Hello World! displayed at the center of the screen by setting an attribute in the
XML definition, and (right) text message Hello World! appears at the top-left corner of the screen.

Let’s now try out the alternate method of assigning text to the TextView control by using
the JavaActivity file.

Assigning Text Through the Activity File


To assign text to the TextView control through the
Java Activity fileHelloWorldAppActivity.java you need to do the following two things:
• Remove the text from XML definition—The first thing that you need to do is to remove the
text that was assigned to the TextView control in the layout file activity_hello_world_app.xml. Open
the activity_hello_world_app.xml file and remove the statementandroid:text="Hello World!".
The TextView control will appear blank and will not display anything on execution.
• Assign an ID to the TextView control—To access the TextView control in the Activity file, you
have to uniquely identify it by assigning it an ID. To assign an ID to a control, use
the android:idattribute. Add the following statement to the TextView tag in
theactivity_hello_world_app.xml file:
android:id="@+id/message"
This statement declares that a constant called message is assigned as an ID to
the TextView control and will be used to uniquely identify it from other Views. The plus sign (+)
in @+id/message means that the ID, message, must be created if it doesn’t already exist.
After you remove the android:text and add the android:id attribute to the TextView tag, the layout
file activity_hello_world_app.xml appears as shown in Listing 1.4.

Listing 1.4. Code Written in the Layout File activity_hello_world_app.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".HelloWorldAppActivity" />
</RelativeLayout>

After you assign an ID to the TextView control, it will be accessible in the Activity file.
To assign text to the TextView control through HelloWorldAppActivity.java, modify it to appear as
shown in Listing 1.5.

Listing 1.5. Code Written in the Java Activity File HelloWorldAppActivity.java

package com.androidunleashed.helloworldapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloWorldAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView mesg = (TextView)findViewById(R.id.message); #1
mesg.setText("Hello World!"); #2
}
}

Statement #1 locates the control with the message ID in the layout file by using
the findViewByIdmethod of the Activity class and maps it to the TextView object, mesg. It means
the mesg object now represents the TextView control with the message ID in the layout file.
Statement #2 assigns the text Hello World! to mesg object and hence to
the TextView control. Because we are not dealing with any menu, we erased
the onCreateOptionsMenu() method from the preceding activity file, which was provided by
default.
On running the application, you see the same output shown in Figure 1.31 (right). Let’s
assign a few more attributes to the TextView control and change its height, width, color, style,
background, and alignment. Android provides several units of measurement for specifying the
dimension when setting the size of controls. Before you begin applying different attributes to
the TextView control, let’s have a brief look at the allowable units of measurements used in
dimensioning controls.

Applying Dimensions to Controls


Dimensions are commonly used to specify the size and other properties for the controls
and layouts. As you design the user interface, you often specify a dimension for a control or
layout. The following units of measurements are used:
• px (pixels)—Corresponds to the actual pixels on the screen.
• in (inches)—Based on the actual size of the screen.
• mm (millimeters)—Based on actual size of the screen.
• pts (points)—Points are a fixed dimension—1/72 of an inch.
• dip or dp (device-independent pixels)—Based on the physical density of the screen. This
unit is relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio
of dp to pixelchanges with the screen density. For example, on a 240 dpi screen, 1 dp is equal
to 1.5 pixels.
• sp (scale independent pixels)—Similar to the dp unit, but also depends on the user’s font
size settings. Hence this unit is preferred while specifying font sizes.

Note
Using the px unit is not recommended, as the UI may not render correctly on a device with a different screen
resolution.
To align the content within the control, the gravity attribute is used. Let’s go ahead and
discuss it.

Aligning Content with the Gravity Attribute


The gravity attribute is used for aligning the content within a control or its container.
For example, to align the text of the TextView control to the center, you set the value of
its android:gravityattribute to center. Some of the valid values for the android:gravity attribute are
shown in Table 1.2.
Table 1.2. Values Used in the Gravity Attribute

You can combine two or more values of any attribute using the '|' (pipe character). For example,
the following example centrally aligns the text horizontally as well as vertically within a
control:

android:gravity="center_horizontal|center_vertical"

If you want to apply the gravity attribute to any control through the Java activity file, the Java
method used for this purpose is setGravity().

Commonly Used Attributes


Table 1.3 lists the attributes commonly applied to configure the controls.
Table 1.3. List of Commonly Used Attributes
Let’s apply some of the attributes shown in the Table 1.3 to the TextView control
(inactivity_hello_world_app.xml) of the HelloWorldApp application, as shown in the following
example:

<TextView
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".HelloWorldAppActivity"
android:typeface="serif"
android:textColor="#0F0"
android:textSize="25dp"
android:textStyle="italic"
android:gravity="center_horizontal" />

This code makes the text of the TextView control appear in serif font, green color, 25dp size,
italic, and at the horizontal center of the container, as shown in Figure 1.32 (left).
Figure 1.32. (left) Text message formatted with different attributes and displayed via TextView control, and
(right) the text of TextView wrapped to the next line

Note
The “dp” unit represents density-independent pixels based on a 160-dpi (pixel density per inch) screen. We
learn more about units in Chapter 4.

Let’s apply a few more attributes to the TextView control here:

<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".HelloWorldAppActivity"
android:gravity="center"
android:height="200dp"
android:width="150dp"
android:typeface="serif"
android:textColor="#0F0"
android:textSize="25dp"
android:textStyle="bold" />

This code makes the content of the TextView wrap move to the next line if the width
assigned to it is insufficient. The TextView control is assigned the height and width of 200dp and
150dp, respectively, and its text is set to appear at the center of its assigned size. The text
appears in seriffont, green color, 25dp font size, and bold. The text in the TextView appears as
shown in Figure 1.32(right).

USING THE ANDROID EMULATOR


The Android emulator is used for testing and debugging applications before they are
loaded onto a real handset. The Android emulator is integrated into Eclipse through the ADT
plug-in.

Limitations of the Android Emulator


The Android emulator is useful to test Android applications for compatibility with
devices of different configurations. But still, it is a piece of software and not an actual device
and has several limitations:
• Emulators no doubt help in knowing how an application may operate within a given
environment, but they still don’t provide the actual environment to an application. For example,
an actual device has memory, CPU, or other physical limitations that an emulator doesn’t
reveal.
• Emulators just simulate certain handset behavior. Features such as GPS, sensors, battery,
power settings, and network connectivity can be easily simulated on a computer.
• SMS messages are also simulated and do not use a real network.
• Phone calls cannot be placed or received but are simulated.
• No support for device-attached headphones is available.
• Peripherals such as camera/video capture are not fully functional.
• No USB or Bluetooth support is available.
The emulator provides some facilities too. You can use the mouse and keyboard to
interact with the emulator when it is running. For example, you can use your computer mouse
to click, scroll, and drag items on the emulator. You can also use it to simulate finger touch on
the soft keyboard or a physical emulator keyboard. You can use your computer keyboard to
input text into UI controls and to execute specific emulator commands. Some of the most
commonly used commands are
• Back [ESC button]
• Call [F3]
• End [F4]
• Volume Up [KEYPAD_PLUS, Ctrl-5]
• Volume down [KEYPAD_MINUS, Ctrl-F6]
• Switching orientations [KEYPAD_7, Ctrl-F11/KEYPAD_9, Ctrl-F12]
You can also interact with an emulator from within the DDMS tool. Eclipse IDE
provides three perspectives to work with: Java perspective, Debug perspective, and DDMS
perspective. The Java perspective is the default and the one with which you have been working
up to now. You can switch between perspectives by choosing the appropriate icon in the top-
right corner of the Eclipse environment. The three perspectives are as follows:
• The Java perspective—It’s the default perspective in Eclipse where you spend most of the
time. It shows the panes where you can write code and navigate around the project.
• The Debug perspective—Enables application debugging. You can set breakpoints; step
through the code; view LogCat logging information, threads, and so on.
• The Dalvik Debug Monitor Service (DDMS) perspective—Enables you to monitor and
manipulate emulator and device status. It also provides screen capture and simulates incoming
phone calls, SMS sending, and GPS coordinates.
The Debug perspective and DDMS are discussed in detail in Chapter 5, “Using Selection
Widgets and Debugging.” To manage content in the device or emulator, you can use the ADB
(Android Debug Bridge).

THE ANDROID DEBUG BRIDGE (ADB)


The Android Debug Bridge (ADB) is a client-server program that is part of the Android
SDK. It is used to communicate with, control, and manage the Android device and emulator.
It consists of three components:
• Client—Runs on a computer machine. It can be invoked from the command prompt using
the adbcommand.
• Daemon—Runs as a background process in either an emulator instance or in the device itself.
• Server—Runs in a computer machine in the background. It manages the communication
between the client and the daemon.
When you install the Android SDK, the Android Debug Bridge is also automatically
installed along with it. When the Android Debug Bridge is active, you can issue adb commands
to interact with one or more emulator instances. You can install applications, push and pull
files, and run shell commands on the target device. Using the shell commands, you can perform
several tasks such as listing existing applications, deleting applications, and querying or
modifying SQLite databases available on the device.
To access ADB through Windows, open the command prompt and navigate to the folder
whereadb.exe is located by using the cd command. By default, adb.exe is installed in C:\Program
Files (x86)\Android\android-sdk\platform-tools. When you are in the folder where adbis found, you can
issue the following commands to interact with the device or emulator:
• adb devices—Displays the list of devices attached to the computer. Figure 1.33 shows the
currently running emulator on your computer, emulator-5554.

Figure 1.33. Output of different commands issued through ADB

• adb push—Copies files from your computer to the device/emulator.


Syntax:
adb push source destination
where source refers to the file along with its path that you want to copy,
and destination refers to the place in the device or emulator where you want to copy the
file. Figure 1.33 copies the mp3 file,song1.mp3, from local disk drive D: to the sdcard folder of
the running emulator.
• adb pull—Copies files from the device/emulator to your computer.
Syntax:
adb pull source [destination]

Figure 1.33 shows how the song1.mp3 file can be copied from the sdcard of the emulator to the
android folder on local disk drive E:.
• adb shell—Displays the shell prompt where you can issue Unix commands. You can see the
names of different files and folders of the emulator after issuing an ls command (see Figure
1.33).
You can issue the commands to list, rename, and delete applications from the emulator. For
example, to delete the file song1.mp3 that you pushed into the emulator, you issue
the rm command, as shown in Figure 1.33.
Leave the shell; press Ctrl+D.
• adb install—Installs an application from your computer to the device/emulator.
Syntax:
adb install appname.apk
This code
C:\Program Files (x86)\Android\android-sdk\platform-tools>adb install D:\
androidunleashed\loginApp.apk

installs the application package file loginApp.apk into the emulator.


Let’s conclude the chapter by understanding how an Android application is launched on a
physical device.

LAUNCHING ANDROID APPLICATIONS ON A HANDSET


To load an application onto a real handset, you need to plug a handset into your
computer, using the USB data cable. You first confirm whether the configurations for
debugging your application are correct and then launch the application as described here:
1. In Eclipse, choose the Run, Debug Configurations option.
2. Select the configuration HelloWorldApp_configuration, which you created for
theHelloWorldApp application.
3. Select the Target tab, set the Deployment Target Selection Mode to Manual. The Manualoption
allows us to choose the device or AVD to connect to when using this launch configuration.
4. Apply the changes to the configuration file by clicking the Apply button.
5. Plug an Android device into your computer, using a USB cable.
6. Select Run, Debug in Eclipse or press the F11 key. A dialog box appears, showing all available
configurations for running and debugging your application. The physical device(s) connected
to the computer are also listed. Double-click the running Android device. Eclipse now installs
the Android application on the handset, attaches a debugger, and runs the application.

SUMMARY
In this chapter, you saw how to install the Android SDK Starter Package, add platforms
and other components, and install Eclipse and the Android Development Tools (ADT) plug-in.
You made the ADT plug-in functional and created Android Virtual Devices to run and deploy
Android applications. You learned how to create a First Android Project and set the layout of
the application. The XML version of the layout file was described, and you learned how to
define action code through Java. You were introduced to the concept and usage of different
tools such as Dalvik VM, APK, ADB, and the Android Emulator. You learned to use
the TextView control in the application and assign text to it via the layout and activity files. You
also learned about the usage of commonly used attributes of controls, including the gravity
attribute. Finally, you learned the steps to launch an application on a handset.
The next chapter focuses on the basic widgets used in an Android application. You learn about
• Folders and files that are automatically created by the ADT plug-in
• Activities, the Android Activity life cycle, usage of Android Manifest file, commonly used layouts
and controls, and how event handling is performed
• How to create an anonymous inner class, implement the OnClickListener interface, and declare
the event handler in the XML definition of the control
• How to create and start your own Activity, Intent, create your own layout file, create a
newActivity, register the new Activity, and start the Activity
• How to use three controls—EditText, CheckBox, and RadioButton—and develop Android
applications using these controls

CASE STUDY:

Android is a mobile operating system based on a modified version of the Linux kernel and
other open source software, designed primarily for touchscreen mobile devices such
as smartphones and tablets. Android is developed by a consortium of developers known as
the Open Handset Alliance and commercially sponsored by Google. It was unveiled in 2007, with
the first commercial Android device launched in September 2008.

History:

Android Inc. was founded in Palo Alto, California, in October 2003 by Andy Rubin, Rich Miner,
Nick Sears, and Chris White.Rubin described the Android project as "tremendous potential in
developing smarter mobile devices that are more aware of its owner's location and
preferences".[17] The early intentions of the company were to develop an advanced operating
system for digital cameras, and this was the basis of its pitch to investors in April 2004.The
company then decided that the market for cameras was not large enough for its goals, and by five
months later it had diverted its efforts and was pitching Android as a handset operating system
that would rival Symbian and Microsoft Windows Mobile.
Rubin had difficulty attracting investors early on, and Android was facing eviction from its office
space.
In July 2005,Google acquired Android Inc. for at least $50 million.Its key employees, including
Rubin, Miner and White, joined Google as part of the acquisition.Not much was known about the
secretive Android at the time, with the company having provided few details other than that it was
making software for mobile phones. At Google, the team led by Rubin developed a mobile device
platform powered by the Linux kernel. Google marketed the platform to handset
makers and carriers on the promise of providing a flexible, upgradeable system.

Android made its official public debut in 2008 with Android 1.0 — a release so ancient it didn't
even have a cute codename.

Things were pretty basic back then, but the software did include a suite of early Google apps
like Gmail, Maps, Calendar, and YouTube, all of which were integrated into the operating
system — a stark contrast to the more easily updatable standalone-app model employed today

The first commercially available smartphone running Android was the HTC Dream, also known as
T-Mobile G1, announced on September 23, 2008.

T-Mobile

The Android 1.0 home screen and its


rudimentary web browser(not yet called
Chrome)

Android version 1.5: Cupcake

With early 2009's Android 1.5 Cupcake release, the tradition of Android version names was born.

Cupcake introduced numerous refinements to the Android interface, including the first on-screen
keyboard — something that'd be necessary as phones moved away from the once-ubiquitous physical
keyboard model.

Cupcake also brought about the framework for third-party app widgets, which would quickly turn into
one of Android's most distinguishing elements, and it provided the platform's first-ever option for
video recording.
Cupcake was all about widgets

Android version 1.6: Donut

Android 1.6, Donut, rolled into the world in the fall of 2009. Donut filled in some important holes in
Android's center, including the ability for the OS to operate on a variety of different screen sizes and
resolutions — a factor that'd be critical in the years to come. It also added support for CDMA networks
like Verizon, which would play a key role in Android's imminent explosion.

Android's universal search


box made its first
appearance in Android 1.6
Android versions 2.0 to 2.1: Eclair

Keeping up the breakneck release pace of Android's early years, Android 2.0 Eclair, emerged just six
weeks after Donut; its "point-one" update, also called Eclair, came out a couple months later. Eclair
was the first Android release to enter mainstream consciousness thanks to the original Motorola Droid
phone and the massive Verizon-led marketing campaign surrounding it.

The release's most transformative element was the addition of voice-guided turn-by-turn navigation
and real-time traffic info — something previously unheard of (and still essentially unmatched) in the
smartphone world. Navigation aside, Eclair brought live wallpapers to

Android as well as the platform's first speech-to-text function. And it made waves for injecting the
once-iOS-exclusive pinch-to-zoom capability into Android — a move often seen as the spark that
ignited Apple's long-lasting "thermonuclear war"against Google.

The first versions of turn-by-


turn navigation and speech-
to-text,in Eclair

Android version 2.2: Froyo

Just four months after Android 2.1 arrived, Google served up Android 2.2, Froyo, which revolved
largely around under-the-hood performance improvements.

Froyo did deliver some important front-facing features, though, including the addition of the now-
standard dock at the bottom of the home screen as well as the first incarnation of Voice Actions, which
allowed you to perform basic functions like getting directions and making notes by tapping an icon
and then speaking a command.

Notably, Froyo also brought support for Flash to Android's web browser — an option that was
significant both because of the widespread use of Flash at the time and because of Apple's adamant
stance against supporting it on its own mobile devices.
Apple would eventually win, of course, and Flash would become far less common. But back when it
was still everywhere, being able to access the full web without any black holes was a genuine
advantage only Android could offer.

Google’s first real


attempt at voice
control,in Froyo

Android version 2.3: Gingerbread

Android's first true visual identity started coming into focus with 2010's Gingerbread release.Bright
green had long been the color of Android's robot mascot, and with Gingerbread, it became an integral
part of the operating system's appearance. Black and green seeped all over the UI as Android started
its slow march toward distinctive design.
It was easy being back in
the Gingerbread days

Android 3.0 to 3.2: Honeycomb

2011's Honeycomb period was a weird time for Android.


Android 3.0 came into the world as a tablet-only release to
accompany the launch of the Motorola Xoom, and through the
subsequent 3.1 and 3.2 updates, it remained a tablet-exclusive
(and closed-source) entity. Under the guidance of newly
arrived design chief Matias Duarte, Honeycomb introduced a
dramatically reimagined UI for Android. It had a space-like
"holographic" design that traded the platform's trademark
green for blue and placed an emphasis on making the most of
a tablet's screen space.

Honeycomb:When Android
got a case of the
holographic blues.

Android version 4.0: Ice Cream Sandwich

With Honeycomb acting as the bridge from old to new, Ice Cream Sandwich— also released in 2011
— served as the platform's official entry into the era of modern design. The release refined the visual
concepts introduced with Honeycomb and reunited tablets and phones with a single, unified UI vision.

ICS dropped much of Honeycomb's "holographic" appearance but kept its use of blue as a system-
wide highlight. And it carried over core system elements like on-screen buttons and a card-like
appearance for app-switching.
The ICS home screen

and app-switching interface

Android 4.0 also made swiping a more


integral method of getting around the operating system,with the then-revolutionary-feeling ability to
swipe away things like notifications and recent apps. And it started the slow process of bringing a
standardized design framework — known as "Holo" — all throughout the OS and into Android's app
ecosystem.

Android versions 4.1 to 4.3: Jelly Bean

Spread across three impactful Android versions, 2012 and 2013's Jelly Bean releases took ICS's fresh
foundation and made meaningful strides in fine-tuning and building upon it. The releases added plenty
of poise and polishinto the operating system and went a long way in making Android more inviting for
the average user.Visuals aside, Jelly Bean brought about our first taste of Google Now — the
spectacular predictive-intelligence utility that's sadly since devolved into a glorified news feed. It gave
us expandable and interactive notifications, an expanded voice search system, and a more advanced
system for displaying search results in general, with a focus on card-based results that attempted to
answer questions directly.

Multiuser support also came into play, albeit on tablets only at this point, and an early version of
Android's Quick Settings panel made its first appearance. Jelly Bean ushered in a heavily hyped system
for placing widgets on your lock screen, too — one that, like so many Android features over the years,
quietly disappeared a couple years later.

Jelly Bean’s Quick Settings panel and short-


lived lock screen widget feature.

Android version 4.4: KitKat


Late-2013's KitKat release marked the end of Android's dark era, as the blacks of Gingerbread and the
blues of Honeycomb finally made their way out of the operating system. Lighter backgrounds and
more neutral highlights took their places, with a transparent status bar and white icons giving the OS
a more contemporary appearance.Android 4.4 also saw the first version of "OK, Google" support —
but in KitKat, the hands-free activation prompt worked only when your screen was already on and you
were either at your home screen or inside the Google app. The release was Google's first foray into
claiming a full panel of the home screen for its services, too — at least, for users of its own Nexus
phones and those who chose to download its first-ever standalone launcher.

The Lightened KitKat home screen


and its dedicated Google Now panel

Android versions 5.0 and 5.1: Lollipop

Google essentially reinvented Android — again — with its Android 5.0 Lollipop release in the fall of
2014. Lollipop launched the still-present-today Material Design standard, which brought a whole new
look that extended across all of Android, its apps and even other Google products.

The card-based concept that had been scattered throughout Android became a core UI pattern — one
that would guide the appearance of everything from notifications, which now showed up on the lock
screen for at-a-glance access, to the Recent Apps list, which took on an unabashedly card-based
appearance.
Lollipop and the onset of Material
Design

Lollipop introduced a slew of new features into Android, including truly hands-free voice control via
the "OK, Google" command, support for multiple users on phones and a priority mode for better
notification management. It changed so much, unfortunately, that it also introduced a bunch of
troubling bugs, many of which wouldn't be fully ironed out until the following year's 5.1 release.

Android version 6.0: Marshmallow

In the grand scheme of things, 2015's Marshmallow was a fairly minor Android release — one that
seemed more like a 0.1-level update than anything deserving of a full number bump. But it started the
trend of Google releasing one major Android version per year and that version

always receiving its own whole number.

Marshmallow's most attention-grabbing element was a screen-search feature called Now On Tap—
something that, as I said at the time, had tons of potential that wasn't fully tapped. Google never quite
perfected the system and ended up quietly retiring its brand and moving it out of the forefront the
following year.
Marshmallow and the almost-brilliance of
Google Now on Tap

Android 6.0 did introduce some stuff with lasting impact, though, including more granular app
permissions, support for fingerprint readers, and support for USB-C.

Android versions 7.0 and 7.1: Nougat

Google's 2016 Android Nougat releases provided Android with a native split-screen mode, a new
bundled-by-app system for organizing notifications, and a Data Saver feature. Nougat added some
smaller but still significant features, too, like an Alt-Tab-like shortcut for snapping between apps.

Android 7.0 Nougat and its new native


split-screen mode
Perhaps most pivotal among Nougat's enhancements, however, was the launch of the Google
Assistant — which came alongside the announcement of Google's first fully self-made phone, the
Pixel, about two months after Nougat's debut.

The Assistant would go on to become a critical component of Android and most other Google products
and is arguably the company's foremost effort today.

Android version 8.0 and 8.1: Oreo

Android Orea added a variety of niceties to the platform, including a native picture-in-picture mode,
a notification snoozing option, and notification channels that offer fine control over how apps can
alert you.

Oreo adds several significant features to


the operating ,including a new picture-in-
picture mode

The 2017 release also included some noteworthy elements that furthered Google's goal of aligning
Android and Chrome OS and improving the experience of using Android apps on Chromebooks, and
it was the first Android version to

feature Project Treble — an ambitious effort to create a modular base for Android's code with the
hope of making it easier for device-makers to provide timely software updates.

Android version 9: Pie

The freshly baked scent of Android Pie, a.k.a. Android 9, wafted into the Android ecosystem in early
August 2018. Pie's most transformative change was its new gesture navigation system, which traded
Android's traditional Back, Home, and Overview keys for a large, multifunctional Home button and a
series of gesture-based commands.
Android 9 introduced a new gesture-driven system for getting around phones,with an elongated Home button and a small
Back button that appears only as needed.Pie included some noteworthy new productivity features,too, such as a universal
suggested-reply system for messaging notifications, a more effective method of screenshot management, and more
intelligent systems for power management and screen brightness control. And, of course, there was no shortage of smaller
but still-significant advancements hidden throughout Pie's filling, including a smarter way to handle Wi-Fi hotspots, a
welcome twist to Android's Battery Saver mode, and a useful new touch for fingerprint sensors.

Android 9 had plenty of under-the-hood improvements as well, including a variety of privacy and security enhancements.
And the software sported its share of visual tweaks most notably an updated look for the notification and Quick Settings
panel and an ambitious series of added animationsthroughout the interface. Pie also introduced a new dashboard of
“Digital Wellbeing” controls intended to help with the ever-present challenge of balancing the digital and physical world.

Android version 10: Q

Google released its first beta preview of 2019's Android Q in March and followed it up with updated
previews in April and May. Q's most prominent change thus far is a totally reimagined interface for
Android gestures (yes, again) — this time doing away with the traditional Android Back button
altogether and relying on a much more iPhone-reminiscent approach to system navigation.

Android Q also introduces a new setup for security updates that'll allow for faster and more consistent
rollouts across the entire ecosystem. And the software has plenty of other important under-the-hood
improvements, including an updated permissions system that gives you more control over exactly how
and when apps are able to access location data as well as expanded protection of unique device
identifiers that can be used to track a device's activity over time.

Beyond that, our early peek at Q plants the seeds for a new bubble-based system for multitasking —
in which apps are able to present anything from individual messaging conversations to lists, recipes,
and even directions in an overlay interface that collapses down and can be kept in a small floating
bubble on your screen. The software lays the groundwork for a long-overdue overhaul of Android's
sharing menu, too, and provides apps with a simpler way of letting you change a system setting —
without having to switch away from your current

Process.
Apps in Android Q can pull up controls for certain system settings within a pop-up panel instead of asking users to go find
those settings on their own.

Fig :Android 10 home screen with Pixel Launcher

Android 10 was officially released on September 3, 2019 for supported Google Pixel devices, as
well as the third-party Essential Phone and Redmi K20 Pro in selected markets.The OnePlus
7T was the first device with Android 10 pre-installed.

Features:Navigation,User experience,Privacy and security and Platform

Android Version 11:

Android 11 is the upcoming eleventh major release and the 18th version of the Android mobile
operating system, due for release in Q3 2020

The first developer preview build of Android 11 was released on February 19, 2020, as a factory image
for supported Google Pixel smartphones

Android 11 will have almost 100 new features.


New platform features in Android 11 include enhancements to support foldable smartphones (including
support for hinge angle sensors), identification of standalone 5G NR networks, Project Mainline
(servicing of system components via Google Play Store), and High Efficiency Image File Format (HEIF).
Support for STIR/SHAKEN call authentication will also be included. Google also stated plans for a
"dedicated conversation section in the notification shade", the ability to only grant certain permissions
to apps on a case-by-case basis (similarly to iOS 13), and to introduce stronger enforcement of the
"scoped storage" system.If automatically rebooting after a system update, apps can automatically
resume and regain access to credential-encrypted storage without authentication.
Android 11 comes with a new "recent apps" UI and the ability to undo an inadvertent closing of a recent
app, as well as the ability to tweak gesture sensitivity.Ethernet tethering is supported when the device
is connected to a USB-to-Ethernet adapter.
Fig:Android
11 lets you
grant an
app
permission
to see your
location or
access your
camera or

microphone only for a single session of use.

Android Platform Architecture:

Android is an open source, Linux-based software stack created for a wide array of devices and
form factors. The following diagram shows the major components of the Android platform.

The Linux Kernel


The foundation of the Android platform is the Linux kernel. For example, the Android Runtime
(ART) relies on the Linux kernel for underlying functionalities such as threading and low-level
memory management.

Using a Linux kernel allows Android to take advantage of key security features and allows device
manufacturers to develop hardware drivers for a well-known kernel.

Hardware Abstraction Layer (HAL)

The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware
capabilities to the higher-level Java API framework. The HAL consists of multiple library modules,
each of which implements an interface for a specific type of hardware component, such as
the camera or bluetooth module. When a framework API makes a call to access device hardware,
the Android system loads the library module for that hardware component.
Fig: The Android Software Stack
Android Runtime

For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process
and with its own instance of the Android Runtime (ART). ART is written to run multiple virtual
machines on low-memory devices by executing DEX files, a bytecode format designed specially
for Android that's optimized for minimal memory footprint. Build toolchains, such as Jack, compile
Java sources into DEX bytecode, which can run on the Android platform.

Some of the major features of ART include the following:

•Ahead-of-time (AOT) and just-in-time (JIT) compilation

•Optimized garbage collection (GC)

•On Android 9 (API level 28) and higher, conversion of an app package's Dalvik Executable format
(DEX) files to more compact machine code.

•Better debugging support, including a dedicated sampling profiler, detailed diagnostic exceptions
and crash reporting, and the ability to set watchpoints to monitor specific fields

Native C/C++ Libraries

Many core Android system components and services, such as ART and HAL, are built from native
code that require native libraries written in C and C++. The Android platform provides Java
framework APIs to expose the functionality of some of these native libraries to apps. For example,
you can access OpenGL ES through the Android framework’s Java OpenGL API to add support
for drawing and manipulating 2D and 3D graphics in your app.

If you are developing an app that requires C or C++ code, you can use the Android NDK to access
some of these native platform libraries directly from your native code.

Java API Framework

The entire feature-set of the Android OS is available to you through APIs written in the Java
language. These APIs form the building blocks you need to create Android apps by simplifying the
reuse of core, modular system components and services, which include the following:

•A rich and extensible View System you can use to build an app’s UI, including lists, grids, text
boxes, buttons, and even an embeddable web browser

•A Resource Manager, providing access to non-code resources such as localized strings,


graphics, and layout files

•A Notification Manager that enables all apps to display custom alerts in the status bar

•An Activity Manager that manages the lifecycle of apps and provides a common navigation back
stack

•Content Providers that enable apps to access data from other apps, such as the Contacts app,
or to share their own data
System Apps

Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing,
contacts, and more. Apps included with the platform have no special status among the apps the
user chooses to install. So a third-party app can become the user's default web browser, SMS
messenger, or even the default keyboard (some exceptions apply, such as the system's Settings
app).

The system apps function both as apps for users and to provide key capabilities that developers
can access from their own app. For example, if your app would like to deliver an SMS message,
you don't need to build that functionality yourself—you can instead invoke whichever SMS app is
already installed to deliver a message to the recipient you specify.

Android Power Management

Power management is the most critical thing in any operating system due to the power demand of
high end mobile devices. Power management is a technique to conserve power in the expense of
latency/performance.
Android Power management built on top of Linux Power Management. Linux Power management
is not good enough for a Mobile device. So android keeps the low level power management
implementation on Linux and built Android Power management stack on top of Linux PM.

Careers in Android Development:

Most employers ask for mobile application developers with a minimum of a degree in software
system engineering, mobile application development, mobile computing, engineering
science or an analogous programming-centric field of study.

Marketable skills to seem for during a mobile development education program embody
• object-oriented programming (OOP)

• Java programming (Java SE/ME/EE)

• JavaScript, HTML, CSS

• Objective-C and C++ programming, user-interface (UI) style

• game & simulation programming

• mobile app portfolio assembly


• database & OS fundamentals

• mobile media promoting.

Current certifications for mobile application developers include:

• ATC android Certified Application Developer


• IBM Certified Mobile Application Developer – Worklight V6.0
• SAP Certified Development Associate – SAP Sybase Unwired Platform a pair of.1 Mobile
Application Developer
• Mobile Development Institute Certified Developer (MDICD)
• Logical Operations’ Master Mobile Application Developer (MMAD)

IT Professionals with mobile development skills are a hot artifact without delay. The demand for
Careers in Android development. is even hotter. Employers are hiring Android application
developers a lot of quicker and additional in numbers than the other professionals in mobile
technology.

Your specialized expertise and coaching in mobile application development could qualify you for a
range of in-demand job roles including:

• Mobile Application Developer


• android Application Developer
• iPhone/iOS Application Developer
• Windows Mobile App Developer
• Software Engineer
• Java Application Developer
• Objective-C Developer

Salary:

As per Indeed.com
–Average salaries for mobile application developers and connected positions:
• Mobile software system Engineer: $94,000

• Mobile Application Developer: $94,000

• Android Application Developer: $97,000

• Senior Android Developer: $107,000

• Senior Mobile Developer: $111,000

• Javascript Jquery Developer: $124,000


The job marketplace for Android application development is anticipated to making over 135,000 new
positions in the coming 2024.

Some Latest Android Projects For IT/Software

• Android Voice Based Train Time-Table

• Voice Authentication App using Microsoft Cognitive Services

• Organ Donation Android Application


• Smart Home Automation System with Light Dimmer

• Graphical Password Authentication for Android App using Persuasive Cued Click Point

• Custom Keyboard Android App

• Face Authentication App using Microsoft’s Cognitive Service

• Android Bookaholics Circle

• Advanced CRM Android Application

• Arduino based Snake Robot Controlled using Android Application


Snake Robot

• Daily Route Planner

• Android College Attendance System

• Android OCR Snap & Share Application

• Cab Booking Android Application

• Android Food order and delivery app

• Currency Detector App for Visually Impaired

• Android Women Safety App

• Friendly Map Android Application for Disabled People

• Trip Planner Android Application

• Android Paper Free Document Sharing App Project

• Android Smart Sticky Notes Application Project

• Library Management System with SMS Autoreply

• Personal diary for Visually Impaired with Microsoft Cognitive Services

• Image Analysis Application & Image Insight using Google’s Cloud Vision API

• Traffic Rules and Traffic Signs Quiz APP

• Location Finder App using Android Phone & Cloud Vision API

• Zapdroid Project: Managing Used Applications on Smartphones

• Android Smart Health Monitoring System

• Android Auction System App Project

• Vehicle Number Plate Recognition using Android

• V App : E College System for Blind Students


• Android Place Marker

• Android Help Assistance Near Me

• Canteen Automation System using Android

• Android Vehicle Tracking with Speed Limiting

• Android based QR Parking Booking

• Multi Restaurant Food Ordering & Management System

• Android Smart Ticketing System using RFID

• Financial Status Analysis Using Credit Score Rating Based On Android

• Android Query Generator

• Android Attendance System Using RFID

• Android General Knowledge Chatbot

• Android Based Self Attendance System Using OTP

• Android Vehicle Toll Payment System

• Android Task Monitoring

• Automated Canteen Ordering System using Android

• RFID Based Automatic Traffic Violation Ticketing

• Android Based Visual Product Identification For The Blind

• Android Offloading Computation Over Cloud

• Railway Ticket Booking System Using QR Codes

• Secure Digi Locker Application

• Android Campus Recruitment System

• Android File Manager Application Project

• Voice Assistant For Visually Impaired

• Your Personal Nutritionist Using FatSecret API

• Mobile Based Attendance System

• Pill Reminder and Medication Tracker using OCR

• Face Detection Using Mobile Vision API

• Child Monitoring System App

• Floating Camera Widget Android


• Android Geo Fencing App Project

• Railway Ticket Booking System Using Qr Code

• Restaurant Table Booking Android Application

• Secure File Sharing Using Access Control

• Android Video Encryption & Sharing

• Android Expiry Reminder App Using OCR

• Android Step Counter App

• Android Boat Crossing Game App

• Calorie Calculator & Suggester Android App

• Android Text Encryption Using Various Algorithms

• Android Smart Ticketing Using Rfid

• Android Battery Saver System

• Android Based Encrypted SMS System

• Advanced Tour Guide

• Android Attendance System

• Public News Droid

• Fingerprint Authenticated Secure Android Notes

• Product Review Analysis For Genuine Rating

• Android Smart City Traveler

• Android Campus Portal With Graphical Reporting

• Mobile Wallet With Merchant Payment Using Android

• Android Crime Reporter & Missing Person Finder

• Android Graphical Image Password Project

• Android Based School Bus Tracking System

• Android Based Vehicle Tracking Project

• Android Based Electronic Appliance Comparison Project

• Android Musical Instrument Store Project

• Android Book Store Project

• Android Smart Alarm System


• Android Customer Relationship Management App

• Geo Trends Classification Over Maps Android

• Android Graphical Information System

• PC Control By Android Over Internet

• Android Phone Theft Security With GPS Tracking

• Smart Android Graphical Password Strategy

• Android Group Expense Tracker Application

• Smart Health Consulting Android System

• Android Sentence Framer Application

• Android Expense Tracker

• Android Multi Layer Pattern Locking Project

• Android Based Universal Ticketing Project

• Android Civil Administration Reporting Project

• Student Faculty Document Sharing Android Project

• Android Local Train Ticketing Project

• Android Patient Tracker

• Android Pc Controller Using Wifi

• Vehicle Tracking Using Driver Mobile Gps Tracking

• Android Customer Relationship Management System

• Android Employee Tracker

• Android – PC Chatting & Image Sharing System

• Android Tourist Guide Project

• Android AI Diet Consultant

• Automated Payroll With GPS Tracking And Image Capture

• Android Blood Bank

• Mobile Quiz Through WiFi Project

• Wireless Indoor Positioning System

• Android Voting System

• Bus Pass Android Project


• Hotel Reservation Android

• Android Bluetooth Chat

• Android Based Parking Booking System

• Photo Viewer Android Project

• Android File finder and Sorting

• Android Inventory Tracker

• Android Places Finder Project

• Android Electricity Bill Payment Project

• Android Tour & Travel Agency Project

• Android Law System Project

• Wifi Library Book Locator Project

• Grocery Shopping Android

• Android Based Furniture Shopping

• Android location Alarm

• Medical Search Engine Project

• Android Joystick Application

• Mobile Attendance System Project

• College Selector App

• Android Dabbawala Project

• Intelligent Tourist System Project

• Android Merchant Application Using Qr

• Android Vehicle Tracking Application

• University Referencing of Bibliography Android With Barcode Scan

• For Electronics/Communication

• Android Powered Juice Vending Machine

• Smart Floor Cleaner Robot Using Android

• Motion Based Maze Solver Using Android


• Wearable Health Monitoring System Project

• Android Antenna Positioning System

• Hovercraft Controlled By Android

• DC Motor Speed Control By Android

• Android Controlled Railway Level Gate Control

• Voice Controlled Robotic Vehicle

• Android Controlled Robotic Arm

• Android Military Spying & Bomb Disposal Robot

• Android Password Based Remote Door Opener System Project

• Android Controlled Automobile

• Voice Based Notice Board Using Android

• Android Controlled Wildlife Observation Robot

• Home Automation Using Android

• Android Home Automation Using PIC

• Voice Controlled Home Automation Using Android

• Android Controlled Remote Password Security

• Android Controlled Remote AC Power Control

• Robot Controlled By Android Application

• Home Appliance Control Using Android Application Project

• Android Controlled Fire Fighter Robot

• Android Controlled Based Spy Robot With Night Vision Camera

• Android Controlled Pick And Place Robotic Arm Vehicle Project

• Android Controlled Induction Motor with 7 segment display

• Android Circuit Breaker


QUESTIONS
1. Features android 4.1 jelly bean sdk? 10M

2. Explain the android software stack? 5M

3. Explain about Layers of Android? 5M

4. Write the following: 10M

a. Installing Java

b. Installing Eclipse

c. Installing Android SDK Tools Setup

5. Installing the Android Development Tools (ADT) Plug-in? 5M

6. Write about How to Create the Android Virtual Devices? 5M

7. Write the following: 5M

a. View

b. ViewGroup

c. Activity

d. Intent

8. Write about android common terms? 5M

9. Defining Xml and Action Code through Java with Neat Example. 10M

10. What are the units of measurements in Android IDE? 5M

11. Explain about aligning content with the gravity attribute? 5M

12. Explain List of Commonly Used Attributes in android? 10M

13. Discuss Limitations of the Android Emulator? 5M

14. Write about The Android Debug Bridge (ADB)? 5M

15. Explain the launching android applications on a handset? 5M

16. Write the following with code and output:

a.TextView Control in Xml

b.TextView Message in .Java


UNIT-2
UNDERSTANDING THE ROLE OF ANDROID APPLICATION
COMPONENTS
To gain an understanding of the role and functionality of different components that make up
an Android application, you create a new Android application and study each of its
components.
Let’s start by creating an application that prompts the user to enter a name and displays a
Welcome message in return. The Android Project Wizard creates all the required files for an
Android application. To create an application, open Eclipse and choose, File, New, Android
Application Project or click the Android Project Creator icon on the Eclipse toolbar. You see a
dialog box, as shown in Figure 2.1 (left).

Figure 2.1. Specifying the project name (left), and specifying the application target (right)

• In the Application Name box, enter the name of the Android project. Let’s name the
applicationWelcomeMsg. The Project Name is automatically assigned, which is the same as the
application name by default. Being a unique identifier, the Package
Name iscom.androidunleashed.welcomemsg.
• From the Build SDK drop-down, select Android 4.1 (API 16) as the target platform as we expect
it to be the version commonly used by your target audience.
• Select API 8: Android 2.2 (Froyo) from the Minimum Required SDK drop-down to indicate that the
application requires at least API level 8 to run.
• Because this is a new project, select the Create Project in Workspace check box to create the
project files at the Workspace location specified when opening Eclipse for the first time.
The Create custom launcher icon check box is selected by default and enables us to define the icon
of our application. Click the Next button to move to the next dialog box.
• The next dialog is Configure Launcher Icon, which is meant for configuring the icon for the
application. Because we want to have a default icon for our application, keeping the default
options selected in the dialog box, click the Next button to move further.
• The next dialog prompts us to select whether we want to create an activity. Also, it prompts
for the type of activity. Because we want to create a blank activity, select the Create
Activity check box and the BlankActivity option from the list and then click Next.
• The next dialog (see Figure 2.1—right) asks us to enter information about the newly created
activity. Name the activity WelcomeMsgActivity. The layout filename and title name
automatically change to reflect the newly assigned activity name. The layout name
becomes activity_welcome_msg, and theTitle of the application also changes
to WelcomeMsgActivity. We can always change the auto-assigned layout filename and title of
the application.
• Keeping the auto-assigned layout filename and the title unchanged, click the Finish button
after supplying the required information. The application is created by ADT, along with all
the necessary files.

UNDERSTANDING THE UTILITY OF ANDROID API


The Android platform provides a framework API that applications can use to interact with the
underlying Android system. The framework API consists of a core set of packages and
classes; XML elements for declaring layouts, resources, and so on; a manifest file to
configure applications; permissions that applications might require; intents; and much more.
The framework API is specified through an integer called API level, and each Android
platform version supports exactly one API level, although backward compatibility is there;
that is, earlier API levels are supported. The initial release of the Android platform provided
API Level 1, and subsequent releases have incremented the API level.
Table 2.1 shows the API level supported by each version of the Android platform.

Table 2.1. The Android Platform and Corresponding API Levels


Each Android API level shows the maximum framework API revision that the
Android platform supports. You need to select the Target Name, and hence the API level for
the application, as doing so helps the application specify the framework API revision it
requires to operate.
Remember that to enable applications to run on a maximum number of platforms, you
can set the applications to target the lowest platform, Android 1.0. Because of backward
compatibility, the application that supports the Android 1.0 platform can easily run on all the
devices, even on the devices with the Android 4.0 platform. However, the opposite is not
true. There is a cost to selecting the lowest platform too: you cannot use features supported in
higher platforms. Thus, all the applications that you create in this book target platform 4.1 to
exploit the latest features added to the API.
After creating the new Android application by name, WelcomeMsg, the ADT creates
a WelcomeMsgdirectory in the default Eclipse workspace for the project. It also creates
subdirectories for keeping source files, compiled or generated files, resource files, and so on.
Certain default content is also created in these subdirectories that are required in an Android
application. Several files, such asAndroidManifest.xml and project.properties, are also
automatically created to make the job of configuring the Android application easier. You can
have a look at the files and directories created by ADT if you expand the project tree in
the Package Explorer window (see Figure 2.2).
Figure 2.2. Package Explorer window showing different directories, subdirectories, and files automatically
created by ADT

Let’s take a quick look at the different folders and files created by ADT.

OVERVIEW OF THE ANDROID PROJECT FILES


The following files and directories are created for the Android application. The list
below is just an overview of the files and directories. We will talk about these files and
directories in detail as we move further in the book:
• /src folder—The folder that contains the entire Java source file of the application. The
folder contains a directory structure corresponding to the package name supplied in the
application. The folder contains the project’s default package: com.androidunleashed.welcomemsg.
On expanding the package, you find the Activity of the application,
the WelcomeMsgActivity.java file, within it.
• /src/com.androidunleashed.welcomemsg—Refers to the package name of the application.
To avoid any collision among the class names, variable names, and so on used in the
application with those of other Android applications, each application has to be packaged in a
unique container.
• /src/com.androidunleashed.welcomemsg/WelcomeMsgActivity.java—The default
Activity file of the application. Recall that each application has at least one Activity that acts
as the main entry point to the application. The Activity file is automatically defined as the
default launch Activity in the Android Manifest file.
• /gen folder—Contains Java files generated by ADT on compiling the application. That is,
the genfolder will come into existence after compiling the application for the first time. The
folder contains anR.java file that contains references for all the resources defined in
the res directory. It also contains a BuildConfig.java file that is used to run code only in debug
mode. It contains a DEBUG constant that helps in running debug-only functions.
• /gen/com.androidunleashed.welcomemsg/R.java—All the layout and other resource
information that is coded in the XML files is converted into Java source code and placed in
the R.java file. It also means that the file contains the ID of all the resources of the application.
The R.java file is compiled into the Java byte code files and then converted into .dex format.
You should never edit this file by hand, as it is automatically overwritten when you add or
edit resources.
• Android SDK jar file—The jar file for the target platform.
• /assets folder—The assets folder is empty by default. It stores raw asset files that may be
required in the application. It may contain fonts, external JAR files, and so on to be used in
the application. The assets folder is like a resource folder where uncompiled resources of the
project are kept and no IDs are generated for the resources kept here.
• /bin folder—The folder that stores the compiled version of the application.
• /res folder—The folder where all application resources (images, layout files, and string
files) are kept. Instead of hard coding an image or string in an application, a better approach
is to create a respective resource in the res folder and include its reference in the application.
This way, you can change the image or string or any other resource anytime without
disturbing the code. Each resource is assigned a unique resource ID, which automatically
appears in the R.java file and thus in the R class after compilation, enabling us to refer to the
resource in the code. To categorize and arrange the resources, three subdirectories are created
by default: drawable, layout, and values.
• /res/drawable-xhdpi, /res/drawable-hdpi, /res/drawable-mdpi, /res/drawable-ldpi—the application’s
icon and graphic resources are kept in these folders. Because devices have screens of
different densities, the graphics of different resolutions are kept in these folders. Usually,
graphics of 320dpi, 240dpi, 160dpi, and 120dpi are used in Android applications. The
graphics with 320dpi, 240dpi, 160dpi, and 120dpi are stored in the res/drawable-
xhdpi, res/drawable-hdpi/, res/drawable-mdpi, and res/drawable-ldpi folders, respectively. The
application picks up the graphic from the correct folder after determining the density of the
current device.
• /res/layout—Stores the layout file(s) in XML format.
• /res/values—Stores all the values resources. The values resources include many types such
as string resource, dimension resource, and color resource.
• /res/layout/activity_welcome_msg.xml—The layout file used by WelcomeMsgActivity to
draw views on the screen. The views or controls are laid in the specified layout.
• /res/values/strings.xml—Contains the string resources. String resources contain the text
matter to be assigned to different controls of the applications. This file also defines string
arrays.
• AndroidManifest.xml—The central configuration file for the application.
• proguard.cfg—Defines how ProGuard optimizes the application’s code. ProGuard is a tool
that removes unused code from the Android application and optimizes it, which increases
performance. It is also used to obfuscate the code to help protect it from decompilation.
• project.properties—A build file used by Eclipse and the Android ADT plug-in. It contains
project settings such as the build target. You can use this file to change various properties of
the project. If required, the file should not be edited directly but through editors available in
Eclipse.
Other folders that may become the part of an Android application include bin, libs,
andreferenced libraries. The bin folder is hidden. The libs and referenced librariesfolders don’t
appear until a third-party library and reference are added to the project.
It’s clear that the Java Activity file is the main file that drives the entire Android application.
The default content of the Activity file WelcomeMsgActivity.java is shown in Listing 2.1.

Listing 2.1. Default Code in the WelcomeMsgActivity.java File

package com.androidunleashed.welcomemsg;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class WelcomeMsgActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_welcome_msg, menu);
return true;
}
}

UNDERSTANDING ACTIVITIES
Every unique screen the user interacts with in an application is displayed through an
Activity—one Activity for each screen. Users can interact with an application by performing
different actions with the visual controls found in the Activity. A simple application may
consist of just one Activity, whereas large applications contain several Activities. Each
Activity of an application operates independently of the others. A stack of Activities is
maintained while running an application, and the Activity at the top of the stack is the one
currently being displayed. When the Back button is pressed, the Activity is popped from the
stack, making the previous Activity the current Activity, which therefore displays the
previous screen. The transition from one Activity to another is accomplished through the use
of asynchronous messages called intents. Intents can be used to pass data from one Activity to
another. All of the Activities in the application must be defined in the Application’s manifest
file, an XML file that keeps track of all the components and permissions of the application.
Each Activity in an Android application is either a direct subclass of the Activity base class or
a subclass of an Activitysubclass.
Activities have life cycles and inherit a set of life cycle methods from the Activity base
class that are executed when the corresponding life cycle state of the Activity is reached.

Understanding the Android Activity Life Cycle


The Android Activity life cycle defines the states or events that an Activity goes
through from the time it is created until it finishes running. The Activity monitors and reacts
to these events by executing methods that override the Activity class methods for each
event. Table 2.2 lists the methods executed during the different events that occur during an
Android Activity life cycle.

Table 2.2. List of Methods Instantiated During Different Events of an Android Activity Life Cycle
All the activities of an application, permissions, and intents are defined through the
XML-structured manifest file AndroidManifest.xml. For each Activity, there needs to be an entry
in theAndroidManifest.xml file, where you can define labels, permissions, and so on. In fact, the
manifest file is the configuration file where all the different components of the application are
defined.

ROLE OF THE ANDROID MANIFEST FILE


The configuration file AndroidManifest.xml is created by ADT when creating a new
Android project and is kept in the project’s root directory. It’s an XML file that defines the
overall structure and information about the application, for example, the activities, services,
and intents used in the application. It also contains the permissions that the application might
need to run. The manifest also defines metadata of the application such as its icon and label.
Besides this, the file also contains the information required in building and packaging the
application for installing and deploying it on an Android device or the emulator. To sum up,
the application manifest file contains all the essential information required by the Android
system to run the application.
Note
Services refers to the processes that run in the background with no visual user interface. Services are used
for the tasks that you want to run quietly in the background without user action and that supply some data
or information to other applications. Services start when an Activity starts or when a device boots up,
keeps running in the background, and stops automatically on finishing its task. Music playing in the
background, a program displaying stock market figures, and a GPS tracking program that monitors the
location of the device are few examples of services.
Listing 2.2 shows the manifest file for the application that you just created.

Listing 2.2. Default Code in the Android Manifest File

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.welcomemsg"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".WelcomeMsgActivity"
android:label="@string/title_activity_welcome_msg" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The <manifest> tag, is the root element of this XML document and contains several attributes:
• android—Identifies the Android namespace used to provide several system attributes used
within the application.
• package—Its value is set to the application’s Java package. The name of the application
package acts as the unique identifier for the application in the Android device.
• versionCode/versionName—The versionCode attribute is used to define the current application
version. The version is used internally to compare application versions.
The versionName attribute is used to specify a version number that is displayed to users.
• <uses-sdk>—This tag is optional and is used to specify the maximum, minimum, and
preferred API level required for the application to operate. Three attributes are used with this
tag as follows:
• android:minSdkVersion—Used to specify the minimum API level required for this
application to run. The default value is “1.” For example, the following attribute says that the
minimum API level required by the application is 15:
android:minSdkVersion="15"
Hence, the application will run on API Level 15 and above, but will not run on API Level 14
or below.
• android:targetSdkVersion—Used to specify the preferred API level on which the
application is designed to run.
• android:maxSdkVersion—Used to specify the maximum API level supportable by the
application; that is, the application cannot run on an API level higher than the one specified
in this attribute. While installing the application, the Android system checks the <uses-
sdk> attributes defined in the application’s manifest files and compares it with its own internal
API level. The application can be installed only if
The value of the android:minSdkVersion attribute of the application must be less than or equal to
the system’s API level. If the android:minSdkVersion attribute is not declared, it is assumed that
the application requires API Level 1.
The value of the android:maxSdkVersion attribute of the application (if it is declared) must be
equal to, or greater than, the system’s API level.
• <application> tag—Nested within <manifest> is <application>, which is the parent of application
control tags. The icon and label attributes of the application tag refer to icon and label resources
that will be displayed in Android devices to represent the application. In Chapter 4, “Utilizing
Resources and Media,” you learn about the resources in detail. For the time being, it is
enough to understand that @string and @drawable refer to the strings and drawable resources,
respectively. The term "@drawable/icon" refers to the image file icon.png in the res/drawablefolder,
and "@string/app_name" refers to the control resource with ID app_name in thestrings.xml file that
is stored in the res/values folder of the application.
• <activity> tag—Nested within <application> is the <activity> tag, which describes an Activity
component. This tag’s name attribute identifies a class that is an Activity, WelcomeMsgActivity.
This name begins with a period character to show that it’s relative to
thecom.androidunleashed.welcomemsg package. That is, the WelcomeMsgActivity is relative
to<manifest>’s package value, com.androidunleashed.welcomemsg. Remember that on creating the
new Android project WelcomeMsg, an Activity named WelcomeMsgActivity was automatically
created for us in the specified package com.androidunleashed.welcomemsg by the ADT.
• <intent- filter>—Nested within <activity> is the <intent-filter>. The intents are used to interact
with the applications and services. By default, the intent specifies the action as MAIN and the
category as LAUNCHER; that is, it makes this Activity available from the application
launcher, allowing it to launch when the application starts. Basically, the <intent-filter> tag
declares the capabilities of different components through the
nested <action> and <category> tags.
Besides the preceding default tags used in the manifest file, the following are some of the
most commonly used tags:
• <service> tags—Used for declaring services. Services refer to the processes that run in the
background without a user interface. They perform required processing and handle events
silently without user interaction.
• <receiver> tags—Used for declaring broadcast receivers. Broadcast receivers are used to
listen and respond to broadcast announcements. Applications initiate broadcasts for the
interested applications when some event occurs that requires attention; for example, essential
information or confirmation is required from the user before taking some destructive action.
An application can have any number of broadcast receivers. A broadcast receiver responds by
taking a specific action.
• <provider> tags—Used for declaring content providers. Content providers provide content,
that is, data to applications. They help in handling, storing, and sharing data such as audio,
images, video, and contact lists with other applications. Android ships with a number of
content providers that the applications can use to access and share data with other
applications.
• <uses-permission> tags—Used for declaring the permissions that the application needs.
Example:
<uses-permission android:name="android.permission.CAMERA" /> —Used for the application that
needs to use the camera.
<uses-permission android:name="android.permission.INTERNET"/> —Used for the application that
needs to access the Internet
Note
The <uses-permission> tags are nested within <manifest> tags. They appear at the same level as
the <application> tag.

Using the Manifest Editor


To configure the application, you don’t have to manipulate the XML code of
theAndroidManifest.xml file manually; instead you can take the help of the Manifest Editor
provided by the Android Development Tools (ADT) plug-in. To use the Manifest Editor in
Eclipse, right-click theAndroidManifest.xml file in the Package Explorer window, and
select Open With, Android Manifest Editor. This presents the Android Manifest Overview screen,
as shown in Figure 2.3.
Figure 2.3. Manifest Editor

The screen provides a user-friendly interface to configure the application, enabling


you to set the application version information and root-level manifest nodes, including uses-
sdk and uses-permission, for example. It also provides shortcut links to the Application,
Permissions, Instrumentation, and raw XML screens. In short, the task of managing the
application—setting icons, setting the theme, applying security, testing settings, and so on—
becomes easy through Manifest Editor.

CREATING THE USER INTERFACE


There are three approaches to creating user interfaces in Android. You can create user
interfaces entirely in Java code or entirely in XML or in both (defining the user interface in
XML and then referring and modifying it through Java code). The third approach,
the combined approach, is highly preferred and is the one used in this book. The XML file in
which you create the user interface isactivity_welcome_msg.xml found in the res/layout folder. In
theactivity_welcome_msg.xml file, different controls or views that you want to interact with the
user are defined. The controls or views in activity_welcome_msg.xml have to be laid out in some
way. The default layout in which the controls or views are usually arranged is RelativeLayout.
Theactivity_welcome_msg.xml file is also referred to as the Activity layout file.
Listing 2.3 shows the original content of the layout file activity_welcome_msg.xml.
Listing 2.3. Default Code in the activity_welcome_msg.xml File

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".WelcomeMsgActivity" />
</RelativeLayout>
Recall that in this application you want to prompt the user to enter a name, and in
return the application displays a welcome message along with the entered name. So, if the
name entered is “Kelly,” the application displays “Welcome Kelly!” For the current
application, you only need to work with two files: activity_welcome_msg.xml and the Activity
file WelcomeMsgActivity.java. Let’s begin with the activity_welcome_msg.xml file. Double-click
theactivity_welcome_msg.xml file and overwrite its default content with the code shown
in Listing 2.4.

Listing 2.4. Code Written in the activity_welcome_msg.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
In the preceding XML file, four controls are used: two TextViews, one EditText, and
one Buttoncontrol. The first TextView prompts the user to enter a name by displaying the
message Enter your name: and the second TextView is used to display the Welcome message
to the user. The EditTextcontrol provides a blank text box, allowing the user to enter a name.
The Button control is for generating an event; that is, only when the user selects
the Button control will a welcome message be displayed through the second TextView control.
The EditText, Button, and one of the TextViewcontrols are assigned the IDs user_name,
click_btn, and response, respectively. These IDs are used to access these controls in the Java
Activity file. The Button control is assigned the caption Click Me. The four controls are laid out
in LinearLayout—a placement that arranges the controls contained in it either horizontally or
vertically.

COMMONLY USED LAYOUTS AND CONTROLS


The views or the controls that we want to display in an application are arranged in an
order or sequence by placing them in the desired layout. The layouts also known as
Containers or ViewGroups are used for organizing the views or controls in the required
format. Examples of layouts areLinearLayout, FrameLayout, and so on. A brief description of
layouts follows:
• LinearLayout—In this layout, all elements are arranged in a descending column from top
to bottom or left to right. Each element contains properties to specify how much of the screen
space it will consume. Depending on the orientation parameter, elements are either arranged
in row or column format.
• RelativeLayout—In this layout, each child element is laid out in relation to other child
elements. That is, a child element appears in relation to the previous child. Also, the elements
are laid out in relation to the parent.
• AbsoluteLayout—In this layout, each child is given a specific location within the bounds
of the parent layout object. This layout is not suitable for devices with different screen sizes
and hence is deprecated.
• FrameLayout—This is a layout used to display a single view. Views added to this are
always placed at the top left of the layout. Any other view that is added to
the FrameLayout overlaps the previous view; that is, each view stacks on top of the previous
one.
• TableLayout—In this layout, the screen is assumed to be divided in table rows, and each of
the child elements is arranged in a specific row and column.
• GridLayout—In this layout, child views are arranged in a grid format, that is, in the rows
and columns pattern. The views can be placed at the specified row and column location. Also,
more than one view can be placed at the given row and column position.
Note
The three terms used to represent user interface elements are view, widget, and control. They are used
interchangeably in this book.
The following list highlights some of the controls commonly used in Android applications:
• TextView—A read-only text label. It supports multiline display, string formatting, and
automatic word wrapping.
• EditText—An editable text box that also accepts multiline entry and word-wrapping.
• ListView—A ViewGroup that creates and manages a vertical list of views, displaying them
as rows within the list.
• Spinner—A TextView and an associated list of items that allows us to select an item from
the list to display in the text box.
• Button—A standard command button.
• CheckBox—A button allowing a user to select (check) or unselect (uncheck).
• RadioButton—A mutually exclusive button, which, when selected, unselects all other
buttons in the group.

EVENT HANDLING
In our sample application, you want the user to enter a name in the EditText control.
After the user has entered the name and clicks the Button control, a welcome message displays
on the screen. The action of clicking a Button, pressing the Enter key, or performing any
action on any control is considered an event. The reaction to the event, that is, the action to be
taken when the event occurs, is called event handling. To handle an event, you use
the listeners that wait for an event occurrence. When an event occurs, the listeners detect it and
direct the program to the appropriate routine.
An event listener is an interface in the View class that contains a single callback
method, called an event occurrence. For example the callback method onClick() is called when
the user clicks on a button. For event handling, the event listener is either implemented in
the Activity class or is defined as an anonymous class. Thereafter, an instance of the
implementation is passed to the respective control through the setOnClickListener() method.
Note
Click is just one type of an event.
In this chapter we discuss three ways of event handling:
• Creating an anonymous inner class
• Implementing the OnClickListener interface
• Declaring the event handler in the XML definition of the control

Creating an Anonymous Inner Class


In this method of event handling, you implement a listener inline; that is,
an anonymous class is defined with an OnClickListener interface, and an onClick(View v) method is
implemented in it. The anonymous inner class is passed to the listener through
the setOnClickListener() method. To implement the concept of anonymous inner class for event
handling, the Java activity fileWelcomeMsgActivity.java is modified to appear as shown
in Listing 2.5.

Listing 2.5. Code Written in the WelcomeMsgActivity.java File

package com.androidunleashed.welcomemsg;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;

public class WelcomeMsgActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
EditText name = (EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " !";
resp.setText(str);
}
});
}
}
You can see that a listener is implemented inline through an anonymous class with
anonClickListener interface. A callback method onClick(View v) is implemented in the class, and,
finally, the anonymous class is associated with the Button object b. Now, whenever
the Buttoncontrol is clicked in the application, the onClick() method is invoked. In
the onClick() method, you fetch the TextView and the EditText controls defined in the layout file
with the IDs responseand user_name, and then map them to
the TextView and EditText objects resp and name, respectively. That is, the
objects resp and name represent the TextView and EditText controls defined in the layout file.
The name entered by the user in the EditText control is accessed, and, after it is prefixed with a
Welcome message, is assigned to a String object, str. Finally, the str object is assigned to
the TextView object, resp, to display the Welcome message, along with the user’s name on the
screen.
Note
The class method onCreate() is called when the Activity is first created. It is used to initialize the Activity
and to create views of the application.
The application is complete. Let’s run it to see its output.
Running the Application
To run the application, you can create an Eclipse launch configuration as described
in Chapter 1, “Introduction to Android.” If you run the application without creating a launch
configuration, you see the Run As dialog box shown in Figure 2.4. Choose Android Application,
and a launch configuration is automatically created.
Figure 2.4. Run As dialog box asking the way to run the current application

The ADT compiles the application and then deploys it to the emulator with the default
launch configuration.
The Android emulator is loaded showing the output of the application. You can see in
the emulator that a prompt message Enter your name: appears via the TextView control. In
addition, a blank text box appears via the EditText control where you will enter a name, and a
button appears via Buttoncontrol (see Figure 2.5—top). After you enter the user
name Kelly and select the Click Me button, a welcome message, Welcome Kelly!, appears via
the TextView control (see Figure 2.5—bottom). Recall that you defined all these controls in the
file activity_welcome_msg.xml.
Figure 2.5. (top) Application asking for the username, and (bottom) Welcome message displayed along with the
username

You have seen the use of the anonymous inner class in event handling. Next, you try another
method of event handling, the Activity Implementing OnClickListener interface.

Activity Implementing the OnClickListener Interface


In this method of event handling, the Activity class implements
the OnClickListener interface, which requires us to implement the onClick() method in this class.
The onClick() method is declared inside the class, and the listener is set by passing a reference
to the class by the following statement: b.setOnClickListener(this);
To implement the OnClickListener interface, the activity file WelcomeMsgActivity.java is modified
to appear as shown in Listing 2.6.

Listing 2.6. Implementing the OnClickListener Interface in the WelcomeMsgActivity.javaFile

package com.androidunleashed.welcomemsg;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class WelcomeMsgActivity extends Activity implements OnClickListener {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}

public void onClick(View v) {


TextView resp = (TextView)this.findViewById(R.id.response);
EditText name = (EditText)this.findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " !";
resp.setText(str);
}
}
This code locates the Button control that you created in the activity_welcome_msg.xml file
(with the ID click_btn), assigns it to the instance b, and attaches an event listener to it. When
the event occurs via a button click, the onClick() method is executed.
The TextView and EditText controls of activity_welcome_msg.xml are located and accessed via
the resp and name objects, respectively. The username entered in the EditText control is fetched
and displayed along with a welcome message via the TextView control; that is, we get the
same output as shown previously inFigure 2.5.
In the WelcomeMsg application, an event such as Click occurs via the Button control,
which, in turn invokes the respective event handler that does the desired action.
Besides the Java code, you can define the event handler in the XML file too. That is,
you can declare the event handler in the XML definition of the control and define the event
handler in the Activity class.

Declaring the Event Handler in the XML Control Definition


Since Android SDK 1.6, there has been another way to set up a click handler for
the Button controls. In the XML definition of a Button in the layout file activity_welcome_msg.xml,
you can add anandroid:onClick attribute. This attribute is used to represent the method you want
to execute when a click event occurs via the Button control. For example, the following
statement declares thedispMessage() method as the event handler for the button when a click
event occurs:

android:onClick="dispMessage"

All you need to do is define the dispMessage() in the Activity class to perform the
desired action.
Remember, to try out this method of event handling, you need to modify the layout
fileactivity_welcome_msg.xml of the application. The code that we write in
theactivity_welcome_msg.xml file is as shown in Listing 2.7. The statement in bold is the newly
added code; the rest is the same as Listing 2.4.

Listing 2.7. Declaring an Event Handler in the activity_welcome_msg.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:id="@+id/click_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="dispMessage" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
In this code block, the attribute android:onClick means that the dispMessage() method
must be invoked when the button is clicked. Note that you can declare the same event handler
for several controls; that is, you can declare the dispMessage() method as the event handler for
multiple buttons.
In the Java Activity file WelcomeMsgActivity.java, the method dispMessage() is defined.
This method performs the task of accessing the name entered in the EditText control and
displaying a welcome message along with the entered name. After you add the
method dispMessage(), the Activity file WelcomeMsgActivity.java appears as shown in Listing 2.8.

Listing 2.8. Adding the dispMessage() Method to the WelcomeMsgActivity.java File

package com.androidunleashed.welcomemsg;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;

public class WelcomeMsgActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}
public void dispMessage(View v) {
TextView resp = (TextView) findViewById(R.id.response);
EditText name = (EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " !";
resp.setText(str);
}
}
You can see in the dispMessage() method that the TextView and EditText controls with the
IDs response and user_name are accessed from the layout file, activity_welcome_msg.xml and
mapped to the TextView and EditText objects resp and name, respectively. The username
entered in the EditText control is accessed through the name object ( EditText control) and is
assigned to the resp object (TextView control) along with the welcome message for display.
On running the application, you get the same output shown previously in Figure 2.5 (top and
bottom).
Can you define the same event handler method in more than one Button control? The
answer is yes. But you might think that if the same event handler, dispMessage, is declared in
more than oneButton control, then how does the application know which control has invoked
it? The solution is theView object; that is, the control on which the event has occurred is also
passed to the event handler. In the event handler, the getId() method of the View object can be
used to discover the button from which the event has occurred and an appropriate action can
be taken, as shown in the following code snippet:

public void dispMessage(View v) {


if (v.getId()==R.id.id1) {

}
if (v.getId()==R.id.id2) {

}
......
.....
}

id1 and id2are the IDs of the button controls that declare the same event handler.
Previously in Listing 2.7, notice that we used two TextView controls. The first TextView control
is used for displaying the text Enter your name. The second TextView does the task of
displaying a welcome message to the user.
Is there any other way of displaying a response in an Android application besides using
the TextViewcontrol? Yes, you can use Toast class for displaying output.

DISPLAYING MESSAGES THROUGH TOAST


A Toast is a transient message that automatically disappears after a while without user
interaction. It is usually used to inform the user about happenings that are not very important
and does not create a problem if they go unnoticed. A Toast is created by calling the static
method, makeText(), of theToast class. The syntax of the makeText() method is shown here:

Toast.makeText(activity_context, string_to_display, duration)

The method needs the Activity (Context) String to display, as well as the duration for
which the message is displayed on the screen. You can also supply the ID of the String
resource that you want to display. The duration is expressed in the form of constants, such
as Toast.LENGTH_SHORT orToast.LENGTH_LONG, to determine the duration for which the
string’s message remains on the screen. The method returns a Toast instance. You call
the show() method on the returned Toastinstance to display the containing string or message.

To display the welcome message through Toast, modify the Java activity
fileWelcomeMsgActivity.java as shown in Listing 2.9. Only the code in bold is new.

Listing 2.9. WelcomeMsgActivity.java File for Displaying a Message Through Toast

package com.androidunleashed.welcomemsg;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class WelcomeMsgActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}
public void dispMessage(View v) {
EditText name = (EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " !";
Toast.makeText(WelcomeMsgActivity.this, str, Toast.LENGTH_SHORT).show();
}
}

You can see that a String object, str, is defined, which contains a Welcome message and
the name entered by the user in the EditText control with the ID user_name. The text in
the String object,str, is displayed via Toast, as shown in Figure 2.6. The message Welcome Kelly
! automatically disappears after a while.

Figure 2.6. Displaying a Welcome message through Toast

Since a Toast is transient, it is not visible for an extensive period, and you don’t
receive any confirmation that the user actually saw it. Therefore, we continue to use
the TextView control in Android applications to display information to the user.
In Listing 2.9, you saw that the Activity of the application is automatically created by the
ADT that drives the application. Can we create our own activity? Let’s see how in the next
section.

CREATING AND STARTING AN ACTIVITY


The structure that is used to start, stop, and transition between Activities within an
application is called an Intent.
Describing Operations Through Intent
An intent is a data structure that describes operations to perform in an Android
application. It consists of an action that the application needs to perform, data to operate on,
and other information helpful in executing the operation. Intent can be explicit or implicit as
follows:
• Explicit Intent—In an explicit intent, you specify the Activity required to respond to the
intent; that is, you explicitly designate the target component. Because the developers of other
applications have no idea of the component names in your application, an explicit intent is
limited to be used within an application—for example, transferring internal messages.
• Implicit Intent—In an implicit intent, you just declare intent and leave it to the platform to
find an Activity that can respond to the intent. That is, you don’t specify the target component
that should respond to the intent. This type of intent is used for activating components of
other applications. It is the job of the Android platform to search for the most suitable
component to handle the implicit intent.

Method Used to Start an Activity


The method used to start an activity is startActivity(). First create an implicit or explicit
intent object and pass it to the startActivity() method in the format shown here:

startActivity(my_intent);

where my_intent refers to the intent that is passed to the method as a parameter.
ThestartActivity() method finds and starts the single Activity that best matches the given intent.
To explicitly specify the Activity that you want to start through an intent, create a new intent
specifying the current application context and the class name of the activity you want to
launch and pass thisIntent to the startActivity() method, as shown here:

startActivity(new Intent(this, Welcome.class));

In the preceding statement, you created an explicit intent and initialized it by passing
the Activity context, this and the Welcome’s class instance, which is the activity that you want
to launch. TheIntent object is passed to the startActivity() method, which launches the activity
described byWelcome.class. If startActivity() is unable to find the specified activity,
anandroid.content.ActivityNotFoundException is thrown.
Let’s explore the concept of creating and starting your own activity using an example.
You create an application similar to the WelcomeMsg application but with the following two
differences:
• Instead of using the default Activity automatically created by the ADT, you create your own
Activity in this application.
• You create and use your own layout file instead of the default layout file.
Launch Eclipse and create a new Android Project called WelcomeApp with the following
settings:
• Select Android 4.1 as the Target platform.
• Let the application name be the default, which is WelcomeApp.
• Let the package name be com.androidunleashed.welcomeapp.
• Let the Activity name be the default, which is WelcomeAppActivity.
From now on, we call the settings shown here the default settings. Almost all
applications in this book will be created with these default settings unless otherwise specified.
In any new Android project that you create, ADT creates a layout
file activity_welcome_app.xmlby default. But as mentioned earlier, in this application you learn
to create and use your own layout file.

Creating Your Own Layout File


To create a new layout file, from the Package Explorer window, right click
the res/layout folder and select the New, Android XML File option. A dialog box appears asking
for information about the new Android XML File. In the File text box, enter the filename
as welcome (no need to add the.xml extension). Select the option LinearLayout from the Root
Element, which denotes that you want to create a linear layout file, and finally, select
the Finish button. The layout file, welcome.xml, is created in the res/layout folder. The initial
content of the file is shown in Listing 2.10.

Listing 2.10. Default Code in the welcome.xml File

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>

Let’s add two TextView controls, an EditText and a Button control, to the layout file (the same
controls as in the WelcomeMsg application). After you add these controls, the contents of
thewelcome.xml file will be as shown in Listing 2.11.

Listing 2.11. Code Written in the welcome.xml File

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
After the layout file is completed, it’s time to create a new Activity.

Creating a New Activity


You know that an Activity file is in the form of a Java file. So, you need to add a Java
file to the packagecom.androidunleashed.welcomeapp that’s inside the src folder of the application.
Click the srcnode in the Package Explorer window to expand it. The
packagecom.androidprogrs.welcomeapp is displayed, showing the default Activity
fileWelcomeAppActivity.java inside it. To create an Activity, right-click the
packagecom.androidunleashed.welcomeapp and select the New, Class option. A New Java Classdialog
box appears, requesting you to enter the name of the Java file. In the Name text box, enter the
name of the Activity file, Welcome (no need to add the .java extension). Keeping all the default
options selected, select the Finish button to create the Java file.
The Activity Welcome.java is added to the package with the default content, as shown here:

package com.androidunleashed.welcomeapp;
public class Welcome {
}

Let’s add some action to the Activity file. Recall that this application is similar to
the WelcomeMsgapplication that you created before; that is, it prompts the user to enter a name
and prints a welcome message when the Button control is selected. So, let’s add the code
shown in Listing 2.12 to the newly created Activity file.

Listing 2.12. Code Written in the Welcome.java File

package com.androidunleashed.welcomeapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;

public class Welcome extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
Button b = (Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
EditText name = (EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " !";
resp.setText(str);
}
});
}
}

Registering the New Activity


Only the components declared in the application’s manifest file AndroidManifest.xml are
visible to Android and hence can be used to run the application. This means that the new
ActivityWelcome.java must be declared in the AndroidManifest.xml file to make it visible to
Android and start it. The AndroidManifest.xml file is shown in Listing 2.13. The statement in
bold is added to register the newly created activity, Welcome.java.

Listing 2.13. The AndroidManifest.xml File

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.welcomeapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".WelcomeAppActivity"
android:label="@string/title_activity_welcome_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Welcome" android:label="@string/app_name" />
</application>
</manifest>

Starting the Activity


After registering the Activity Welcome.java in the AndroidManifest.xml file, you can now
start it by using the startActivity() method discussed at the beginning of the section. Because the
new Activity is started from the default activity file of the application WelcomeAppActivity.java,
thestartActivity() method needs to be added to the same file. The code in the default Activity
fileWelcomeAppActivity.java, after adding the startActivity() method, appears as shown inListing
2.14.
Listing 2.14. The WelcomeAppActivity.java File

package com.androidunleashed.welcomeapp;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;

public class WelcomeAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_app);
startActivity(new Intent(this, Welcome.class));
}
}
The statements in bold are the statements just added to the file; the remainder is the
default code provided by ADT. The startActivity() method creates an explicit intent, which
explicitly specifies that the Activity file Welcome.java is to be run at the start. When the
application is run, you see the same output as that of the WelcomeMsg application (see Figure
2.5, left and right).
Before we move on to the next application, let’s have a quick look at the attributes that can be
used in XML definitions of the EditText and Button controls to configure them.

USING THE EDITTEXT CONTROL


The EditText control is a subclass of TextView and is used for getting input from the
user. You can use several attributes to configure the EditText control to suit your requirements.
For example, you can implement the scrolling feature to scroll the text when the user types
beyond the width of the control or the auto text feature to correct common spelling mistakes
while the user types. The default behavior of the EditText control is to display text as a single
line and run over to the next line when the user types beyond the width of the control. By
applying attributes, you can constrain the EditTextcontrol to remain on a single line only and
let the text scroll to the left. You can also hide the characters typed by the user for security
purposes, that is, convert the characters into dots, which you usually see while typing
passwords.
Example:

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:singleLine="false"
android:id="@+id/user_name" />

The preceding example sets the EditText control to expand to multiple lines when the
user types beyond the width of the control. Also, the control displays the hint text Enter your
name, which is automatically erased as the user types data.
The list of attributes that can be used to configure EditText control are discussed in the
following section.

Attributes Used to Configure the EditText Control


The following is a list of attributes that can be used to configure the EditText control:
• android:layout_width—Used to set the width of the EditText control. The two valid values
arewrap_content and match_parent. The value wrap_content sets the width of the EditTextcontrol to
accept only a single character. When the user types text, the width of the EditText control
automatically increases to accommodate the new content. Also, the cursor moves to the next
line when the boundary of the container is reached. No text scrolling takes place unless
theandroid:scrollHorizontally attribute is set to "true". In this case, instead of moving to the next
line, the text scrolls left to accommodate the newly typed content. If the value of
theandroid:layout_width attribute is set to match_parent, the width of the EditText control is set
equal to the width of its container. When the user types the text beyond the available width,
the cursor moves to the next line.
• android:layout_height—Used to set the height of the EditText control. Valid values
arewrap_content and match_parent. When the value wrap_content is assigned to the control, the
height of the EditText control increases when typing text beyond the width of the control. If
the valuematch_parent is assigned to the control, text expands the height of the control to fill up
the height of the container.
• android:singleLine—When set to true, forces the EditText control to remain on a single line.
That is, on reaching the end of the available width, the text that is typed in scrolls to the left.
If the value is set to false, the cursor moves to the next line when the end of the available
width of the control is reached.
• android:hint—Displays helpful text in the EditText control to guide user entry. The text
automatically disappears when the user enters data. For example, android:hint="Enter your
name" displays the text Enter your name in the EditText control to indicate that a name has to be
entered in this EditText control.
• android:lines—Sets the height of the EditText control to accommodate the specified number
of lines. For example, android:lines="5" sets the height of EditText control to accommodate five
lines. Typing text beyond the fifth line causes the text to scroll up to accommodate input.
• android:textSize—Sets the size of the text typed in the EditText control. You can specify the
size in any of the following units of measurement: px, in, mm, pts, dip, and sp. For
example,android:textSize="15px" sets the size of text typed in the EditText control to 15 pixels.
The recommended unit for text size is sp as it works correctly across different screen sizes
and densities.
• android:autoText—When set to true enables the EditText control to correct common
spelling mistakes.
• android:capitalize—Automatically converts typed text into capital letters. The valid values
are none,characters, words, and sentences. The value none does not capitalize anything. The
valuecharacters capitalizes every character. The value words capitalizes the first character of
every word. The value sentences capitalizes the first character of the first word of each
sentence.
• android:password—When set to true, the attribute converts the typed characters into dots
to hide entered text.
• android:minWidth—Used to specify the minimum width of the control.
• android:maxWidth—Used to specify the maximum width of the control. Text typed
beyond the maximum width scrolls if the android:scrollHorizontally attribute is set to true;
otherwise, it moves onto the next line.
• android:minHeight—Used to specify the minimum height of the control.
• android:maxHeight—Used to specify the maximum height of the control.
• android:scrollHorizontally—When set to true, makes the text scroll horizontally if typed
beyond the specified width of the control.
• android:inputType—Specifies the type of data that will be typed in the EditText control.
This attribute configures the onscreen keyboard too. There are many possible values that
include number,phone, text, textCapCharacters, textCapWords, textEmailAddress, datetime, date,time, textA
utoCorrect, textMultiLine, and textPassword. Figure 2.7 (first through fifth image) shows how the
onscreen keyboard changes when the values number, phone, text, textCap Characters,
and textEmailAddress are assigned to this attribute, respectively. This single attribute actually
replaces many attributes such
as android:password, android:singleLine,android:numeric, android:phoneNumber, android:capitalize,
and android:autoText.

Figure 2.7. (first) Keyboard when inputType is number, (second) keyboard wheninputType is phone, (third)
keyboard when inputType is text, (fourth) keyboard wheninputType is textCapCharacters, and (fifth)
keyboard when inputType is textEmailAddress

In the WelcomeMsg application that you created earlier, you saw that an event listener
was associated with the Button control; that is, the application performs an action when the
user performs an event (clicks) on the Button control. Is it essential to have a Button control to
initiate action? Can’t you initiate an action by pressing the Enter key on the EditText control?
In other words, can you add an event listener to the EditText control? The answer is yes! Let’s
see how.

Adding an Event Listener to the EditText Control


In this section, you learn how to add an event listener to the EditText control that
checks for the occurrence of an event in the EditText control and executes the callback method
accordingly. You use a practical approach by creating a new Android application to perform
this action. In this application, an EditText control is displayed on the screen asking the user to
enter a name. After the user enters a name and presses the Enter key, a welcome message
displays via the TextView control.
First launch Eclipse and create a new Android project called EditTextApp, and
modifyactivity_edit_text_app.xml as shown in Listing 2.15.

Listing 2.15. The activity_edit_text_app.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:id="@+id/user_name"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
You can see that the layout contains two controls: EditText for getting the name from
the user andTextView for displaying a welcome message. The EditText and TextView controls
are assigned theuser_name and response IDs, respectively. The EditText control displays hint
text, Enter your name, to indicate that a name must be entered in the EditText control.
To add an action, that is, to display the welcome message when the user presses the Enter key
after entering a name, we need to write code in the Activity file. Let’s put the code shown
in Listing 2.16 into the Activity file EditTextAppActivity.java.

Listing 2.16. The EditTextAppActivity.java File

package com.androidunleashed.edittextapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.KeyEvent;

public class EditTextAppActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text_app);
final TextView resp = (TextView)this.findViewById(R.id.response);
final EditText username = (EditText) findViewById(R.id.user_name);
username.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode ==
KeyEvent.KEYCODE_ENTER)) {
resp.setText("Welcome "+username.getText()+" !");
return true;
}
return false;
}
});
}
}

In Listing 2.16, the EditText control from the layout is captured and mapped to the
usernameEditText object. To display the welcome message to the user, the TextView control
with theresponse ID is captured from the layout and assigned to the TextView object resp. An
event listener, OnKeyListener, is added to the EditText object username so that the callback
methodonKey() is invoked whenever a key is pressed. The onKey() method is implemented, and
it checks whether the Enter key is pressed. When the Enter key is pressed, a welcome
message is displayed to the user through the TextView object, resp. The onKey() method is set to
return false until the Enter key is pressed. The onKey() method is set to return true when the
Enter key is pressed by the user.
Note
The onKey() method is set to return true if the event is handled and you want no other handler to listen to
the events. You set this method to return false if the event is not handled and you want the method to listen
for more key presses and to continue handling events.

You see the output shown in Figure 2.8 (top). You can see the hint text Enter your
name in theEditText control. After the user has entered a name and pressed the Enter key, the
username and the welcome message appear, as shown in Figure 2.8 (bottom).
Figure 2.8. EditTextApp displaying the hint text Enter your name (top), and welcome message displayed when
the Enter key is pressed (bottom)

While developing applications, you may encounter a situation where you want to
display certain options for the user to select. The two controls that enable you to do this
are CheckBox andRadioButton.

CHOOSING OPTIONS WITH CHECKBOX


A checkbox control has two states: checked and unchecked. When the check box is
selected, it toggles its state from checked to unchecked and vice versa. A check box is created
via an instance ofandroid.widget.CheckBox.
In Java, the following methods can be used with Checkbox controls:
• isChecked()—Determines whether the check box is checked
• setChecked()—Sets or changes the state of the check box
• toggle()—Toggles the state of the check box from checked to unchecked or vice versa
To add an event listener, you can implement the OnCheckedChangeListener interface that
invokes the callback method onCheckedChanged() when the state of the check box changes. In
addition, you can also use the traditional implementation, the OnClickListener interface, that
invokes theonClick() method when any of the CheckBox controls are clicked.
Example:

<CheckBox
android:id="@+id/purchase"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Purchase" />

The preceding example shows a Purchase check box that the user can select to
indicate that he or she wants to purchase an item.
To learn the concept of CheckBox, let’s create an Android application based on these
controls. In this application, you create three CheckBox controls, each representing a food item
along with its price (see Figure 2.9—left). When the food items are selected, the total price is
displayed. The application shows us how CheckBox controls are displayed, how event listeners
are attached to them, and whether the CheckBox is in a checked or unchecked state. Let’s start
with the application.

Figure 2.9. CheckBox controls displayed on application startup (left), price displayed when the first and
last CheckBox controls are selected (middle), and price displayed when the last two CheckBox controls are
selected (right)

Launch Eclipse, create a new Android project called CheckBoxApp, and add
three CheckBox controls to the Activity layout file activity_check_box_app.xml, as shown
in Listing 2.17.

Listing 2.17. The activity_check_box_app.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Items you want"/>
<CheckBox
android:id="@+id/checkbox_pizza"
android:layout_height="wrap_content"
android:text="Pizza $15"
android:layout_width="match_parent" />
<CheckBox
android:id="@+id/checkbox_hotdog"
android:layout_height="wrap_content"
android:text="Hot Dog $5"
android:layout_width="match_parent" />
<CheckBox
android:id="@+id/checkbox_burger"
android:layout_height="wrap_content"
android:text="Burger $10"
android:layout_width="match_parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bill_btn"
android:text="Calculate Bill"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/amount"/>
</LinearLayout>
You can see that two TextViews, three CheckBoxes, and a Button control are defined
in Listing 2.17. The first TextView is for displaying a message, Select Items you want, asking the
user to select the food items using the CheckBox controls. The three CheckBoxes are assigned
unique IDs—checkbox_pizza, checkbox_hotdog, and checkbox_burger—and they represent the food
items, Pizza, HotDog, and Burger, respectively. The caption and ID assigned to the Button control
are bill_btn and Calculate Bill, respectively. The second TextView is assigned the ID amountand is
meant for displaying the total price of the food items selected by the user.
To add an action to the application, that is, to check the status of each of
the CheckBox controls and to print the sum of the food items selected, you need to write some
Java code in the Activity file. Let’s write the code shown in Listing 2.18 in the Activity
file CheckBoxAppActivity.java.

Listing 2.18. The CheckBoxAppActivity.java File

package com.androidunleashed.checkboxapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.view.View;
import android.view.View.OnClickListener;

public class CheckBoxAppActivity extends Activity implements OnClickListener {


CheckBox c1,c2,c3;
TextView resp;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box_app);
Button b = (Button)this.findViewById(R.id.bill_btn);
resp = (TextView)this.findViewById(R.id.amount);
c1 = (CheckBox)findViewById(R.id.checkbox_pizza);
c2 = (CheckBox)findViewById(R.id.checkbox_hotdog);
c3 = (CheckBox)findViewById(R.id.checkbox_burger);
b.setOnClickListener(this);
}

public void onClick(View v) {


int amt=0;
if (c1.isChecked()) {
amt=amt+15;
}
if (c2.isChecked()) {
amt=amt+5;
}
if (c3.isChecked()) {
amt=amt+10;
}
resp.setText("Bill is " +Integer.toString(amt));
}
}

The Button control with the ID bill_btn is accessed from the layout file and is mapped to
theButton object b. The TextView control with the ID amount is accessed from the layout file and
is mapped to the TextView object resp. Similarly, the three CheckBoxes with the
IDscheckbox_pizza, checkbox_hotdog, and checkbox_burger are accessed from the layout file and
mapped to the CheckBox objects c1, c2, and c3, respectively. An event handler,setOnClickListener,
is attached to the button. Hence, whenever the button is clicked, theonClick() method is called.
In the onClick() method, an integer variable amt is initialized to 0. The state of each check box
is checked through the isChecked() method. The isChecked() method returns the Boolean
value true if the check box is checked; otherwise, it returns false. The three check boxes
represent the food items Pizza, HotDog, and Burger, respectively. The state of each check
box is checked, and if any of them is selected, the amount associated with that food item is
added to theamt variable. That is, the total amount of the selected food item is computed and
stored in the amtvariable. The total in the amt variable is displayed on the screen by assigning
it to the TextView objectresp. When the application is run, you get the screen shown in Figure
2.9 (left). No total is displayed, as no food item has been selected. When a check box is
selected, the total price of the selected food items is displayed, as shown in Figure
2.9 (middle and right).
What if you want users to select only a single option from a group? The solution is
using theRadioButton control.
CHOOSING MUTUALLY EXCLUSIVE ITEMS
USING RADIOBUTTONS
RadioButton controls are two-state widgets that can be in either a checked or unchecked
state. The difference between check boxes and radio buttons is that you can select more than
one check box in a set, whereas radio buttons are mutually exclusive—only one radio button
can be selected in a group. Selecting a radio button automatically deselects other radio
buttons in the group.
To make them mutually exclusive, RadioButton controls are grouped together into
the RadioGroupelement so that no more than one can be selected at a time. To create a group of
radio buttons, first create a RadioGroup and then populate the group with
few RadioButton controls, as shown in the following example:

<RadioGroup
android:id="@+id/group_hotel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star " />
<RadioButton android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star" />
</RadioGroup>

In the preceding code block, a RadioGroup with the group_hotel ID is defined, which
contains twoRadioButton controls with the IDs radio_fivestar and radio_threestar, respectively.
Because only a single radio button in a group can be in a checked state, checking a radio
button automatically unchecks the other radio button in the group.
In Java, the following methods can be applied to RadioButtons:
• isChecked()—Detects whether the RadioButton control is selected.
• toggle()—Toggles the state of the RadioButton from selected to unselected and vice versa.
• check()—Checks a specific RadioButton whose ID is supplied in the method.
• getCheckedRadioButtonId()—Gets the ID of the currently selected RadioButton control. It
returns –1 if no RadioButton control is checked.
Let’s create an application using the concept of radio buttons. In this application, you
define twoRadioButton controls in a RadioGroup. Each RadioButton represents a hotel type, and
whenever a RadioButton is selected, the hotel type represented by it will be displayed through
a TextViewcontrol (see Figure 2.9—middle). It is obvious that when a RadioButton representing
a hotel type is selected, any other previously selected RadioButton is automatically unselected.
The application shows how RadioButton controls are defined, how they are nested
in RadioGroup controls, and how an event listener is attached to them. Let’s start with the
application.
Launch Eclipse, create a new Android project called RadioButtonApp, and add
two RadioButtoncontrols to the Activity layout file activity_radio_button_app.xml, as shown
in Listing 2.19.

Listing 2.19. The activity_radio_button_app.xml File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star " />
<RadioButton android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
</LinearLayout>
In Listing 2.19, you can see that two RadioButton controls with
the radio_fivestar andradio_threestar IDs are grouped inside a RadioGroup. This means that the two
radio buttons have become mutually exclusive—selecting one radio button automatically
deselects the other radio button.
To add an event listener action to the two RadioButton controls, you need to write some
Java code in the Activity file. Let’s write the code shown in Listing 2.20 in the Activity
fileRadioButtonAppActivity.java.

Listing 2.20. The RadioButtonAppActivity.java File

package com.androidunleashed.radiobuttonapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;

public class RadioButtonAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_app);
RadioButton radioFivestar = (RadioButton) findViewById(R.id.radio_fivestar);
RadioButton radioThreestar = (RadioButton) findViewById(R.id.radio_threestar);
radioFivestar.setOnClickListener(radioListener);
radioThreestar.setOnClickListener(radioListener);
}

private OnClickListener radioListener = new OnClickListener() {


public void onClick(View v) {
TextView selectedHotel = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
selectedHotel.setText("The hotel type selected is: " +rb.getText());
}
};
}
The two RadioButton controls are captured from the layout and mapped to
the RadioButtonobjects radioFivestar and radioThreestar. The View.OnClickListener interface is
implemented to listen to the click events on the RadioButton controls. The onClick() callback
method is implemented. This is the method that is executed when any of the RadioButton controls
are selected. In the onClick() callback method, the TextView control from the layout is captured
and mapped to the TextView object selectedHotel. Also, the text content of the RadioButtoncontrol
that is selected by the user is fetched through the getText() method and is displayed through
the TextView object selectedHotel. On execution of the application, you see
two RadioButtoncontrols on the startup screen, as shown in Figure 2.10 (left). When the user
selects the five starRadioButton, the TextView displays the message The hotel type selected is: Five
Star(see Figure 2.10—middle). Similarly, when the user selects the three star RadioButton,
theTextView displays the message The hotel type selected is: Three Star (see Figure 2.10—right).

Figure 2.10. RadioButton controls displayed on application startup (left), TextViewdisplaying the message
when the Five Star RadioButton is selected (middle), andTextView displaying the message when the Three
Star RadioButton is selected (right)
In the preceding application you have a single set of RadioButton controls nested inside
aRadioGroup. What if you want to display two sets of RadioButton controls, asking the user to
select a RadioButton from both sets? For example, the user needs to select the type of the hotel,
as well as the type of room. In that case, you need to create two RadioGroup controls: one to
represent hotel types and the other to represent room types. The RadioGroup that represents
hotel types will have two RadioButton controls showing the text Five Star and Three Star.
Similarly, the otherRadioGroup that represents room types will have three RadioButton controls
to show three options: Ordinary Room, Luxury Room, and Grand Suite. The layout file with
two RadioGroup controls appears as shown in Listing 2.21.

Listing 2.21. The activity_radio_button_app.xml File with Two RadioGroup Controls

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup android:id="@+id/group_hotel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star " />
<RadioButton android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of room"/>
<RadioGroup android:id="@+id/group_room"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_suite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grand Suite " />
<RadioButton android:id="@+id/radio_luxury"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luxury Room" />
<RadioButton android:id="@+id/radio_ordinary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ordinary Room" />
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype" />
</LinearLayout>
To make two independent sets of radio buttons, one to represent hotel types and
another to represent room types, you create two RadioGroup controls with
the group_hotel and group_room IDs. The first RadioGroup, group_hotel, contains
two RadioButton controls with the radio_fivestarand radio_threestar IDs to represent five star and
three star hotels. Similarly, the nextRadioGroup, group_room, contains three RadioButton controls
with the radio_suite,radio_luxury, and radio_ordinary IDs to represent the suite, luxury, and
ordinary room types. The two TextView controls are used to display the messages Select the type
of hotel andSelect the type of room, asking the user to select the type of hotel and room. The
thirdTextView with the hoteltype ID is used to display the options selected by the user. To make
the twoRadioGroups functional and to display the hotel and room type selected by the user,
write the code shown in Listing 2.22 in the Java activity file RadioButtonAppActivity.java.

Listing 2.22. The RadioButtonAppActivity.java File

package com.androidunleashed.radiobuttonapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;

public class RadioButtonAppActivity extends Activity {


String str1="";
String str2="";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_app);
RadioButton radioFivestar = (RadioButton) findViewById(R.id.radio_fivestar);
RadioButton radioThreestar = (RadioButton) findViewById(R.id.radio_threestar);
RadioButton radioSuite = (RadioButton) findViewById(R.id.radio_suite);
RadioButton radioLuxury = (RadioButton) findViewById(R.id.radio_luxury);
RadioButton radioOrdinary = (RadioButton) findViewById(R.id.radio_ordinary);
radioFivestar.setOnClickListener(radioListener1);
radioThreestar.setOnClickListener(radioListener1);
radioSuite.setOnClickListener(radioListener2);
radioLuxury.setOnClickListener(radioListener2);
radioOrdinary.setOnClickListener(radioListener2);
}

private OnClickListener radioListener1 = new OnClickListener() {


public void onClick(View v) {
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str1="The hotel type selected is: " +rb.getText();
selectedOptions.setText(str1+"\n"+str2);
}
};

private OnClickListener radioListener2 = new OnClickListener() {


public void onClick(View v) {
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str2="Room type selected is: " +rb.getText();
selectedOptions.setText(str1+"\n"+str2);
}
};
}

The RadioButton controls with IDs radio_fivestar, radio_threestar, radio_suite,radio_luxury,


and radio_ordinary are captured from the layout file and mapped to
theRadioButton objects radioFivestar, radioThreestar, radioSuite, radioLuxury, andradioOrdinary,
respectively. Two event listener interfaces are created, radioListener1 andradioListener2. One
checks for event occurrences in the RadioButton controls in group_hotel, and the other checks for
the occurrence of events in the RadioButton controls in group_room. Both the interfaces have the
callback method onClick() implemented in them.
When any of the RadioButton controls in the first RadioGroup, group_hotel, is selected, the
callback method onClick() of radioListener1 is executed and text is assigned to the string str1to
represent the RadioButton selected in that radio group. Similarly, when any RadioButtoncontrol
from the second RadioGroup, group_room, is selected, the callback
method onClick() ofradioListener2 is executed. This assigns text to the string str2 to represent
the RadioButtonselected in that radio group. The TextView with the hoteltype ID is captured from
the layout file and is mapped to the TextView object selected Options. The text messages in both
the str1 andstr2 strings are assigned to the TextView control selectedOptions for display. On
running the application, you see two sets of RadioButton controls in their
respective RadioGroups (see Figure 2.11—left). When the five star RadioButton from
the RadioGroup group_hotel and theRadioButton luxury room from the RadioGroup group_room are
selected, the TextView displays the message The hotel type selected is: Five Star Room; Type selected
is: Luxury Room (see Figure 2.11—middle). Similarly, when the three star RadioButton control
from the RadioGroup group_hotel and the grand suite RadioButton from the RadioGroup
group_room are selected, the TextView displays the message The hotel type selected is: Three Star and
Room type selected is: Grand Suite (see Figure 2.11—right).
Figure 2.11. RadioButton controls in two RadioGroups (left), TextView informing that the Five
Star RadioButton and the Grand Suite Room RadioButton are selected (middle), and TextView informing that
the Three Star RadioButton and the Grand Suite RadioButton are selected (right)

SUMMARY
The main focus of this chapter was to understand the working of basic widgets such
as EditText,CheckBox, and RadioButton, and to develop Android applications using these controls.
You also learned the role of the folders and files automatically created by the ADT plug-in.
You learned about Activities, the Android Activity life cycle, the usage of the Android
Manifest file, commonly used layouts and controls, and how events are handled in Android
applications. To respond to different events, you learned to create anonymous inner classes,
implement the OnClickListener interface, and declare the event handler in the XML definition of
the control. You also saw how to describe operations through Intent, create your own layout
file, create a new Activity, register the new Activity, and finally, the steps needed to start the
Activity.
Questions

1.Explain different attributes are using in Text View,EditText Control and give an example of Layout & Activity.
2. List out role of Android Manifest File.
3. Define an Activity. Explain Android Activity Life Cycle in detail.
4. Define Intent and its operations.
5. How to create, Register and Start a New Activity.
6. Define Android Debug Bridge,Android Virtual Device.
7. To create an Android Application by using Edit Text, Check Box, Radio Button, Button controls to display
messages through Toast.
Technical Interview Questions(some out of syllabus)

Core Android

Base

•Tell all the Android application components.

•What is the project structure of an Android Application?

•What is Context? How is it used?


•What is AndroidManifest.xml?
•What is Application class?

Activity and Fragment

•What is Activity and its lifecycle?

•What is the difference between onCreate() and onStart()

•When only onDestroy is called for an activity without onPause() and


onStop()?

•Why do we need to call setContentView() in onCreate() of Activity class?

•What is onSavedInstanceState() and onRestoreInstanceState() in activity?

•What is Fragment and its lifecycle.

•What are "launch modes"?

•What is the difference between a Fragment and an Activity? Explain the


relationship between the two.

•When should you use a Fragment rather than an Activity?

•What is the difference between FragmentPagerAdapter vs


FragmentStatePagerAdapter?

•What is the difference between adding/replacing fragment in backstack?


•Why is it recommended to use only the default constructor to create
a Fragment?

•How would you communicate between two Fragments?

•What is retained Fragment?

Views and ViewGroups

•What is View in Android?


•Difference between View.GONE and View.INVISIBLE?

•Can you a create custom view? How?

•What are ViewGroups and how they are different from the Views?

•Relative Layout vs Linear Layout.

•Tell about Constraint Layout

•How does the Touch Control and Events work in Android?

Displaying Lists of Content

•What is the difference between ListView and RecyclerView?

•How does RecyclerView work internally?

Dialogs and Toasts

•What is Dialog in Android?


•What is Toast in Android? -
•What the difference between Dialog and Dialog Fragment?

Intents and Broadcasting

•What is Intent?
•What is an Implicit Intent?
•What is an Explicit Intent?
•What is a BroadcastReceiver?
•What is a LocalBroadcastManager?
•What is the function of an IntentFilter?
•What is a Sticky Intent?
•Describe how broadcasts and intents work to be able to pass messages
around your app?

•What are the different types of Broadcasts?

Services

•What is Serivce?
•Service vs IntentService.
•What is a JobScheduler?

Inter-process Communication

•How can two distinct Android apps interact?

•What can you use for background processing in Android?

•What is a ContentProvider and what is it typically used for?

Long-running Operations

•How to run parallel tasks in Java or Android, and get callback when all
complete?

•What is an AsyncTask?

•What are the problems in AsyncTask?

•When would you use java thread instead of an AsyncTask?

•What is a Loader? (Deprecated)


•What is the relationship between the life cycle of an AsyncTask and
an Activity? What problems can this result in? How can these problems be
avoided?

•How does the threading work in Android?

•Android Memory Leak and Garbage Collection

Working With Multimedia Content

•How do you handle bitmaps in Android as it takes too much memory?


•Tell about the Bitmap pool.

•How to play sounds in Android?

•How image compression is preformed?

You might also like