Tải bản đầy đủ (.pdf) (441 trang)

beginning android application development lee 2011 04 19 Lập trình android

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (35.97 MB, 441 trang )

CuuDuongThanCong.com


Beginning Android™ Application Development
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2011 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-01711-1
ISBN: 978-1-118-08729-9 (ebk)
ISBN: 978-1-118-08749-7 (ebk)
ISBN: 978-1-118-08780-0 (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 />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 also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
Library of Congress Control Number: 2011921777
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 affiliates, 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. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in
this book.

CuuDuongThanCong.com


Contents

Introduction
Chapter 1: Getting Started with Android Programming

What Is Android?

xv
1

2

Android Versions
Features of Android
Architecture of Android

Android Devices in the Market
The Android Market

2
3
3
4
6

Obtaining the Required Tools

6

Eclipse
Android SDK
Android Development Tools (ADT)
Creating Android Virtual Devices (AVDs)
Creating Your First Android Application
Anatomy of an Android Application

Summary
Chapter 2: Activities and Intents

Understanding Activities
Applying Styles and Themes to Activity
Hiding the Activity Title
Displaying a Dialog Window
Displaying a Progress Dialog

Linking Activities Using Intents

Resolving Intent Filter Collision
Returning Results from an Intent
Passing Data Using an Intent Object

Calling Built-In Applications Using Intents
Understanding the Intent Object
Using Intent Filters
Adding Categories

Displaying Notifications
Summary

CuuDuongThanCong.com

7
7
7
11
14
22

25
27

27
32
33
34
39


43
48
50
54

56
64
65
71

73
78


CONTENTS

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


Managing Changes to Screen Orientation
Persisting State Information during Changes in Configuration
Detecting Orientation Changes
Controlling the Orientation of the Activity

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 Using Views

Basic Views
TextView View
Button, ImageButton, EditText, CheckBox, ToggleButton, RadioButton,
and RadioGroup Views
ProgressBar View
AutoCompleteTextView View

Picker Views
TimePicker View
Displaying the TimePicker in a Dialog Window
DatePicker View
Displaying the DatePicker View in a Dialog Window

List Views
ListView View
Customizing the ListView

Using the Spinner View

Summary

x

CuuDuongThanCong.com

81

81
82
83
87
89
91
93
95

97
98
101

104
108
109
110

111
114

114
119

122
125

126
126
127
135
141

144
144
147
149
153

156
156
159
162

166


CONTENTS

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
Using getSharedPreferences()
Using getPreferences()

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

Adding Contacts
Retrieving All the Contacts
Retrieving a Single Contact
Updating a Contact
Deleting a Contact
Upgrading the Database
Pre-Creating the Database
Bundling the Database with an Application

Summary
Chapter 7: Content Providers

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

169

169
170
177
181

185
186
188
190

193
194

194

200
203

203
204
208

209
209
214
216
217

218
218
224
224
225
226
227
228
230
230
231

234
237


237
238
243
xi

CuuDuongThanCong.com


CONTENTS

Projections
Filtering
Sorting

Creating Your Own Content Providers
Using the Content Provider

Summary
Chapter 8: Messaging and Networking

SMS Messaging
Sending SMS Messages Programmatically
Getting Feedback After Sending the Message
Sending SMS Messages Using Intent
Receiving SMS Messages
Updating an Activity from a BroadcastReceiver
Invoking an Activity from a BroadcastReceiver
Caveats and Warnings

Sending E‑Mail

Networking
Downloading Binary Data
Downloading Text Files
Accessing Web Services
Performing Asynchronous Calls

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

Summary

xii

CuuDuongThanCong.com

246

246
247

247
256

260
263

263
264
267
269
270
273
277
280

281
284
286
288
291
296

297
301

302
302

303
305
308
310
312
315
318
320

322
327

327


CONTENTS

Chapter 10: Developing Android Services

Creating Your Own Services
Performing Long-Running Tasks in a Service
Performing Repeated Tasks in a Service
Executing Asynchronous Tasks on
Separate Threads Using IntentService

331

331
336
341

343

Communicating between a Service and an Activity
Binding Activities to Services
Summary

346
350
356

Chapter 11: Publishing Android Applications

359

Preparing for Publishing
Versioning
Digitally Signing Your Android Applications

Deploying APK Files
Using the adb.exe Tool
Using a Web Server
Publishing on the Android Market
Creating a Developer Profile
Submitting Your Apps

Summary
Appendix A: Using Eclipse for Android Development

Getting Around in Eclipse
Workspaces

Package Explorer
Using Projects from Other Workspaces
Editors
Perspectives
Auto Import of Namespaces
Code Completion
Refactoring

Debugging
Setting Breakpoints
Exceptions

Appendix B: Using the Android Emulator

Uses of the Android Emulator
Installing Custom AVDs

359
360
362

367
367
369
372
372
373

378
3 81


381
381
382
383
385
387
387
388
388

389
389
390

393

393
393

xiii

CuuDuongThanCong.com


CONTENTS

Emulating Real Devices
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
Appendix C: Answers to Exercises

Chapter 1 Answers
Chapter 2 Answers
Chapter 3 Answers
Chapter 4 Answers
Chapter 5 Answers
Chapter 6 Answers
Chapter 7 Answers
Chapter 8 Answers
Chapter 9 Answers
Chapter 10 Answers
Chapter 11 Answers
Index

xiv

CuuDuongThanCong.com

398
399
401
402
403
406

407
409
411

411
411
412
412
412
413
413
413
413
414
414
415


CuuDuongThanCong.com


introduction

What This Book Covers
This book covers the fundamentals of Android programming using the Android SDK. It is divided
into 11 chapters and three appendices.
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 in the market. You will then 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 and Intents gets you acquainted with the two fundamental concepts in Android
programming: activities and intents. Activities are the building blocks of an Android application. You
will learn how to link activities together to form a complete Android application using intents, the
glue to links activities and 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 Using 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.
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 files onto internal and external storage (SD card). In addition, you will learn how to
create and use a SQLite database in your Android application.
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 and Networking explores two of the most interesting topics in mobile programming — sending SMS messages and network programming. You will learn how to programmatically send and receive SMS and e‑mail messages; and how to connect to web servers to download
data. Finally, you will see how Web services can be consumed in an Android application.
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: Developing Android Services shows you 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.
xvi

CuuDuongThanCong.com



CuuDuongThanCong.com


CuuDuongThanCong.com


CuuDuongThanCong.com


introduction

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 for many common questions specific to P2P
and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

xx

CuuDuongThanCong.com


CuuDuongThanCong.com


2 


❘  Chapter 1   Getting Started with Android Programming

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 first release. Table 1-1 shows the various versions of Android and their codenames.
Table 1-1:  A Brief History of Android Versions
Android Version

Release Date

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

Unconfirmed at the time of writing

Honeycomb

CuuDuongThanCong.com

Codename


CuuDuongThanCong.com


4 

❘  Chapter 1   Getting Started with Android Programming

The Android OS is roughly divided into five sections in four main layers:


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.



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 the 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.



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.

Android Devices in the Market
Android devices come in all shapes and sizes. As of late
November 2010, the Android OS can be seen powering
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 (clockwise) the Samsung Galaxy S,
the HTC Desire HD, and the LG Optimus One smartphones.
Another popular category of devices that manufacturers
are rushing out is the tablet. Tablet sizes typically start at
seven inches, measured diagonally. Figure 1-3 shows the
Samsung Galaxy Tab and the Dell Streak, which is a fiveinch phone tablet.

CuuDuongThanCong.com


Figure 1-2


What Is Android? 

❘  5

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 NOOKcolor, which is a color e-Book reader
running the Android OS.

Figure 1-3

Figure 1-4

In addition to these popular mobile devices, Android is also slowly finding its way into your living
room. People of Lava, a Swedish company, has developed an Android-based TV, call the Scandinavia
Android TV (see Figure 1-5).
Google has also ventured into a proprietary smart TV platform based on Android and co-developed
with companies such as Intel, Sony, and Logitech. Figure 1-6 shows Sony’s Google TV.

Figure 1-5

CuuDuongThanCong.com

Figure 1-6


CuuDuongThanCong.com



Obtaining the Required Tools 

❘  7

Eclipse
The first step towards developing any applications is obtaining the integrated development environment
(IDE). 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, etc.
For Android development, you should download the Eclipse IDE for Java EE
Developers (www.eclipse​.org/downloads/packages/eclipse-ide-java-eedevelopers/heliossr1). 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\. Figure 1-7 shows the content of the eclipse folder.

Android SDK
The next 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 />index.html.

Figure 1-7

Once the SDK is downloaded, unzip its content (the android-sdk-windows folder)
into the C:\Android\ folder, or whatever name you have given to the folder you just
created.

Android Development Tools (ADT)
The Android Development Tools (ADT) plug-in for Eclipse 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 (APK).



Create digital certificates for code-signing your APK.

To install the ADT, first launch Eclipse by double-clicking on the eclipse.exe file located in the
eclipse folder.

CuuDuongThanCong.com


8 


❘  Chapter 1   Getting Started with Android Programming

When Eclipse is first started, you will be prompted for a folder to use as your workspace. In Eclipse,
a workspace is a folder where you store all your projects. Take the default suggested and click OK.
Once Eclipse is up and running, select the Help ➪ Install New Software… menu item (see
Figure 1-8).
In the Install window that appears, type in the text box (see
Figure 1-9) and click Add….
After a while, you will see the Developer Tools item appear in the middle of the window (see Figure 1-10).
Expand it, and it will reveal its content: Android DDMS, Android Development Tools, and Android
Hierarchy Viewer. Check all of them and click Next.

Figure 1-8

Figure 1-9

CuuDuongThanCong.com


Obtaining the Required Tools 

Figure 1-10

When you see the installation details, as shown in Figure 1-11, click Next.

Figure 1-11

CuuDuongThanCong.com

❘  9



CuuDuongThanCong.com


Obtaining the Required Tools 

❘  11

Figure 1-14

In the Preferences window that appears, select Android. You will see an error message saying that
the SDK has not been set up (see Figure 1-15). Click OK to dismiss it.

Figure 1-15

Enter the location of the Android SDK folder. In this example, it would be C:\Android\​
android-sdk-windows. Click OK.

Creating Android Virtual Devices (AVDs)
The next step is to create AVD to be used for testing your Android applications. AVD stands for
Android Virtual Devices. An AVD is an emulator instance that enables you to model an actual device.

CuuDuongThanCong.com


×