ffirs.indd ii

25/01/12 8:34 AM
BEGINNING
ANDROID™ 4 APPLICATION DEVELOPMENT
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
ffirs.indd ii

25/01/12 8:34 AM
BEGINNING

Android™ 4 Application Development

ffirs.indd iii

25/01/12 8:34 AM
ffirs.indd iv

25/01/12 8:34 AM
BEGINNING

Android™ 4 Application Development
Wei-Meng Lee

John Wiley & Sons, Inc.

ffirs.indd v

25/01/12 8:34 AM
Beginning Android™ 4 Application Development
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis,...
To my family:
Thanks for the understanding and support
while I worked on getting this book ready.
I love you all!

ffirs.i...
ffirs.indd viii

25/01/12 8:34 AM
ABOUT THE AUTHOR

WEI-MENG LEE is a technologist and founder of Developer Learning Solutions (www.learn2develop
.net), a t...
ffirs.indd x

25/01/12 8:34 AM
CREDITS

EXECUTIVE EDITOR

PRODUCTION MANAGER

Robert Elliott

Tim Tate

SENIOR PROJECT EDITOR

VICE PRESIDENT AND EXECUTI...
ffirs.indd xii

25/01/12 8:34 AM
ACKNOWLEDGMENTS

WRITING THIS BOOK HAS been a roller-coaster ride. Working with just-released software is always

a huge c...
ffirs.indd xiv

25/01/12 8:34 AM
CONTENTS

INTRODUCTION
CHAPTER 1: GETTING STARTED WITH ANDROID PROGRAMMING

What Is Android?
Android Versions
Features of ...
CONTENTS

Calling Built-In Applications Using Intents
Understanding the Intent Object
Using Intent Filters
Adding Categori...
CONTENTS

TimePicker View
DatePicker View

Using List Views to Display Long Lists
ListView View
Using the Spinner View

Un...
CONTENTS

CHAPTER 7: CONTENT PROVIDERS

Sharing Data in Android
Using a Content Provider
Predefined Query String Constants
...
CONTENTS

Downloading Text Content
Accessing Web Services Using the GET Method

Consuming JSON Services
Sockets Programmin...
CONTENTS

APPENDIX B: USING THE ANDROID EMULATOR

499

Uses of the Android Emulator
Creating Snapshots
SD Card Emulation
E...
INTRODUCTION

I FIRST STARTED PLAYING WITH THE ANDROID SDK before it was officially released as version 1.0.

Back then, th...
INTRODUCTION

NOTE All the examples discussed in this book were written and tested using
version 4.0 of the Android SDK. W...
INTRODUCTION

Chapter 7: Content Providers discusses how data can be shared among different applications on an
Android dev...
INTRODUCTION

WHAT YOU NEED TO USE THIS BOOK
All the examples in this book run on the Android emulator (which is included ...
INTRODUCTION

SOURCE CODE
As you work through the examples in this book, you may choose either to type in all the code
man...
INTRODUCTION

P2P.WROX.COM
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based...
1
Getting Started with Android
Programming
WHAT YOU WILL LEARN IN THIS CHAPTER
➤

What is Android?

➤

Android versions an...
2

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

designed for widescreen devices, specifically tablets. If you are...
What Is Android?

❘ 3

TABLE 1-1: A Brief History of Android Versions
ANDROID VERSION

RELEASE DATE

CODENAME

1.1

9 Febr...
4

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

➤

Messaging — Supports both SMS and MMS. Chapter 8 discusses me...
c01.indd 5

25/01/12 1:04 PM

FIGURE 1-1

Contacts
Phone

FreeType
SSL

Camera Driver
Wi-Fi Driver

OpenGL / ES
SGL

Displ...
6

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

Android Devices in the Market
Android devices come in all shapes...
What Is Android?

❘ 7

FIGURE 1-3

Besides smartphones and tablets, Android is also beginning to appear in dedicated devic...
8

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-5

FIGURE 1-6

At the time of writing, the Samsung Gala...
Obtaining the Required Tools

❘ 9

As such, in August 2008, Google announced Android Market, an online application store f...
10

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

For Android development, you can use a Mac, a Windows PC, or a ...
Obtaining the Required Tools

❘ 11

The Android SDK is packaged in a zip fi le. You can download it and unzip its content (...
12

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-10

FIGURE 1-11

Configuring the Android SDK Manager
Th...
Obtaining the Required Tools

❘ 13

FIGURE 1-12

NOTE For a start, you should at least select the latest Android 4.0 SDK p...
14

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

You will be asked to choose the packages to install (see Figure...
Obtaining the Required Tools

❘ 15

Android Development Tools (ADT)
When Eclipse is launched, select Help ➪ Install New So...
16

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-16

NOTE If you have any problems downloading the ADT,...
Obtaining the Required Tools

❘ 17

NOTE As each new version of the SDK is released, the installation steps tend to
differ...
18

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

In the Android Virtual Device Manager dialog (see Figure 1-19),...
Obtaining the Required Tools

❘ 19

In this case, you have created an AVD (put simply, an Android emulator) that emulates ...
❘

20

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-22

CREATING YOUR FIRST ANDROID APPLICATION
With all t...
Creating Your First Android Application

❘ 21

FIGURE 1-23

NOTE After you have created your first Android application, sub...
22

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-25

4.
5.

Select the Android 4.0 target and click Nex...
Creating Your First Android Application

❘ 23

NOTE You need to have at least a period (.) in the package name. The
recomm...
24

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

FIGURE 1-28

FIGURE 1-29

9.

Add the following code in bold to...
Creating Your First Android Application

❘ 25

android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextV...
26

❘

12.

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

If you have not made any mistakes in the project, you shou...
Creating Your First Android Application

❘ 27

FIGURE 1-32

FIGURE 1-33

c01.indd 27

25/01/12 1:05 PM
28

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

WHICH AVD WILL BE USED TO TEST YOUR APPLICATION?
Recall that ea...
❘ 29

Anatomy of an Android Application

In Android, an activity is a window that contains the user interface of your appl...
30

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

➤

res — This folder contains all the resources used in your ap...
Anatomy of an Android Application

❘ 31

If the user loads the same application on a phone configured to display French as ...
32

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

➤

Within the definition for this activity, there is an element ...
❘ 33

Summary

Finally, the code that connects the activity to the UI (main.xml) is the setContentView() method,
which is ...
34

❘

CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING

WHAT YOU LEARNED IN THIS CHAPTER
TOPIC

Android OS

Android is ...
2
Activities, Fragments,
and Intents
WHAT YOU WILL LEARN IN THIS CHAPTER
➤

The life cycles of an activity

➤

Using fragm...
36

❘

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

UNDERSTANDING ACTIVITIES
This chapter begins by looking at how to cre...
Understanding Activities

➤

❘ 37

onPause() — Called when the current activity is being paused and the previous activity ...
❘

38

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

The best way to understand the various stages of an activity is to cr...
Understanding Activities

❘ 39

{
super.onStop();
Log.d(tag, “In the onStop() event”);
}
public void onDestroy()
{
super.o...
40

❘

6.

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

Click the Home button and hold it there. Click the Activities ico...
Understanding Activities

❘ 41

Applying Styles and Themes to an Activity
By default, an activity occupies the entire scre...
❘

42

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

String tag = “Lifecycle”;
/** Called when the activity is first creat...
Understanding Activities

import
import
import
import
import
import

❘ 43

android.app.AlertDialog;
android.app.Dialog;
an...
44

❘

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

}
}
).create();

}
return null;
}
}

4.

Press F11 to debug the appli...
Understanding Activities

❘ 45

{
Toast.makeText(getBaseContext(),
“OK clicked!”, Toast.LENGTH_SHORT).show();
}
}
)
.setNe...
46

❘

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
boolean[] ...
Understanding Activities

❘ 47

THE CONTEXT OBJECT
In Android, you often encounter the Context class and its instances. In...
48

❘

CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS

android:layout_width=”fill_parent”
android:layout_height=”fill_parent...
Understanding Activities

❘ 49

public void run(){
try {
//---simulate doing something lengthy--Thread.sleep(5000);
//---d...
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Wrox press beginning android 4 application development (2012)
Upcoming SlideShare
Loading in...5
×

Wrox press beginning android 4 application development (2012)

2,713

Published on

android dev

Published in: Education, Technology, Business
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,713
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
290
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Wrox press beginning android 4 application development (2012)

  1. 1. ffirs.indd ii 25/01/12 8:34 AM
  2. 2. BEGINNING ANDROID™ 4 APPLICATION DEVELOPMENT INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi CHAPTER 1 Getting Started with Android Programming . . . . . . . . . . . . . . . . . . . . . . . . . 1 CHAPTER 2 Activities, Fragments, and Intents. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 CHAPTER 3 Getting to Know the Android User Interface. . . . . . . . . . . . . . . . . . . . . . 105 CHAPTER 4 Designing Your User Interface with Views . . . . . . . . . . . . . . . . . . . . . . . 159 CHAPTER 5 Displaying Pictures and Menus with Views. . . . . . . . . . . . . . . . . . . . . . . 219 CHAPTER 6 Data Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 CHAPTER 7 Content Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 CHAPTER 8 Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 CHAPTER 9 Location-Based Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 CHAPTER 10 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 CHAPTER 11 Developing Android Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 CHAPTER 12 Publishing Android Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 APPENDIX A Using Eclipse for Android Development . . . . . . . . . . . . . . . . . . . . . . . . . 483 APPENDIX B Using the Android Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 APPENDIX C Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 ffirs.indd i 25/01/12 8:34 AM
  3. 3. ffirs.indd ii 25/01/12 8:34 AM
  4. 4. BEGINNING Android™ 4 Application Development ffirs.indd iii 25/01/12 8:34 AM
  5. 5. ffirs.indd iv 25/01/12 8:34 AM
  6. 6. BEGINNING Android™ 4 Application Development Wei-Meng Lee John Wiley & Sons, Inc. ffirs.indd v 25/01/12 8:34 AM
  7. 7. Beginning Android™ 4 Application Development Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-19954-1 ISBN: 978-1-118-22824-1 (ebk) ISBN: 978-1-118-24067-0 (ebk) ISBN: 978-1-118-26538-3 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http:// booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2011945560 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and may not be used without written permission. Android is a trademark of Google, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book. ffirs.indd vi 25/01/12 8:34 AM
  8. 8. To my family: Thanks for the understanding and support while I worked on getting this book ready. I love you all! ffirs.indd vii 25/01/12 8:34 AM
  9. 9. ffirs.indd viii 25/01/12 8:34 AM
  10. 10. ABOUT THE AUTHOR WEI-MENG LEE is a technologist and founder of Developer Learning Solutions (www.learn2develop .net), a technology company specializing in hands-on training on the latest mobile technologies. Wei-Meng has many years of training experience and his training courses place special emphasis on the learning-by-doing approach. This hands-on approach to learning programming makes understanding the subject much easier than reading books, tutorials, and other documentation. Wei-Meng is also the author of Beginning iOS 5 Application Development (Wrox, 2010) and Beginning Android Application Development (Wrox, 2011). Contact Wei-Meng at weimenglee@ learn2develop.net. ABOUT THE TECHNICAL EDITOR CHAIM KRAUSE is a Simulation Specialist at the US Army’s Command and General Staff College where he develops various software products on a multitude of platforms, from iOS and Android devices to Windows desktops and Linux servers, among other duties. Python is his preferred language, but he is multilingual and also codes in Java and JavaScript/HTML5/CSS, and others. He was fortunate to begin his professional career in the software field at Borland where he was a Senior Developer Support Engineer for Delphi. Outside of computer geek stuff, Chaim enjoys techno and dubstep music and scootering with his two sled dogs, Dasher and Minnie. ffirs.indd ix 25/01/12 8:34 AM
  11. 11. ffirs.indd x 25/01/12 8:34 AM
  12. 12. CREDITS EXECUTIVE EDITOR PRODUCTION MANAGER Robert Elliott Tim Tate SENIOR PROJECT EDITOR VICE PRESIDENT AND EXECUTIVE GROUP PUBLISHER Ami Sullivan Richard Swadley TECHNICAL EDITOR Chaim Krause PRODUCTION EDITOR VICE PRESIDENT AND EXECUTIVE PUBLISHER Neil Edde Kathleen Wisor ASSOCIATE PUBLISHER COPY EDITOR Jim Minatel Luann Rouff PROJECT COORDINATOR, COVER EDITORIAL MANAGER Katie Crocker Mary Beth Wakefield PROOFREADER FREELANCER EDITORIAL MANAGER Rosemarie Graham ASSOCIATE DIRECTOR OF MARKETING David Mayhew Nancy Carassco INDEXER Johnna VanHoose Dinse MARKETING MANAGER Ryan Sneed BUSINESS MANAGER COVER IMAGE Amy Knies ffirs.indd xi COVER DESIGNER Ashley Zurcher © Viktoriya Sukhanova / iStockPhoto 25/01/12 8:34 AM
  13. 13. ffirs.indd xii 25/01/12 8:34 AM
  14. 14. ACKNOWLEDGMENTS WRITING THIS BOOK HAS been a roller-coaster ride. Working with just-released software is always a huge challenge. When I fi rst started working on this book, the Android 4 SDK had just been released; and wading through the documentation was like fi nding a needle in a haystack. To add to the challenge, the Android emulator for the tablet is extremely slow and unstable, making the development process very laborious. Now that the book is done, I hope your journey will not be as eventful as mine. Like any good guide, my duty is to make your foray into Android tablet development an enjoyable and fruitful experience. The book you are now holding is the result of the collaborative efforts of many people, and I wish to take this opportunity to acknowledge them here. First, my personal gratitude to Bob Elliott, executive editor at Wrox. Bob is always ready to lend a listening ear and to offer help when it’s needed. It is a great pleasure to work with Bob, as he is one of the most responsive persons I have ever worked with! Thank you, Bob, for the help and guidance! Of course, I cannot forget Ami Sullivan, my editor (and friend!), who is always a pleasure to work with. After working together on four books, we now know each other so well that we know the content of incoming e-mail messages even before we open them! Thank you, Ami! Nor can I forget the heroes behind the scenes: copyeditor Luann Rouff and technical editor Chaim Krause. They have been eagle-eye editing the book, making sure that every sentence makes sense — both grammatically and technically. Thanks, Luann and Chaim! Last, but not least, I want to thank my parents and my wife, Sze Wa, for all the support they have given me. They have selflessly adjusted their schedules to accommodate my busy schedule when I was working on this book. My wife, as always, has stayed up with me on numerous nights as I was furiously working to meet the deadlines, and for this I would like to say to her and my parents, “I love you all!” Finally, to our lovely dog, Ookii, thanks for staying by our side. ffirs.indd xiii 25/01/12 8:34 AM
  15. 15. ffirs.indd xiv 25/01/12 8:34 AM
  16. 16. CONTENTS INTRODUCTION CHAPTER 1: GETTING STARTED WITH ANDROID PROGRAMMING What Is Android? Android Versions Features of Android Architecture of Android Android Devices in the Market The Android Market The Android Developer Community Obtaining the Required Tools Android SDK Installing the Android SDK Tools Configuring the Android SDK Manager Eclipse Android Development Tools (ADT) Creating Android Virtual Devices (AVDs) Creating Your First Android Application Anatomy of an Android Application Summary CHAPTER 2: ACTIVITIES, FRAGMENTS, AND INTENTS Understanding Activities Applying Styles and Themes to an Activity Hiding the Activity Title Displaying a Dialog Window Displaying a Progress Dialog Displaying a More Sophisticated Progress Dialog Linking Activities Using Intents Resolving Intent Filter Collision Returning Results from an Intent Passing Data Using an Intent Object Fragments Adding Fragments Dynamically Life Cycle of a Fragment Interactions between Fragments ftoc.indd xv xxi 1 2 2 3 4 6 8 9 9 10 11 12 14 15 17 20 29 33 35 36 41 41 42 47 50 53 58 59 63 69 73 76 80 25/01/12 8:35 AM
  17. 17. CONTENTS Calling Built-In Applications Using Intents Understanding the Intent Object Using Intent Filters Adding Categories Displaying Notifications Summary CHAPTER 3: GETTING TO KNOW THE ANDROID USER INTERFACE Understanding the Components of a Screen Views and ViewGroups LinearLayout AbsoluteLayout TableLayout RelativeLayout FrameLayout ScrollView Adapting to Display Orientation Anchoring Views Resizing and Repositioning 85 89 91 96 98 103 105 105 106 107 115 116 117 118 121 123 125 127 Managing Changes to Screen Orientation 130 Persisting State Information during Changes in Configuration Detecting Orientation Changes Controlling the Orientation of the Activity 133 135 135 Utilizing the Action Bar Adding Action Items to the Action Bar Customizing the Action Items and Application Icon Creating the User Interface Programmatically Listening for UI Notifications Overriding Methods Defined in an Activity Registering Events for Views Summary CHAPTER 4: DESIGNING YOUR USER INTERFACE WITH VIEWS Using Basic Views TextView View Button, ImageButton, EditText, CheckBox, ToggleButton, RadioButton, and RadioGroup Views ProgressBar View AutoCompleteTextView View Using Picker Views 136 139 144 146 148 149 152 156 159 160 160 161 171 177 179 xvi ftoc.indd xvi 25/01/12 8:35 AM
  18. 18. CONTENTS TimePicker View DatePicker View Using List Views to Display Long Lists ListView View Using the Spinner View Understanding Specialized Fragments Using a ListFragment Using a DialogFragment Using a PreferenceFragment Summary CHAPTER 5: DISPLAYING PICTURES AND MENUS WITH VIEWS Using Image Views to Display Pictures Gallery and ImageView Views ImageSwitcher GridView Using Menus with Views Creating the Helper Methods Options Menu Context Menu Some Additional Views AnalogClock and DigitalClock Views WebView Summary CHAPTER 6: DATA PERSISTENCE Saving and Loading User Preferences Accessing Preferences Using an Activity Programmatically Retrieving and Modifying the Preferences Values Changing the Default Name of the Preferences File Persisting Data to Files Saving to Internal Storage Saving to External Storage (SD Card) Choosing the Best Storage Option Using Static Resources Creating and Using Databases Creating the DBAdapter Helper Class Using the Database Programmatically Pre-Creating the Database Summary 179 184 191 191 199 202 202 207 210 214 219 219 220 226 231 234 235 238 240 242 242 243 249 251 251 252 259 261 263 263 268 271 272 273 273 279 285 289 xvii ftoc.indd xvii 25/01/12 8:35 AM
  19. 19. CONTENTS CHAPTER 7: CONTENT PROVIDERS Sharing Data in Android Using a Content Provider Predefined Query String Constants Projections Filtering Sorting Creating Your Own Content Providers Using the Content Provider Summary CHAPTER 8: MESSAGING SMS Messaging Sending SMS Messages Programmatically Getting Feedback after Sending a Message Sending SMS Messages Using Intent Receiving SMS Messages Caveats and Warnings Sending E-mail Summary CHAPTER 9: LOCATION-BASED SERVICES Displaying Maps Creating the Project Obtaining the Maps API Key Displaying the Map Displaying the Zoom Control Changing Views Navigating to a Specific Location Adding Markers Getting the Location That Was Touched Geocoding and Reverse Geocoding Getting Location Data Monitoring a Location Project — Building a Location Tracker Summary CHAPTER 10: NETWORKING Consuming Web Services Using HTTP Downloading Binary Data 293 293 294 300 303 304 305 305 314 319 321 321 322 325 328 329 344 345 347 351 352 352 353 355 358 361 363 366 369 371 375 384 385 390 393 393 396 xviii ftoc.indd xviii 25/01/12 8:35 AM
  20. 20. CONTENTS Downloading Text Content Accessing Web Services Using the GET Method Consuming JSON Services Sockets Programming Summary CHAPTER 11: DEVELOPING ANDROID SERVICES Creating Your Own Services 402 404 409 417 426 429 429 Performing Long-Running Tasks in a Service 433 Performing Repeated Tasks in a Service 439 Executing Asynchronous Tasks on Separate Threads Using IntentService 442 Establishing Communication between a Service and an Activity Binding Activities to Services Understanding Threading Summary 445 449 454 460 CHAPTER 12: PUBLISHING ANDROID APPLICATIONS 463 Preparing for Publishing Versioning Your Application Digitally Signing Your Android Applications Deploying APK Files Using the adb.exe Tool Using a Web Server Publishing on the Android Market Summary APPENDIX A: USING ECLIPSE FOR ANDROID DEVELOPMENT Getting Around in Eclipse Workspaces Package Explorer Using Projects from Other Workspaces Using Editors within Eclipse Understanding Eclipse Perspectives Automatically Importing Packages Using the Code Completion Feature Refactoring Debugging your Application Setting Breakpoints Dealing with Exceptions 463 464 466 471 471 474 476 481 483 483 483 485 486 487 490 490 491 492 494 495 497 xix ftoc.indd xix 25/01/12 8:35 AM
  21. 21. CONTENTS APPENDIX B: USING THE ANDROID EMULATOR 499 Uses of the Android Emulator Creating Snapshots SD Card Emulation Emulating Devices with Different Screen Sizes Emulating Physical Capabilities Sending SMS Messages to the Emulator Making Phone Calls Transferring Files into and out of the Emulator Resetting the Emulator 499 501 502 504 506 508 509 511 513 APPENDIX C: ANSWERS TO EXERCISES 515 INDEX 521 xx ftoc.indd xx 25/01/12 8:35 AM
  22. 22. INTRODUCTION I FIRST STARTED PLAYING WITH THE ANDROID SDK before it was officially released as version 1.0. Back then, the tools were unpolished, the APIs in the SDK were unstable, and the documentation was sparse. Fast-forward three and a half years, Android is now a formidable mobile operating system, with a following no less impressive than the iPhone. Having gone through all the growing pains of Android, I think now is the best time to start learning about Android programming — the APIs have stabilized, and the tools have improved. One challenge remains, however: Getting started is still an elusive goal for many. What’s more, Google has recently released their latest version of the Android SDK — 4.0, a unified mobile OS for both smartphones and tablets. The Android 4.0 SDK includes several new features for tablet developers, and understanding all these new features requires some effort on the part of beginners. It was with this challenge in mind that I was motivated to write this book, one that could benefit beginning Android programmers and enable them to write progressively more sophisticated applications. As a book written to help jump-start beginning Android developers, it covers the necessary topics in a linear manner so that you can build on your knowledge without being overwhelmed by the details. I adopt the philosophy that the best way to learn is by doing — hence, the numerous Try It Out sections in each chapter, which first show you how to build something and then explain how everything works. I have also taken this opportunity to further improve the previous edition of this book, addressing feedback from readers and adding additional topics that are important to beginning Android developers. Although Android programming is a huge topic, my aim for this book is threefold: to get you started with the fundamentals, to help you understand the underlying architecture of the SDK, and to appreciate why things are done in certain ways. It is beyond the scope of any book to cover everything under the sun related to Android programming, but I am confident that after reading this book (and doing the exercises), you will be well equipped to tackle your next Android programming challenge. WHO THIS BOOK IS FOR This book is targeted for the beginning Android developer who wants to start developing applications using Google’s Android SDK. To truly benefit from this book, you should have some background in programming and at least be familiar with object-oriented programming concepts. If you are totally new to Java — the language used for Android development — you might want to take a programming course in Java programming first, or grab one of many good books on Java programming. In my experience, if you already know C# or VB.NET, learning Java is not too much of an effort; you should be comfortable just following along with the Try It Outs. For those totally new to programming, I know the lure of developing mobile apps and making some money is tempting. However, before attempting to try out the examples in this book, I think a better starting point would be to learn the basics of programming fi rst. flast.indd xxi 25/01/12 8:35 AM
  23. 23. INTRODUCTION NOTE All the examples discussed in this book were written and tested using version 4.0 of the Android SDK. While every effort is made to ensure that all the tools used in this book are the latest, it is always possible that by the time you read this book, a newer version of the tools may be available. If so, some of the instructions and/or screenshots may differ slightly. However, any variations should be manageable. WHAT THIS BOOK COVERS This book covers the fundamentals of Android programming using the Android SDK. It is divided into 12 chapters and three appendixes. Chapter 1: Getting Started with Android Programming covers the basics of the Android OS and its current state. You will learn about the features of Android devices, as well as some of the popular devices on the market. You will also learn how to download and install all the required tools to develop Android applications and then test them on the Android emulator. Chapter 2: Activities, Fragments, and Intents gets you acquainted with these three fundamental concepts in Android programming. Activities and fragments are the building blocks of an Android application. You will learn how to link activities together to form a complete Android application using intents, one of the unique characteristics of the Android OS. Chapter 3: Getting to Know the Android User Interface covers the various components that make up the UI of an Android application. You will learn about the various layouts you can use to build the UI of your application, and the numerous events that are associated with the UI when users interact with the application. Chapter 4: Designing Your User Interface with Views walks you through the various basic views you can use to build your Android UI. You will learn three main groups of views: basic views, picker views, and list views. You will also learn about the specialized fragments available in Android 3.0 and 4.0. Chapter 5: Displaying Pictures and Menus with Views continues the exploration of views. Here, you will learn how to display images using the various image views, as well as display options and context menus in your application. This chapter ends with some additional cool views that you can use to spice up your application. Chapter 6: Data Persistence shows you how to save, or store, data in your Android application. In addition to learning the various techniques to store user data, you will also learn file manipulation and how to save fi les onto internal and external storage (SD card). In addition, you will learn how to create and use a SQLite database in your Android application. xxii flast.indd xxii 25/01/12 8:35 AM
  24. 24. INTRODUCTION Chapter 7: Content Providers discusses how data can be shared among different applications on an Android device. You will learn how to use a content provider and then build one yourself. Chapter 8: Messaging explores two of the most interesting topics in mobile programming — sending SMS messages and e-mail. You will learn how to programmatically send and receive SMS and e-mail messages, and how to intercept incoming SMS messages so that the built-in Messaging application will not be able to receive any messages. Chapter 9: Location-Based Services demonstrates how to build a location-based service application using Google Maps. You will also learn how to obtain geographical location data and then display the location on the map. Chapter 10: Networking explores how to connect to web servers to download data. You will see how XML and JSON web services can be consumed in an Android application. This chapter also explains sockets programming, and you will learn how to build a chat client in Android. Chapter 11: Developing Android Services demonstrates how you can write applications using services. Services are background applications that run without a UI. You will learn how to run your services asynchronously on a separate thread, and how your activities can communicate with them. Chapter 12: Publishing Android Applications discusses the various ways you can publish your Android applications when you are ready. You will also learn about the necessary steps to publishing and selling your applications on the Android Market. Appendix A: Using Eclipse for Android Development provides a brief overview of the many features in Eclipse. Appendix B: Using the Android Emulator provides some tips and tricks on using the Android emulator for testing your applications. Appendix C: Answers to Exercises contains the solutions to the end-of-chapter exercises found in every chapter. HOW THIS BOOK IS STRUCTURED This book breaks down the task of learning Android programming into several smaller chunks, enabling you to digest each topic before delving into a more advanced one. If you are a total beginner to Android programming, start with Chapter 1 fi rst. Once you have familiarized yourself with the basics, head over to the appendixes to read more about Eclipse and the Android emulator. When you are ready, continue with Chapter 2 and gradually move into more advanced topics. A feature of this book is that all the code samples in each chapter are independent of those discussed in previous chapters. This gives you the flexibility to dive into the topics that interest you and start working on the Try It Out projects. xxiii flast.indd xxiii 25/01/12 8:35 AM
  25. 25. INTRODUCTION WHAT YOU NEED TO USE THIS BOOK All the examples in this book run on the Android emulator (which is included as part of the Android SDK). However, to get the most out of this book, having a real Android device would be useful (though not absolutely necessary). CONVENTIONS To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book. TRY IT OUT These Are Exercises or Examples for You to Follow The Try It Out sections appear once or more per chapter. These are exercises to work through as you follow the related discussion in the text. 1. 2. They consist of a set of numbered steps. Follow the steps with your copy of the project files. How It Works After each Try It Out, the code you’ve typed is explained in detail. As for other conventions in the text: ➤ New terms and important words are highlighted in italics when first introduced. ➤ Keyboard combinations are treated like this: Ctrl+R. ➤ Filenames, URLs, and code within the text are treated like so: persistence.properties. ➤ Code is presented in two different ways: We use a monofont type with no highlighting for most code examples. We use bolding to emphasize code that is of particular importance in the present context. NOTE Notes, tips, hints, tricks, and asides to the current discussion look like this. xxiv flast.indd xxiv 25/01/12 8:35 AM
  26. 26. INTRODUCTION SOURCE CODE As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com. When at the site, simply locate the book’s title (use the Search box or one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book. You’ll fi nd the fi lename of the project you need in a CodeNote such as this at the beginning of the Try it Out features: code snippet filename After you download the code, just decompress it with your favorite compression tool. Alternatively, go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and for all other Wrox books. NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-118-19954-1. ERRATA We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you fi nd an error in one of our books, such as a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration and at the same time help us provide even higher-quality information. To fi nd the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. NOTE A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml. If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/ techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book. xxv flast.indd xxv 25/01/12 8:35 AM
  27. 27. INTRODUCTION P2P.WROX.COM For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums. At p2p.wrox.com, you will fi nd a number of different forums that will help you not only as you read this book but also as you develop your own applications. To join the forums, just follow these steps: 1. 2. 3. 4. Go to p2p.wrox.com and click the Register link. Read the terms of use and click Agree. Complete the required information to join as well as any optional information you want to provide and click Submit. You will receive an e-mail with information describing how to verify your account and complete the joining process. NOTE You can read messages in the forums without joining P2P, but in order to post your own messages, you must join. After you join, you can post new messages and respond to messages that other users post. You can read messages at any time on the web. If you want to have new messages from a particular forum e-mailed to you, click the Subscribe to This Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page. xxvi flast.indd xxvi 25/01/12 8:35 AM
  28. 28. 1 Getting Started with Android Programming WHAT YOU WILL LEARN IN THIS CHAPTER ➤ What is Android? ➤ Android versions and its feature set ➤ The Android architecture ➤ The various Android devices on the market ➤ The Android Market application store ➤ How to obtain the tools and SDK for developing Android applications ➤ How to develop your first Android application Welcome to the world of Android! When I was writing my fi rst book on Android (which was just less than a year ago), I stated that Android was ranked second in the U.S. smartphone market, second to Research In Motion’s (RIM) BlackBerry, and overtaking Apple’s iPhone. Shortly after the book went to press, comScore (a global leader in measuring the digital world and the preferred source of digital marketing intelligence) reported that Android has overtaken BlackBerry as the most popular smartphone platform in the U.S. A few months later, Google released Android 3.0, code named Honeycomb. With Android 3.0, Google’s focus in the new Software Development Kit was the introduction of several new features c01.indd 1 25/01/12 1:04 PM
  29. 29. 2 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING designed for widescreen devices, specifically tablets. If you are writing apps for Android smartphones, Android 3.0 is not really useful, as the new features are not supported on smartphones. At the same time that Android 3.0 was released, Google began working on the next version of Android, which can be used on both smartphones and tablets. In October 2011, Google released Android 4.0, code named Ice Cream Sandwich, and that is the focus of this book. In this chapter you will learn what Android is, and what makes it so compelling to both developers and device manufacturers alike. You will also get started with developing your fi rst Android application, and learn how to obtain all the necessary tools and set them up so that you can test your application on an Android 4.0 emulator. By the end of this chapter, you will be equipped with the basic knowledge you need to explore more sophisticated techniques and tricks for developing your next killer Android application. WHAT IS ANDROID? Android is a mobile operating system that is based on a modified version of Linux. It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the mobile space, Google purchased Android and took over its development work (as well as its development team). Google wanted Android to be open and free; hence, most of the Android code was released under the open source Apache License, which means that anyone who wants to use Android can do so by downloading the full Android source code. Moreover, vendors (typically hardware manufacturers) can add their own proprietary extensions to Android and customize Android to differentiate their products from others. This simple development model makes Android very attractive and has thus piqued the interest of many vendors. This has been especially true for companies affected by the phenomenon of Apple’s iPhone, a hugely successful product that revolutionized the smartphone industry. Such companies include Motorola and Sony Ericsson, which for many years have been developing their own mobile operating systems. When the iPhone was launched, many of these manufacturers had to scramble to find new ways of revitalizing their products. These manufacturers see Android as a solution — they will continue to design their own hardware and use Android as the operating system that powers it. The main advantage of adopting Android is that it offers a unified approach to application development. Developers need only develop for Android, and their applications should be able to run on numerous different devices, as long as the devices are powered using Android. In the world of smartphones, applications are the most important part of the success chain. Device manufacturers therefore see Android as their best hope to challenge the onslaught of the iPhone, which already commands a large base of applications. Android Versions Android has gone through quite a number of updates since its fi rst release. Table 1-1 shows the various versions of Android and their codenames. c01.indd 2 25/01/12 1:04 PM
  30. 30. What Is Android? ❘ 3 TABLE 1-1: A Brief History of Android Versions ANDROID VERSION RELEASE DATE CODENAME 1.1 9 February 2009 1.5 30 April 2009 Cupcake 1.6 15 September 2009 Donut 2.0/2.1 26 October 2009 Eclair 2.2 20 May 2010 Froyo 2.3 6 December 2010 Gingerbread 3.0/3.1/3.2 22 February 2011 Honeycomb 4.0 19 October 2011 Ice Cream Sandwich In February 2011, Google released Android 3.0, a tablet-only release supporting widescreen devices. The key changes in Android 3.0 are as follows. ➤ New user interface optimized for tablets ➤ 3D desktop with new widgets ➤ Refined multi-tasking ➤ New web browser features, such as tabbed browsing, form auto-fill, bookmark synchronization, and private browsing ➤ Support for multi-core processors Applications written for versions of Android prior to 3.0 are compatible with Android 3.0 devices, and they run without modifications. Android 3.0 tablet applications that make use of the newer features available in 3.0, however, will not be able to run on older devices. To ensure that an Android tablet application can run on all versions of devices, you must programmatically ensure that you only make use of features that are supported in specific versions of Android. In October 2011, Google released Android 4.0, a version that brought all the features introduced in Android 3.0 to smartphones, along with some new features such as facial recognition unlock, data usage monitoring and control, Near Field Communication (NFC), and more. Features of Android Because Android is open source and freely available to manufacturers for customization, there are no fixed hardware or software configurations. However, Android itself supports the following features: ➤ ➤ c01.indd 3 Storage — Uses SQLite, a lightweight relational database, for data storage. Chapter 6 discusses data storage in more detail. Connectivity — Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth (includes A2DP and AVRCP), Wi-Fi, LTE, and WiMAX. Chapter 8 discusses networking in more detail. 25/01/12 1:04 PM
  31. 31. 4 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING ➤ Messaging — Supports both SMS and MMS. Chapter 8 discusses messaging in more detail. ➤ Web browser — Based on the open source WebKit, together with Chrome’s V8 JavaScript engine ➤ Media support — Includes support for the following media: H.263, H.264 (in 3GP or MP4 container), MPEG-4 SP, AMR, AMR-WB (in 3GP container), AAC, HE-AAC (in MP4 or 3GP container), MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP ➤ Hardware support — Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS ➤ Multi-touch — Supports multi-touch screens ➤ Multi-tasking — Supports multi-tasking applications ➤ Flash support — Android 2.3 supports Flash 10.1. ➤ Tethering — Supports sharing of Internet connections as a wired/wireless hotspot Architecture of Android In order to understand how Android works, take a look at Figure 1-1, which shows the various layers that make up the Android operating system (OS). The Android OS is roughly divided into five sections in four main layers: ➤ ➤ Libraries — These contain all the code that provides the main features of an Android OS. For example, the SQLite library provides database support so that an application can use it for data storage. The WebKit library provides functionalities for web browsing. ➤ Android runtime — At the same layer as the libraries, the Android runtime provides a set of core libraries that enable developers to write Android apps using the Java programming language. The Android runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine (Android applications are compiled into Dalvik executables). Dalvik is a specialized virtual machine designed specifically for Android and optimized for battery-powered mobile devices with limited memory and CPU. ➤ Application framework — Exposes the various capabilities of the Android OS to application developers so that they can make use of them in their applications. ➤ c01.indd 4 Linux kernel — This is the kernel on which Android is based. This layer contains all the lowlevel device drivers for the various hardware components of an Android device. Applications — At this top layer, you will find applications that ship with the Android device (such as Phone, Contacts, Browser, etc.), as well as applications that you download and install from the Android Market. Any applications that you write are located at this layer. 25/01/12 1:04 PM
  32. 32. c01.indd 5 25/01/12 1:04 PM FIGURE 1-1 Contacts Phone FreeType SSL Camera Driver Wi-Fi Driver OpenGL / ES SGL Display Driver Keypad Driver Iibc WebKit SQLite Audio Drivers ... Power Management Binder (IPC) Driver Dalvik Virtual Machine Core Libraries ANDROID RUNTIME Notification Manager View System Location Manager Browser Flash Memory Driver LINUX KERNEL Media Framework Surface Manager LIBRARIES Resource Manager Content Providers APPLICATION FRAMEWORK Window Manager Telephony Manager Activity Manager Package Manager Home APPLICATIONS
  33. 33. 6 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING Android Devices in the Market Android devices come in all shapes and sizes. As of late November 2011, the Android OS powers the following types of devices: ➤ Smartphones ➤ Tablets ➤ E-reader devices ➤ Netbooks ➤ MP4 players ➤ Internet TVs Chances are good that you own at least one of the preceding devices. Figure 1-2 shows (left to right) the Samsung Galaxy S II, the Motorola Atrix 4G, and the HTC EVO 4G smartphones. FIGURE 1-2 Another popular category of devices that manufacturers are rushing out is the tablet. Tablets typically come in two sizes: seven inches and ten inches, measured diagonally. Figure 1-3 shows the Samsung Galaxy Tab 10.1 (left) and the Asus Eee Pad Transformer TF101 (right), both 10.1-inch tablets. Both the Samsung Galaxy 10.1 and the Asus Eee Pad Transfer TF101 run on Android 3. c01.indd 6 25/01/12 1:04 PM
  34. 34. What Is Android? ❘ 7 FIGURE 1-3 Besides smartphones and tablets, Android is also beginning to appear in dedicated devices, such as e-book readers. Figure 1-4 shows the Barnes and Noble’s NOOK Color (left) and Amazon’s Kindle Fire (right), both of which are color e-Book readers running the Android OS. FIGURE 1-4 In addition to these popular mobile devices, Android is also slowly fi nding its way into your living room. People of Lava, a Swedish company, has developed an Android-based TV, called the Scandinavia Android TV (see Figure 1-5). Google has also ventured into a proprietary smart TV platform based on Android and codeveloped with companies such as Intel, Sony, and Logitech. Figure 1-6 shows Sony’s Google TV. c01.indd 7 25/01/12 1:04 PM
  35. 35. 8 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-5 FIGURE 1-6 At the time of writing, the Samsung Galaxy Nexus (see Figure 1-7) is the only device running on Android 4.0. However, Google has promised that existing devices (such as the Nexus S) will be able to upgrade to Android 4.0. By the time you are reading this, there should be a plethora of devices running Android 4.0. FIGURE 1-7 The Android Market As mentioned earlier, one of the main factors determining the success of a smartphone platform is the applications that support it. It is clear from the success of the iPhone that applications play a very vital role in determining whether a new platform swims or sinks. In addition, making these applications accessible to the general user is extremely important. c01.indd 8 25/01/12 1:04 PM
  36. 36. Obtaining the Required Tools ❘ 9 As such, in August 2008, Google announced Android Market, an online application store for Android devices, and made it available to users in October 2008. Using the Market application that is preinstalled on their Android device, users can simply download third-party applications directly onto their devices. Both paid and free applications are supported on the Android Market, though paid applications are available only to users in certain countries due to legal issues. Similarly, in some countries, users can buy paid applications from the Android Market, but developers cannot sell in that country. As an example, at the time of writing, users in India can buy apps from the Android Market, but developers in India cannot sell apps on the Android Market. The reverse may also be true; for example, users in South Korea cannot buy apps, but developers in South Korea can sell apps on the Android Market. NOTE Chapter 12 discusses more about the Android Market and how you can sell your own applications in it. The Android Developer Community With Android in its fourth version, there is a large developer community all over the world. It is now much easier to get solutions to problems, and fi nd like-minded developers to share app ideas and exchange experiences. Here are some developer communities/sites that you can turn to for help if you run into problems while working with Android: ➤ Stack Overflow (www.stackoverflow.com) — Stack Overflow is a collaboratively edited question and answer site for developers. If you have a question about Android, chances are someone at Stack Overflow is probably already discussing the same question and someone else had already provided the answer. Best of all, other developers can vote for the best answer so that you can know which are the answers that are trustworthy. ➤ Google Android Training (http://developer.android.com/training/index .html) — Google has launched the Android Training site that contains a number of useful classes grouped by topics. At the time of writing, the classes mostly contain useful code snippets that are very useful to Android developers once they have started with the basics. Once you have learned the basics in this book, I strongly suggest you take a look at the classes. ➤ Android Discuss (http://groups.google.com/group/android-discuss) — Android Discuss is a discussion group hosted by Google using the Google Groups service. Here, you will be able to discuss the various aspects of Android programming. This group is monitored closely by the Android team at Google, and so this is good place to clarify your doubts and learn new tips and tricks. OBTAINING THE REQUIRED TOOLS Now that you know what Android is and what its feature set contains, you are probably anxious to get your hands dirty and start writing some applications! Before you write your fi rst app, however, you need to download the required tools and SDKs. c01.indd 9 25/01/12 1:04 PM
  37. 37. 10 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING For Android development, you can use a Mac, a Windows PC, or a Linux machine. All the tools needed are free and can be downloaded from the Web. Most of the examples provided in this book should work fi ne with the Android emulator, with the exception of a few examples that require access to the hardware. For this book, I am using a Windows 7 computer to demonstrate all the code samples. If you are using a Mac or Linux computer, the screenshots should look similar; some minor differences may be present, but you should be able to follow along without problems. Let the fun begin! JAVA JDK The Android SDK makes use of the Java SE Development Kit (JDK). If your computer does not have the JDK installed, you should start by downloading it from www.oracle.com/technetwork/java/javase/downloads/index.html and installing it prior to moving to the next section. Android SDK The fi rst and most important piece of software you need to download is, of course, the Android SDK. The Android SDK contains a debugger, libraries, an emulator, documentation, sample code, and tutorials. You can download the Android SDK from http://developer.android.com/sdk/index.html (see Figure 1-8). FIGURE 1-8 c01.indd 10 25/01/12 1:04 PM
  38. 38. Obtaining the Required Tools ❘ 11 The Android SDK is packaged in a zip fi le. You can download it and unzip its content (the android-sdk-windows folder) into a folder, say C:Android 4.0. For Windows user, Google recommends that you download the installer_r15-windows.exe fi le instead and use it to set up the tools for you automatically. The following steps walk you through the installation process using this approach. Installing the Android SDK Tools When you have downloaded the installer_r15-windows.exe fi le, double-click it to start the installation of the Android tools. In the welcome screen of the Setup Wizard, click Next to continue. If your computer does not have Java installed, you will see the error dialog shown in Figure 1-9. However, even if you have Java installed, you may still see this error. If this is the case, click the Report error button and then click Next. FIGURE 1-9 You will be asked to provide a destination folder to install the Android SDK tools. Enter a destination path (see Figure 1-10) and click Next. When you are asked to choose a Start Menu folder to create the program’s shortcut, take the default “Android SDK Tools” and click Install. When the setup is done, check the “Start SDK Manager (to download system images, etc.)” option and click Finish (see Figure 1-11). This will start the SDK Manager. c01.indd 11 25/01/12 1:04 PM
  39. 39. 12 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-10 FIGURE 1-11 Configuring the Android SDK Manager The Android SDK Manager manages the various versions of the Android SDK currently installed on your computer. When it is launched, you will see a list of items and whether or not they are currently installed on your computer (see Figure 1-12). Check the relevant tools, documentation, and platforms you need for your project. Once you have selected the items you want, click the Install button to download them. Because it takes a while to download from Google’s server, it is a good idea to download only what you need immediately, and download the rest when you have more time. For now, you may want to check the items shown in the figure. c01.indd 12 25/01/12 1:04 PM
  40. 40. Obtaining the Required Tools ❘ 13 FIGURE 1-12 NOTE For a start, you should at least select the latest Android 4.0 SDK platform and the Extras. At the time of writing, the latest SDK platform is SDK Platform Android 4.0, API 14. Each version of the Android OS is identified by an API level number. For example, Android 2.3.3 is level 10 (API 10), while Android 3.0 is level 11 (API 11), and so on. For each level, two platforms are available. For example, level 14 offers the following: ➤ SDK Platform ➤ Google APIs by Google Inc. The key difference between the two is that the Google APIs platform contains additional APIs provided by Google (such as the Google Maps library). Therefore, if the application you are writing requires Google Maps, you need to create an AVD using the Google APIs platform (more on this is provided in Chapter 9, “Location-Based Services.” c01.indd 13 25/01/12 1:04 PM
  41. 41. 14 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING You will be asked to choose the packages to install (see Figure 1-13). Check the Accept All option and click Install. FIGURE 1-13 The SDK Manager will proceed to download the packages that you have selected. The installation takes some time, so be patient. When all the packages are installed, you will be asked to restart the ADB (Android Debug Bridge). Click Yes. Eclipse The next step is to obtain the integrated development environment (IDE) for developing your Android applications. In the case of Android, the recommended IDE is Eclipse, a multi-language software development environment featuring an extensible plug-in system. It can be used to develop various types of applications, using languages such as Java, Ada, C, C++, COBOL, Python, and others. For Android development, you should download the Eclipse IDE for Java EE Developers (www.eclipse.org/downloads/). Six editions are available: Windows (32- and 64-bit), Mac OS X (Cocoa 32- and 64), and Linux (32- and 64-bit). Simply select the relevant one for your operating system. All the examples in this book were tested using the 32-bit version of Eclipse for Windows. Once the Eclipse IDE is downloaded, unzip its content (the eclipse folder) into a folder, say C:Android 4.0. Figure 1-14 shows the content of the eclipse folder. FIGURE 1-14 To launch Eclipse, double-click on the eclipse.exe fi le. You are fi rst asked to specify your workspace. In Eclipse, a workspace is a folder where you store all your projects. Take the default suggested (or you can specify your own folder as the workspace) and click OK. c01.indd 14 25/01/12 1:04 PM
  42. 42. Obtaining the Required Tools ❘ 15 Android Development Tools (ADT) When Eclipse is launched, select Help ➪ Install New Software (see Figure 1-15) to install the Android Development Tools (ADT) plug-in for Eclipse. FIGURE 1-15 The ADT is an extension to the Eclipse IDE that supports the creation and debugging of Android applications. Using the ADT, you will be able to do the following in Eclipse: ➤ Create new Android application projects. ➤ Access the tools for accessing your Android emulators and devices. ➤ Compile and debug Android applications. ➤ Export Android applications into Android Packages (APKs). ➤ Create digital certificates for code-signing your APK. In the Install dialog that appears, specify https://dl-ssl.google.com/android/eclipse/ and press Enter. After a while, you will see the Developer Tools item appear in the middle of the window (see Figure 1-16). Expand it to reveal its content: Android DDMS, Android Development Tools, Android Hierarchy Viewer, and Android Traceview. Check all of them and click Next twice. c01.indd 15 25/01/12 1:05 PM
  43. 43. 16 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-16 NOTE If you have any problems downloading the ADT, check out Google’s help at http://developer.android.com/sdk/eclipse-adt.html#installing. You will be asked to review and accept the licenses. Check the “I accept the terms of the license agreements” option and click Finish. Once the installation is completed, you will be asked to restart Eclipse. Go ahead and restart Eclipse now. When Eclipse is restarted, you are asked to configure your Android SDK (see Figure 1-17). As the Android SDK has already been downloaded earlier in the previous section, check the “Use existing SDKs” option and specify the directory where you have installed the Android SDK. Click Next. After this step, you are asked to send your usage statistics to Google. Once you have selected your choice, click Finish. c01.indd 16 FIGURE 1-17 25/01/12 1:05 PM
  44. 44. Obtaining the Required Tools ❘ 17 NOTE As each new version of the SDK is released, the installation steps tend to differ slightly. If you do not experience the same steps as described here, don’t worry — just follow the instructions on screen. Creating Android Virtual Devices (AVDs) The next step is to create an Android Virtual Device (AVD) to be used for testing your Android applications. An AVD is an emulator instance that enables you to model an actual device. Each AVD consists of a hardware profi le; a mapping to a system image; as well as emulated storage, such as a secure digital (SD) card. You can create as many AVDs as you want in order to test your applications with several different configurations. This testing is important to confi rm the behavior of your application when it is run on different devices with varying capabilities. NOTE Appendix B discusses some of the capabilities of the Android emulator. To create an AVD, select Window ➪ AVD Manager (see Figure 1-18). FIGURE 1-18 c01.indd 17 25/01/12 1:05 PM
  45. 45. 18 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING In the Android Virtual Device Manager dialog (see Figure 1-19), click the New... button to create a new AVD. FIGURE 1-19 In the Create new Android Virtual Device (AVD) dialog, enter the items as shown in Figure 1-20. Click the Create AVD button when you are done. FIGURE 1-20 c01.indd 18 25/01/12 1:05 PM
  46. 46. Obtaining the Required Tools ❘ 19 In this case, you have created an AVD (put simply, an Android emulator) that emulates an Android device running version 4.0 of the OS with a built-in 10-MB SD card. In addition to what you have created, you also have the option to emulate the device with different screen densities and resolutions. NOTE Appendix B explains how to emulate the different types of Android devices. It is preferable to create a few AVDs with different API levels and hardware configurations so that your application can be tested on different versions of the Android OS. Once your ADV has been created, it is time to test it. Select the AVD that you want to test and click the Start… button. The Launch Options dialog will appear (see Figure 1-21). If you have a small monitor, it is recommended that you check the “Scale display to real size” option so that you can set the emulator to a smaller size. Click the Launch button to start the emulator. FIGURE 1-21 The Android emulator will start, and after a while it will be ready for use (see Figure 1-22). Go ahead and try out the emulator. It will behave just like a real Android device. After that, in the next section you will learn how to write your fi rst Android application! c01.indd 19 25/01/12 1:05 PM
  47. 47. ❘ 20 CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-22 CREATING YOUR FIRST ANDROID APPLICATION With all the tools and the SDK downloaded and installed, it is now time to start your engine. As in all programming books, the fi rst example uses the ubiquitous Hello World application. This will give you a detailed look at the various components that make up an Android project. TRY IT OUT Creating Your First Android Application codefile HelloWorld.zip available for download at Wrox.com 1. c01.indd 20 Using Eclipse, create a new project by selecting File ➪ New ➪ Project . . . (see Figure 1-23). 25/01/12 1:05 PM
  48. 48. Creating Your First Android Application ❘ 21 FIGURE 1-23 NOTE After you have created your first Android application, subsequent Android projects can be created by selecting File ➪ New ➪ Android Project. 2. 3. Expand the Android folder and select Android Project (see Figure 1-24). Click Next. Name the Android project HelloWorld, as shown in Figure 1-25, and then click Next. FIGURE 1-24 c01.indd 21 25/01/12 1:05 PM
  49. 49. 22 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-25 4. 5. Select the Android 4.0 target and click Next. Fill in the Application Info details as shown in Figure 1-26. Click Finish. FIGURE 1-26 c01.indd 22 25/01/12 1:05 PM
  50. 50. Creating Your First Android Application ❘ 23 NOTE You need to have at least a period (.) in the package name. The recommended convention for the package name is to use your domain name in reverse order, followed by the project name. For example, my company’s domain name is learn2develop.net; hence, my package name would be net.learn2develop.HelloWorld. 6. The Eclipse IDE should now look like Figure 1-27. FIGURE 1-27 7. 8. c01.indd 23 In the Package Explorer (located on the left of the Eclipse IDE), expand the HelloWorld project by clicking on the various arrows displayed to the left of each item in the project (see Figure 1-28). In the res/layout folder, double-click the main.xml fi le. The main.xml fi le defi nes the user interface (UI) of your application. The default view is the Layout view, which lays out the activity graphically. To modify the UI by hand, click the main.xml tab located at the bottom (see Figure 1-29). 25/01/12 1:05 PM
  51. 51. 24 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING FIGURE 1-28 FIGURE 1-29 9. Add the following code in bold to the main.xml fi le: <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/ android” android:layout_width=”fill_parent” c01.indd 24 25/01/12 1:05 PM
  52. 52. Creating Your First Android Application ❘ 25 android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/hello” /> <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”This is my first Android Application!” /> <Button android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”And this is a clickable button!” /> </LinearLayout> 10. 11. To save the changes made to your project, press Ctrl+S. You are now ready to test your application on the Android emulator. Right-click the project name in Eclipse and select Run As ➪ Android Application (see Figure 1-30). FIGURE 1-30 c01.indd 25 25/01/12 1:05 PM
  53. 53. 26 ❘ 12. CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING If you have not made any mistakes in the project, you should now be able to see the application installed and running on the Android emulator (see Figure 1-31). FIGURE 1-31 13. Click the Home button (the house icon in the lower-left corner above the keyboard) so that it now shows the Home screen (see Figure 1-32). 14. Click the application launcher icon to display the list of applications installed on the device. Note that the HelloWorld application is now installed in the application launcher (see Figure 1-33). c01.indd 26 25/01/12 1:05 PM
  54. 54. Creating Your First Android Application ❘ 27 FIGURE 1-32 FIGURE 1-33 c01.indd 27 25/01/12 1:05 PM
  55. 55. 28 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING WHICH AVD WILL BE USED TO TEST YOUR APPLICATION? Recall that earlier you created a few AVDs using the AVD Manager. So which one will be launched by Eclipse when you run an Android application? Eclipse checks the target that you specified (when you created a new project), comparing it against the list of AVDs that you have created. The first one that matches will be launched to run your application. If you have more than one suitable AVD running prior to debugging the application, Eclipse will display the Android Device Chooser dialog, which enables you to select the desired emulator/device to debug the application (see Figure 1-34). FIGURE 1-34 How It Works To create an Android project using Eclipse, you need to supply the information shown in Table 1-2. TABLE 1-2: Project Files Created by Default PROPERTIES Project name The name of the project Application name A user-friendly name for your application Package name The name of the package. You should use a reverse domain name for this. Create Activity The name of the first activity in your application Min SDK Version c01.indd 28 DESCRIPTION The minimum version of the SDK that your project is targeting 25/01/12 1:05 PM
  56. 56. ❘ 29 Anatomy of an Android Application In Android, an activity is a window that contains the user interface of your applications. An application can have zero or more activities; in this example, the application contains one activity: HelloWorldActivity. This HelloWorldActivity is the entry point of the application, which is displayed when the application is started. Chapter 2 discusses activities in more detail. In this simple example, you modified the main.xml fi le to display the string “This is my fi rst Android Application!” and a button. The main.xml fi le contains the user interface of the activity, which is displayed when HelloWorldActivity is loaded. When you debug the application on the Android emulator, the application is automatically installed on the emulator. And that’s it — you have developed your fi rst Android application! The next section unravels how all the various fi les in your Android project work together to make your application come alive. ANATOMY OF AN ANDROID APPLICATION Now that you have created your fi rst Hello World Android application, it is time to dissect the innards of the Android project and examine all the parts that make everything work. First, note the various fi les that make up an Android project in the Package Explorer in Eclipse (see Figure 1-35). The various folders and their files are as follows: ➤ src — Contains the .java source files for your project. In this example, there is one file, HelloWorldActivity .java. The HelloWorldActivity.java file is the source file for your activity. You write the code for your application in this file. The Java file is listed under the package name for your project, which in this case is net .learn2develop.HelloWorld. ➤ gen — Contains the R.java file, a compiler-generated file that references all the resources found in your project. You should not modify this file. All the resources in your project are automatically compiled into this class so that you can refer to them using the class. ➤ Android 4.0 library — This item contains one file, android.jar, which contains all the class libraries needed for an Android application. ➤ assets — This folder contains all the assets used by your application, such as HTML, text files, databases, etc. ➤ bin — This folder contains the files built by the ADT during the build process. In particular, it generates the .apk file (Android Package). An .apk file is the application binary of an FIGURE 1-35 Android application. It contains everything needed to run an Android application. c01.indd 29 25/01/12 1:05 PM
  57. 57. 30 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING ➤ res — This folder contains all the resources used in your application. It also contains a few other subfolders: drawable-<resolution>, layout, and values. Chapter 3 talks more about how you can support devices with different screen resolutions and densities. ➤ AndroidManifest.xml — This is the manifest file for your Android application. Here you specify the permissions needed by your application, as well as other features (such as intent-filters, receivers, etc.). Chapter 2 discusses the use of the AndroidManifest.xml file in more detail. The main.xml fi le defi nes the user interface for your activity. Observe the following in bold: <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/hello” /> The @string in this case refers to the strings.xml fi le located in the res/values folder. Hence, @string/hello refers to the hello string defi ned in the strings.xml fi le, which is “Hello World, HelloWorldActivity!”: <?xml version=”1.0” encoding=”utf-8”?> <resources> <string name=”hello”>Hello World, HelloWorldActivity!</string> <string name=”app_name”>HelloWorld</string> </resources> It is recommended that you store all the string constants in your application in this strings.xml fi le and reference these strings using the @string identifier. That way, if you ever need to localize your application to another language, all you need to do is make a copy of the entire values folder and modify the values of strings.xml to contain the string in the language that you want to display. Figure 1-36 shows that I have another folder named values-fr with the strings.xml fi le containing the same hello string in French. FIGURE 1-36 c01.indd 30 25/01/12 1:05 PM
  58. 58. Anatomy of an Android Application ❘ 31 If the user loads the same application on a phone configured to display French as the default language, your application will automatically display the hello string in French. The next important fi le in an Android project is the manifest fi le. Note the content of the AndroidManifest.xml fi le: <?xml version=”1.0” encoding=”utf-8”?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”net.learn2develop.HelloWorld” android:versionCode=”1” android:versionName=”1.0” > <uses-sdk android:minSdkVersion=”14” /> <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” > <activity android:label=”@string/app_name” android:name=”.HelloWorldActivity” > <intent-filter > <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> The AndroidManifest.xml fi le contains detailed information about the application: ➤ ➤ The version code of the application is 1 (set via the android:versionCode attribute). This value is used to identify the version number of your application. It can be used to programmatically determine whether an application needs to be upgraded. ➤ The version name of the application is 1.0 (set via the android:versionName attribute). This string value is mainly used for display to the user. You should use the format <major>.<minor>.<point> for this value. ➤ The android:minSdkVersion attribute of the <uses-sdk> element specifies the minimum version of the OS on which the application will run. ➤ The application uses the image named ic_launcher.png located in the drawable folders. ➤ The name of this application is the string named app_name defined in the strings.xml file. ➤ c01.indd 31 It defines the package name of the application as net.learn2develop.HelloWorld. There is one activity in the application represented by the HelloWorldActivity.java file. The label displayed for this activity is the same as the application name. 25/01/12 1:05 PM
  59. 59. 32 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING ➤ Within the definition for this activity, there is an element named <intent-filter>: ➤ The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. ➤ The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device’s launcher icon. Chapter 2 discusses intents in more detail. As you add more fi les and folders to your project, Eclipse will automatically generate the content of R.java, which currently contains the following: /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package net.learn2develop.HelloWorld; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } You are not supposed to modify the content of the R.java fi le; Eclipse automatically generates the content for you when you modify your project. NOTE If you delete R.java manually, Eclipse will regenerate it for you immediately. Note that in order for Eclipse to generate the R.java file for you, the project must not contain any errors. If you realize that Eclipse has not regenerated R.java after you have deleted it, check your project again. The code may contain syntax errors, or your XML files (such as AndroidManifest .xml, main.xml, etc.) may not be well-formed. c01.indd 32 25/01/12 1:05 PM
  60. 60. ❘ 33 Summary Finally, the code that connects the activity to the UI (main.xml) is the setContentView() method, which is in the HelloWorldActivity.java fi le: package net.learn2develop.HelloWorld; import android.app.Activity; import android.os.Bundle; public class HelloWorldActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } Here, R.layout.main refers to the main.xml fi le located in the res/layout folder. As you add additional XML fi les to the res/layout folder, the filenames will automatically be generated in the R.java fi le. The onCreate() method is one of many methods that are fi red when an activity is loaded. Chapter 2 discusses the life cycle of an activity in more detail. SUMMARY This chapter has provided a brief overview of Android, and highlighted some of its capabilities. If you have followed the sections on downloading the tools and the Android SDK, you should now have a working system — one that is capable of developing more interesting Android applications other than the Hello World application. In the next chapter, you will learn about the concepts of activities and intents, and the very important roles they play in Android. EXERCISES 1. What is an AVD? 2. What is the difference between the android:versionCode and android:versionName attributes in the AndroidManifest.xml file? 3. What is the use of the strings.xml file? Answers to the exercises can be found in Appendix C. c01.indd 33 25/01/12 1:05 PM
  61. 61. 34 ❘ CHAPTER 1 GETTING STARTED WITH ANDROID PROGRAMMING WHAT YOU LEARNED IN THIS CHAPTER TOPIC Android OS Android is an open source mobile operating system based on the Linux operating system. It is available to anyone who wants to adapt it to run on their own devices. Languages used for Android application development You use the Java programming language to develop Android applications. Written applications are compiled into Dalvik executables, which are then run on top of the Dalvik virtual machine. Android Market The Android Market hosts all the various Android applications written by third-party developers. Tools for Android application development Eclipse IDE, Android SDK, and the ADT Activities An activity is represented by a screen in your Android application. Each application can have zero or more activities. The Android manifest file c01.indd 34 KEY CONCEPTS The AndroidManifest.xml file contains detailed configuration information for your application. As your example application becomes more sophisticated, you will modify this file, and you will see the different information you can add to it as you progress through the chapters. 25/01/12 1:05 PM
  62. 62. 2 Activities, Fragments, and Intents WHAT YOU WILL LEARN IN THIS CHAPTER ➤ The life cycles of an activity ➤ Using fragments to customize your UI ➤ Applying styles and themes to activities ➤ How to display activities as dialog windows ➤ Understanding the concept of intents ➤ Using the Intent object to link activities ➤ How intent filters help you selectively connect to other activities ➤ Displaying alerts to the user using notifications In Chapter 1, you learned that an activity is a window that contains the user interface of your application. An application can have zero or more activities. Typically, applications have one or more activities; and the main purpose of an activity is to interact with the user. From the moment an activity appears on the screen to the moment it is hidden, it goes through a number of stages, known as an activity’s life cycle. Understanding the life cycle of an activity is vital to ensuring that your application works correctly. In addition to activities, Android 4.0 also supports a feature that was introduced in Android 3.0 (for tablets): fragments. Think of fragments as “miniature” activities that can be grouped to form an activity. In this chapter, you will learn about how activities and fragments work together. Apart from activities, another unique concept in Android is that of an intent. An intent is basically the “glue” that enables different activities from different applications to work together seamlessly, ensuring that tasks can be performed as though they all belong to one single application. Later in this chapter, you will learn more about this very important concept and how you can use it to call built-in applications such as the Browser, Phone, Maps, and more. c02.indd 35 25/01/12 12:13 PM
  63. 63. 36 ❘ CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS UNDERSTANDING ACTIVITIES This chapter begins by looking at how to create an activity. To create an activity, you create a Java class that extends the Activity base class: package net.learn2develop.Activity101; import android.app.Activity; import android.os.Bundle; public class Activity101Activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } Your activity class loads its UI component using the XML fi le defi ned in your res/layout folder. In this example, you would load the UI from the main.xml fi le: setContentView(R.layout.main); Every activity you have in your application must be declared in your AndroidManifest.xml file, like this: <?xml version=“1.0“ encoding=“utf-8“?> <manifest xmlns:android=“http://schemas.android.com/apk/res/android“ package=”net.learn2develop.Activity101” android:versionCode=”1” android:versionName=”1.0” > <uses-sdk android:minSdkVersion=”14” /> <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” > <activity android:label=”@string/app_name” android:name=”.Activity101Activity” > <intent-filter > <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> The Activity base class defi nes a series of events that govern the life cycle of an activity. The Activity class defi nes the following events: ➤ ➤ onStart() — Called when the activity becomes visible to the user ➤ c02.indd 36 onCreate() — Called when the activity is first created onResume() — Called when the activity starts interacting with the user 25/01/12 12:13 PM
  64. 64. Understanding Activities ➤ ❘ 37 onPause() — Called when the current activity is being paused and the previous activity is being resumed ➤ onStop() — Called when the activity is no longer visible to the user ➤ onDestroy() — Called before the activity is destroyed by the system (either manually or by the system to conserve memory) ➤ onRestart() — Called when the activity has been stopped and is restarting again By default, the activity created for you contains the onCreate() event. Within this event handler is the code that helps to display the UI elements of your screen. Figure 2-1 shows the life cycle of an activity and the various stages it goes through — from when the activity is started until it ends. Activity starts onCreate() User navigates back to the activity Process is killed onStart() onRestart() onResume() Activity is running The activity comes to the foreground Another activity comes in front of the activity Other applications need memory onPause() The activity comes to the foreground The activity is no longer visible onStop() onDestroy() Activity is shut down Image reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. See http://developer.android .com/reference/android/app/Activity.html FIGURE 2-1 c02.indd 37 25/01/12 12:13 PM
  65. 65. ❘ 38 CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS The best way to understand the various stages of an activity is to create a new project, implement the various events, and then subject the activity to various user interactions. TRY IT OUT Understanding the Life Cycle of an Activity codefile Activity101.zip available for download at Wrox.com 1. 2. Using Eclipse, create a new Android project and name it Activity101. In the Activity101Activity.java fi le, add the following statements in bold: package net.learn2develop.Activity101; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Activity101Activity extends Activity { String tag = “Lifecycle”; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d(tag, “In the onCreate() event”); } public void onStart() { super.onStart(); Log.d(tag, “In the onStart() event”); } public void onRestart() { super.onRestart(); Log.d(tag, “In the onRestart() event”); } public void onResume() { super.onResume(); Log.d(tag, “In the onResume() event”); } public void onPause() { super.onPause(); Log.d(tag, “In the onPause() event”); } public void onStop() c02.indd 38 25/01/12 12:13 PM
  66. 66. Understanding Activities ❘ 39 { super.onStop(); Log.d(tag, “In the onStop() event”); } public void onDestroy() { super.onDestroy(); Log.d(tag, “In the onDestroy() event”); } } 3. 4. Press F11 to debug the application on the Android emulator. When the activity is fi rst loaded, you should see something very similar to the following in the LogCat window (click the Debug perspective; see also Figure 2-2): 11-16 06:25:59.396: D/Lifecycle(559): In the onCreate() event 11-16 06:25:59.396: D/Lifecycle(559): In the onStart() event 11-16 06:25:59.396: D/Lifecycle(559): In the onResume() event FIGURE 2-2 5. If you click the Back button on the Android emulator, the following is printed: 11-16 06:29:26.665: D/Lifecycle(559): In the onPause() event 11-16 06:29:28.465: D/Lifecycle(559): In the onStop() event 11-16 06:29:28.465: D/Lifecycle(559): In the onDestroy() event c02.indd 39 25/01/12 12:13 PM
  67. 67. 40 ❘ 6. CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS Click the Home button and hold it there. Click the Activities icon and observe the following: 11-16 06:31:08.905: D/Lifecycle(559): In the onCreate() event 11-16 06:31:08.905: D/Lifecycle(559): In the onStart() event 11-16 06:31:08.925: D/Lifecycle(559): In the onResume() event 7. Click the Phone button on the Android emulator so that the activity is pushed to the background. Observe the output in the LogCat window: 11-16 06:32:00.585: D/Lifecycle(559): In the onPause() event 11-16 06:32:05.015: D/Lifecycle(559): In the onStop() event 8. Notice that the onDestroy() event is not called, indicating that the activity is still in memory. Exit the phone dialer by clicking the Back button. The activity is now visible again. Observe the output in the LogCat window: 11-16 06:32:50.515: D/Lifecycle(559): In the onRestart() event 11-16 06:32:50.515: D/Lifecycle(559): In the onStart() event 11-16 06:32:50.515: D/Lifecycle(559): In the onResume() event The onRestart() event is now fi red, followed by the onStart() and onResume() methods. How It Works As you can see from this simple example, an activity is destroyed when you click the Back button. This is crucial to know, as whatever state the activity is currently in will be lost; hence, you need to write additional code in your activity to preserve its state when it is destroyed (Chapter 3 shows you how). At this point, note that the onPause() method is called in both scenarios — when an activity is sent to the background, as well as when it is killed when the user presses the Back button. When an activity is started, the onStart() and onResume()methods are always called, regardless of whether the activity is restored from the background or newly created. When an activity is created for the fi rst time, the onCreate() method is called. From the preceding example, you can derive the following guidelines: ➤ Use the onCreate() method to create and instantiate the objects that you will be using in your application. ➤ Use the onResume() method to start any services or code that needs to run while your activity is in the foreground. ➤ Use the onPause() method to stop any services or code that does not need to run when your activity is not in the foreground. ➤ Use the onDestroy() method to free up resources before your activity is destroyed. NOTE Even if an application has only one activity and the activity is killed, the application will still be running in memory. c02.indd 40 25/01/12 12:13 PM
  68. 68. Understanding Activities ❘ 41 Applying Styles and Themes to an Activity By default, an activity occupies the entire screen. However, you can apply a dialog theme to an activity so that it is displayed as a floating dialog. For example, you might want to customize your activity to display as a pop-up, warning users about some actions that they are going to perform. In this case, displaying the activity as a dialog is a good way to get their attention. To apply a dialog theme to an activity, simply modify the <Activity> element in the AndroidManifest.xml fi le by adding the android:theme attribute: <?xml version=“1.0“ encoding=“utf-8“?> <manifest xmlns:android=“http://schemas.android.com/apk/res/android“ package=”net.learn2develop.Activity101” android:versionCode=”1” android:versionName=”1.0” > <uses-sdk android:minSdkVersion=”14” /> <application android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@android:style/Theme.Dialog”> <activity android:label=”@string/app_name” android:name=”.Activity101Activity” > <intent-filter > <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> This will make the activity appear as a dialog, as shown in Figure 2-3. Hiding the Activity Title You can also hide the title of an activity if desired (such as when you just want to display a status update to the user). To do so, use the requestWindowFeature() method and pass it the Window .FEATURE_NO_TITLE constant, like this: import import import import android.app.Activity; android.os.Bundle; android.util.Log; android.view.Window; public class Activity101Activity extends Activity { c02.indd 41 FIGURE 2-3 25/01/12 12:14 PM
  69. 69. ❘ 42 CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS String tag = “Lifecycle”; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //---hides the title bar--requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); Log.d(tag, “In the onCreate() event”); } } This will hide the title bar, as shown in Figure 2-4. Displaying a Dialog Window There are times when you need to display a dialog window to get a confi rmation from the user. In this case, you can override the onCreateDialog() protected method defi ned in the Activity base FIGURE 2-4 class to display a dialog window. The following Try It Out shows you how. TRY IT OUT Displaying a Dialog Window Using an Activity codefile Dialog.zip available for download at Wrox.com 1. 2. Using Eclipse, create a new Android project and name it Dialog. Add the following statements in bold to the main.xml fi le: <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <Button android:id=”@+id/btn_dialog” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Click to display a dialog” android:onClick=”onClick” /> </LinearLayout> 3. Add the following statements in bold to the DialogActivity.java fi le: package net.learn2develop.Dialog; import android.app.Activity; c02.indd 42 25/01/12 12:14 PM
  70. 70. Understanding Activities import import import import import import ❘ 43 android.app.AlertDialog; android.app.Dialog; android.content.DialogInterface; android.os.Bundle; android.view.View; android.widget.Toast; public class DialogActivity extends Activity { CharSequence[] items = { “Google”, “Apple”, “Microsoft” }; boolean[] itemsChecked = new boolean [items.length]; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClick(View v) { showDialog(0); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: return new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle(“This is a dialog with some simple text...”) .setPositiveButton(“OK”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “OK clicked!”, Toast.LENGTH_SHORT).show(); } } ) .setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “Cancel clicked!”, Toast.LENGTH_SHORT).show(); } } ) .setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), items[which] + (isChecked ? “ checked!”:” unchecked!”), Toast.LENGTH_SHORT).show(); c02.indd 43 25/01/12 12:14 PM
  71. 71. 44 ❘ CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS } } ).create(); } return null; } } 4. Press F11 to debug the application on the Android emulator. Click the button to display the dialog (see Figure 2-5). Checking the various checkboxes will cause the Toast class to display the text of the item checked/unchecked. To dismiss the dialog, click the OK or Cancel button. How It Works To display a dialog, you fi rst implement the onCreateDialog() method in the Activity class: FIGURE 2-5 @Override protected Dialog onCreateDialog(int id) { //... } This method is called when you call the showDialog() method: public void onClick(View v) { showDialog(0); } The onCreateDialog() method is a callback for creating dialogs that are managed by the activity. When you call the showDialog() method, this callback will be invoked. The showDialog() method accepts an integer argument identifying a particular dialog to display. In this case, we used a switch statement to identify the different types of dialogs to create, although the current example creates only one type of dialog. Subsequent Try It Out exercises will extend this example to create different types of dialogs. To create a dialog, you use the AlertDialog class’s Builder constructor. You set the various properties, such as icon, title, and buttons, as well as checkboxes: @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: return new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle(“This is a dialog with some simple text...”) .setPositiveButton(“OK”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) c02.indd 44 25/01/12 12:14 PM
  72. 72. Understanding Activities ❘ 45 { Toast.makeText(getBaseContext(), “OK clicked!”, Toast.LENGTH_SHORT).show(); } } ) .setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “Cancel clicked!”, Toast.LENGTH_SHORT).show(); } } ) .setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), items[which] + (isChecked ? “ checked!”:” unchecked!”), Toast.LENGTH_SHORT).show(); } } ).create(); } return null; } The preceding code sets two buttons, OK and Cancel, using the setPositiveButton() and setNegativeButton() methods, respectively. You also set a list of checkboxes for users to choose via the setMultiChoiceItems() method. For the setMultiChoiceItems() method, you passed in two arrays: one for the list of items to display and another to contain the value of each item, to indicate if they are checked. When each item is checked, you use the Toast class to display a message indicating the item that was checked. The preceding code for creating the dialog looks complicated, but it could easily be rewritten as follows: package net.learn2develop.Dialog; import import import import import import import import android.app.Activity; android.app.AlertDialog; android.app.AlertDialog.Builder; android.app.Dialog; android.content.DialogInterface; android.os.Bundle; android.view.View; android.widget.Toast; public class DialogActivity extends Activity { c02.indd 45 25/01/12 12:14 PM
  73. 73. 46 ❘ CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS CharSequence[] items = { “Google”, “Apple”, “Microsoft” }; boolean[] itemsChecked = new boolean [items.length]; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClick(View v) { showDialog(0); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle(“This is a dialog with some simple text...”); builder.setPositiveButton(“OK”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “OK clicked!”, Toast.LENGTH_SHORT).show(); } } ); builder.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “Cancel clicked!”, Toast.LENGTH_SHORT).show(); } } ); builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), items[which] + (isChecked ? “ checked!”:” unchecked!”), Toast.LENGTH_SHORT).show(); } } ); return builder.create(); } return null; } } c02.indd 46 25/01/12 12:14 PM
  74. 74. Understanding Activities ❘ 47 THE CONTEXT OBJECT In Android, you often encounter the Context class and its instances. Instances of the Context class are often used to provide references to your application. For example, in the following code snippet, the first parameter of the Toast class takes in a Context object: .setPositiveButton(“OK”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), “OK clicked!”, Toast.LENGTH_SHORT).show(); } } However, because the Toast() class is not used directly in the activity (it is used within the AlertDialog class), you need to return an instance of the Context class by using the getBaseContext() method. You also encounter the Context class when creating a view dynamically in an activity. For example, you may want to dynamically create a TextView from code. To do so, you instantiate the TextView class, like this: TextView tv = new TextView(this); The constructor for the TextView class takes a Context object; and because the Activity class is a subclass of Context, you can use the this keyword to represent the Context object. Displaying a Progress Dialog One common UI feature in an Android device is the “Please wait” dialog that you typically see when an application is performing a long-running task. For example, the application may be logging in to a server before the user is allowed to use it, or it may be doing a calculation before displaying the result to the user. In such cases, it is helpful to display a dialog, known as a progress dialog, so that the user is kept in the loop. The following Try It Out demonstrates how to display such a dialog. TRY IT OUT 1. Displaying a Progress (Please Wait) Dialog Using the same project created in the previous section, add the following statements in bold to the main.xml fi le: <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” c02.indd 47 25/01/12 12:14 PM
  75. 75. 48 ❘ CHAPTER 2 ACTIVITIES, FRAGMENTS, AND INTENTS android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <Button android:id=”@+id/btn_dialog” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Click to display a dialog” android:onClick=”onClick” /> <Button android:id=”@+id/btn_dialog2” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Click to display a progress dialog” android:onClick=”onClick2” /> </LinearLayout> 2. Add the following statements in bold to the DialogActivity.java fi le: package net.learn2develop.Dialog; import import import import import import import import import android.app.Activity; android.app.AlertDialog; android.app.AlertDialog.Builder; android.app.Dialog; android.app.ProgressDialog; android.content.DialogInterface; android.os.Bundle; android.view.View; android.widget.Toast; public class DialogActivity extends Activity { CharSequence[] items = { “Google”, “Apple”, “Microsoft” }; boolean[] itemsChecked = new boolean [items.length]; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClick(View v) { showDialog(0); } public void onClick2(View v) { //---show the dialog--final ProgressDialog dialog = ProgressDialog.show( this, “Doing something”, “Please wait...”, true); new Thread(new Runnable(){ c02.indd 48 25/01/12 12:14 PM
  76. 76. Understanding Activities ❘ 49 public void run(){ try { //---simulate doing something lengthy--Thread.sleep(5000); //---dismiss the dialog--dialog.dismiss(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } @Override protected Dialog onCreateDialog(int id) { ... } } 3. Press F11 to debug the application on the Android emulator. Clicking the second button will display the progress dialog, as shown in Figure 2-6. It will go away after five seconds. How It Works Basically, to create a progress dialog, you created an instance of the ProgressDialog class and called its show() method: FIGURE 2-6 //---show the dialog--final ProgressDialog dialog = ProgressDialog.show( this, “Doing something”, “Please wait...”, true); This displays the progress dialog that you have just seen. Because this is a modal dialog, it will block the UI until it is dismissed. To perform a long-running task in the background, you created a Thread using a Runnable block (you will learn more about threading in Chapter 11). The code that you placed inside the run() method will be executed in a separate thread, and in this case you simulated it performing something for five seconds by inserting a delay using the sleep() method: new Thread(new Runnable(){ public void run(){ try { //---simulate doing something lengthy--Thread.sleep(5000); //---dismiss the dialog--dialog.dismiss(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); After the five seconds elapse, you dismiss the dialog by calling the dismss() method. c02.indd 49 25/01/12 12:14 PM

×