Android Development
Android 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
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 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.
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.
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.
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.
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.
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.
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.
<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>
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.
package com.androidunleashed.helloworldapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
public boolean onCreateOptionsMenu(Menu menu) { #4
getMenuInflater().inflate(R.menu.activity_hello_world_app, menu);
return true;
}
}
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.
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.
<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.
<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.
package com.androidunleashed.helloworldapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
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.
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.
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().
<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.
<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).
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
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
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 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.
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.
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.
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
Honeycomb:When Android
got a case of the
holographic blues.
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
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.
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.
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
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.
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.
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 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.
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.
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.
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.
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.
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 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.
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.
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.
•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
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.
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 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.
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.
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)
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:
Salary:
As per Indeed.com
–Average salaries for mobile application developers and connected positions:
• Mobile software system Engineer: $94,000
• Graphical Password Authentication for Android App using Persuasive Cued Click Point
• Image Analysis Application & Image Insight using Google’s Cloud Vision API
• Location Finder App using Android Phone & Cloud Vision API
• For Electronics/Communication
a. Installing Java
b. Installing Eclipse
a. View
b. ViewGroup
c. Activity
d. Intent
9. Defining Xml and Action Code through Java with Neat Example. 10M
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.
Let’s take a quick look at the different folders and files created by ADT.
package com.androidunleashed.welcomemsg;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@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.
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.
<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.
<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.
<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.
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
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;
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.
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;
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.
<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.
package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
}
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.
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.
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.
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.
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:
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.
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.
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.
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;
<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>
package com.androidunleashed.welcomeapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
<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.
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.
<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.
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;
@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.
<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.
<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.
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;
@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);
}
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.
<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.
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;
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.
<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.
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;
@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);
}
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
•What are ViewGroups and how they are different from the Views?
•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?
Services
•What is Serivce?
•Service vs IntentService.
•What is a JobScheduler?
Inter-process Communication
Long-running Operations
•How to run parallel tasks in Java or Android, and get callback when all
complete?
•What is an AsyncTask?