1. Trang chủ
  2. » Công Nghệ Thông Tin

The busy coder’s guide to android development (2011, v 3 6, murphy m l )

731 1,2K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề The Busy Coder’s Guide to Android Development
Tác giả Mark L. Murphy
Trường học Unknown University or Institution
Chuyên ngành Android Development
Thể loại Guide
Năm xuất bản 2011
Thành phố United States
Định dạng
Số trang 731
Dung lượng 22,02 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Welcome to the Warescription!We hope you enjoy this ebook and its updates – subscribe to the Warescription newsletter on the Warescription site to learn when new editions of this book, o

Trang 1

011023 4 567

 !"#$%#&!'()

*  +,-

./0012345367 89:21;:5<=> ?@A

Trang 2

Download from Wow! eBook <www.wowebook.com>

The Busy Coder's Guide to Android

Development

by Mark L Murphy

Trang 3

Download from Wow! eBook <www.wowebook.com>

The Busy Coder's Guide to Android Development

by Mark L Murphy

Copyright © 2008-2011 CommonsWare, LLC All Rights Reserved.

Printed in the United States of America.

CommonsWare books may be purchased in printed (bulk) or digital form for educational or

business use For more information, contact direct@commonsware.com.

Printing History:

Mar 2011:Version 3.6 ISBN: 978-0-9816780-0-9

The CommonsWare name and logo, “Busy Coder's Guide”, and related trade dress are trademarks of CommonsWare, LLC.

All other trademarks referenced in this book are trademarks of their respective firms The publisher and author(s) assume no responsibility for errors or omissions or for damages resulting from the use of the information contained herein.

Trang 4

Download from Wow! eBook <www.wowebook.com>

Table of Contents

Welcome to the Warescription! .xxiii

Preface .xxv

Welcome to the Book! xxv

Warescription .xxv

Book Bug Bounty .xxvi

Source Code And Its License .xxvii

Creative Commons and the Four-to-Free (42F) Guarantee xxviii

Acknowledgments .xxix

The Big Picture .1

What Androids Are Made Of 3

Activities .3

Services .4

Content Providers .4

Intents 4

Stuff At Your Disposal 5

Storage .5

Network .5

Multimedia .5

GPS .5

iii

Trang 5

Download from Wow! eBook <www.wowebook.com>

Phone Services .6

The Big Picture Of This Book 6

How To Get Started .7

Step #1: Java 7

Install the JDK .7

Learn Java .8

Step #2: Install the Android SDK .9

Install the Base Tools 9

Install the SDKs and Add-Ons 9

Step #3: Install the ADT for Eclipse .13

Step #4: Install Apache Ant .15

Step #5: Set Up the Emulator 16

Step #6: Set Up the Device 23

Windows 24

OS X and Linux 25

Your First Android Project .27

Step #1: Create the New Project 27

Eclipse .27

Command Line 31

Step #2: Build, Install, and Run the Application in Your Emulator or Device .32

Eclipse .32

Command Line .33

Examining Your First Project 37

Project Structure 37

Root Contents 37

The Sweat Off Your Brow .38

iv

Trang 6

Download from Wow! eBook <www.wowebook.com>

And Now, The Rest of the Story .39

What You Get Out Of It 40

Inside Your Manifest 40

In The Beginning, There Was the Root, And It Was Good 41

An Application For Your Application 42

A Bit About Eclipse .45

What the ADT Gives You 45

Coping with Eclipse .46

How to Import a Non-Eclipse Project 46

How to Get To DDMS .51

How to Create an Emulator 53

How to Run a Project 54

How Not to Run Your Project .55

Alternative IDEs 55

More on the Tools .56

IDEs And This Book .57

Enhancing Your First Project 59

Supporting Multiple Screens .59

Specifying Versions .60

Rewriting Your First Project .65

The Activity 65

Dissecting the Activity 66

Building and Running the Activity .68

About the Remaining Examples 69

Using XML-Based Layouts .71

What Is an XML-Based Layout? 71

Why Use XML-Based Layouts? 72

v

Trang 7

Download from Wow! eBook <www.wowebook.com>

OK, So What Does It Look Like? 73

What's With the @ Signs? .74

And We Attach These to the Java How? .74

The Rest of the Story .75

Employing Basic Widgets 79

Assigning Labels .79

Button, Button, Who's Got the Button? 80

Fleeting Images .81

Fields of Green Or Other Colors .83

Just Another Box to Check 85

Turn the Radio Up .88

It's Quite a View .90

Padding 90

Other Useful Properties .90

Useful Methods 91

Colors 91

Working with Containers 93

Thinking Linearly 94

Concepts and Properties .94

Example .97

The Box Model .102

All Things Are Relative 104

Concepts and Properties .104

Example .107

Overlap 109

Tabula Rasa .111

Concepts and Properties .112

vi

Trang 8

Download from Wow! eBook <www.wowebook.com>

Example 114

Scrollwork 115

The Input Method Framework .119

Keyboards, Hard and Soft .119

Tailored To Your Needs 120

Tell Android Where It Can Go 124

Fitting In .127

Jane, Stop This Crazy Thing! .128

Using Selection Widgets 131

Adapting to the Circumstances .131

Using ArrayAdapter .132

Lists of Naughty and Nice 133

Selection Modes .135

Spin Control 137

Grid Your Lions (Or Something Like That ) 141

Fields: Now With 35% Less Typing! 145

Galleries, Give Or Take The Art 149

Getting Fancy With Lists .151

Getting To First Base .151

A Dynamic Presentation 154

Inflating Rows Ourselves 156

A Sidebar About Inflation .156

And Now, Back To Our Story .158

Better Stronger Faster 159

Using convertView 159

Using the Holder Pattern 161

Interactive Rows 164

vii

Trang 9

Download from Wow! eBook <www.wowebook.com>

Still More Widgets and Containers .171

Pick and Choose 171

Time Keeps Flowing Like a River 176

Seeking Resolution 178

Putting It On My Tab 179

The Pieces 180

Wiring It Together .181

Adding Them Up .184

Flipping Them Off .188

Getting In Somebody's Drawer .193

Other Good Stuff 197

Embedding the WebKit Browser 199

A Browser, Writ Small .199

Loading It Up 202

Navigating the Waters .203

Entertaining the Client .204

Settings, Preferences, and Options (Oh, My!) .206

Applying Menus .209

Flavors of Menu 209

Menus of Options 210

Menus in Context .212

Taking a Peek 213

Yet More Inflation 218

Menu XML Structure 219

Menu Options and XML .219

Inflating the Menu 221

In the Land of Menus and Honey 223

viii

Trang 10

Download from Wow! eBook <www.wowebook.com>

Showing Pop-Up Messages .225

Raising Toasts .225

Alert! Alert! .226

Checking Them Out .227

Handling Activity Lifecycle Events .231

Schroedinger's Activity .231

Life, Death, and Your Activity .232

onCreate() and onDestroy() .232

onStart(), onRestart(), and onStop() .233

onPause() and onResume() .234

The Grace of State .234

Handling Rotation 237

A Philosophy of Destruction 237

It's All The Same, Just Different .238

Picking and Viewing a Contact 240

Saving Your State .242

Now With More Savings! .245

DIY Rotation .247

But Google Does Not Recommend This .250

Forcing the Issue .251

Making Sense of it All 253

Dealing with Threads 255

The Main Application Thread .255

Making Progress with ProgressBars .257

Getting Through the Handlers 258

Messages .258

Runnables .262

ix

Trang 11

Download from Wow! eBook <www.wowebook.com>

Where, Oh Where Has My UI Thread Gone? .262

Asyncing Feeling 262

The Theory 263

AsyncTask, Generics, and Varargs 264

The Stages of AsyncTask .264

A Sample Task .265

Threads and Rotation 270

Manual Activity Association .271

Flow of Events .274

Why This Works 275

And Now, The Caveats 276

Creating Intent Filters .277

What's Your Intent? .278

Pieces of Intents .278

Intent Routing 279

Stating Your Intent(ions) 280

Narrow Receivers 282

The Pause Caveat 283

Launching Activities and Sub-Activities .285

Peers and Subs 286

Start 'Em Up 286

Make an Intent 286

Make the Call 287

Tabbed Browsing, Sort Of .291

Working with Resources .297

The Resource Lineup 297

String Theory .298

x

Trang 12

Download from Wow! eBook <www.wowebook.com>

Plain Strings .298

String Formats 299

Styled Text .300

Styled Text and Formats 300

Got the Picture? 304

XML: The Resource Way .306

Miscellaneous Values .309

Dimensions 309

Colors 310

Arrays 311

Different Strokes for Different Folks .312

RTL Languages: Going Both Ways 317

Defining and Using Styles 319

Styles: DIY DRY .319

Elements of Style .321

Where to Apply a Style .322

The Available Attributes 322

Inheriting a Style .323

The Possible Values 324

Themes: Would a Style By Any Other Name .325

Handling Multiple Screen Sizes .327

Taking the Default 328

Whole in One 329

Don't Think About Positions, Think About Rules 330

Consider Physical Dimensions 331

Avoid "Real" Pixels .331

Choose Scalable Drawables .332

xi

Trang 13

Download from Wow! eBook <www.wowebook.com>

Tailor Made, Just For You (And You, And You, And ) 332

<supports-screens> 333

Resources and Resource Sets 334

Finding Your Size .335

Ain't Nothing Like the Real Thing .336

Density Differs 336

Adjusting the Density .337

Ruthlessly Exploiting the Situation 338

Replace Menus with Buttons 339

Replace Tabs with a Simple Activity 339

Consolidate Multiple Activities .340

Example: EU4You 340

The First Cut 341

Fixing the Fonts 347

Fixing the Icons .350

Using the Space .350

What If It Is Not a Browser? .353

Introducing the Honeycomb UI .357

Why Honeycomb? .357

What the User Sees .358

The Holographic Theme .363

Dealing with the Rest of the Devices 364

Using the Action Bar 367

Enabling the Action Bar 367

Promoting Menu Items to the Action Bar 368

Responding to the Logo 369

Adding Custom Views to the Action Bar 370

xii

Trang 14

Download from Wow! eBook <www.wowebook.com>

Defining the Layout .370

Putting the Layout in the "Menu" 372

Getting Control of User Input .373

Don't Forget the Phones! .375

Fragments .377

Introducing Fragments 377

The Problem .378

The Fragments Solution .378

The Android Compatibility Library 380

Creating Fragment Classes .381

General Fragments 381

ListFragment 383

Other Fragment Base Classes 388

Fragments, Layouts, Activities, and Multiple Screen Sizes 389

EU4You .390

DetailsActivity .395

Fragments and Configuration Changes 396

Designing for Fragments 397

Handling Platform Changes .399

Things That Make You Go "Boom" .399

View Hierarchy .400

Changing Resources .400

Handling API Changes .401

Minimum, Maximum, Target, and Build Versions .401

Detecting the Version .404

Wrapping the API 404

Patterns for Honeycomb 407

xiii

Trang 15

Download from Wow! eBook <www.wowebook.com>

The Action Bar .407

Writing Tablet-Only Apps .409

Accessing Files 413

You And The Horse You Rode In On .413

Readin' 'n Writin' .417

External Storage: Giant Economy-Size Space .421

Where to Write .422

When to Write .422

StrictMode: Avoiding Janky Code .423

Setting up Strict Mode 424

Seeing It In Action .424

Development Only, Please! .425

Conditionally Being Strict .425

Linux Filesystems: You Sync, You Win 428

Using Preferences .431

Getting What You Want 431

Stating Your Preference .432

Introducing PreferenceActivity .433

Letting Users Have Their Say .434

Adding a Wee Bit O' Structure 439

The Kind Of Pop-Ups You Like 442

Preferences via Fragments 446

The Honeycomb Way 447

Adding Backwards Compatibility .452

Managing and Accessing Local Databases .455

A Quick SQLite Primer .457

Start at the Beginning .457

xiv

Trang 16

Download from Wow! eBook <www.wowebook.com>

Setting the Table .461

Makin' Data 462

What Goes Around, Comes Around .463

Raw Queries .463

Regular Queries .464

Using Cursors .465

Custom CursorAdapters 466

Making Your Own Cursors .467

Flash: Sounds Faster Than It Is .467

Data, Data, Everywhere .468

Leveraging Java Libraries 471

Ants and Jars 471

The Outer Limits .472

Following the Script .473

Reviewing the Script .478

Communicating via the Internet 481

REST and Relaxation .481

HTTP Operations via Apache HttpClient 482

Parsing Responses 484

Stuff To Consider 486

AndroidHttpClient .487

Leveraging Internet-Aware Android Components 488

Downloading Files .488

Continuing Our Escape From Janky Code .500

Services: The Theory 503

Why Services? .503

Setting Up a Service .504

xv

Trang 17

Download from Wow! eBook <www.wowebook.com>

The Service Class 504

Lifecycle Methods .505

Manifest Entry .505

Communicating To Services 506

Sending Commands with startService() .506

Binding with bindService() .508

Communicating From Services .509

Callback/Listener Objects 509

Broadcast Intents .510

Pending Results .511

Messenger 511

Notifications .512

Basic Service Patterns .513

The Downloader .513

The Design 514

The Service Implementation 514

Using the Service 517

The Music Player 518

The Design .519

The Service Implementation 519

Using the Service 521

The Web Service Interface .522

The Design .523

The Rotation Challenge .523

The Service Implementation 524

Using the Service 529

xvi

Trang 18

Download from Wow! eBook <www.wowebook.com>

Alerting Users Via Notifications 537

Notification Configuration 537

Hardware Notifications .538

Icons .539

Notifications in Action 540

Staying in the Foreground .545

FakePlayer, Redux 546

Notifications and Honeycomb .548

Requesting and Requiring Permissions 553

Mother, May I? 554

Halt! Who Goes There? .555

Enforcing Permissions via the Manifest 556

Enforcing Permissions Elsewhere .557

May I See Your Documents? 557

New Permissions in Old Applications .558

Permissions: Up Front Or Not At All 558

Accessing Location-Based Services .563

Location Providers: They Know Where You're Hiding .564

Finding Yourself .564

On the Move .566

Are We There Yet? Are We There Yet? Are We There Yet? .568

Testing Testing .569

Mapping with MapView and MapActivity .571

Terms, Not of Endearment .571

Piling On 572

The Key To It All 572

The Bare Bones .574

xvii

Trang 19

Download from Wow! eBook <www.wowebook.com>

Optional Maps 576

Exercising Your Control 576

Zoom 577

Center 577

Layers Upon Layers .578

Overlay Classes 578

Drawing the ItemizedOverlay 578

Handling Screen Taps 580

My, Myself, and MyLocationOverlay 581

Rugged Terrain .582

Maps and Fragments 584

Limit Yourself to Android 3.0 .584

Use onCreateView() and onActivityCreated() 585

Host the Fragment in a MapActivity 586

Handling Telephone Calls .589

Report To The Manager 590

You Make the Call! .590

No, Really, You Make the Call! .593

Fonts 595

Love The One You're With .595

Here a Glyph, There a Glyph 599

More Development Tools 601

Hierarchy Viewer: How Deep Is Your Code? 601

DDMS: Under Android's Hood 606

Logging .608

File Push and Pull .609

Screenshots .610

xviii

Trang 20

Download from Wow! eBook <www.wowebook.com>

Location Updates 611

Placing Calls and Messages 612

Memory Management 616

adb: Like DDMS, With More Typing 617

The Role of Alternative Environments .621

In the Beginning, There Was Java 622

And It Was OK .622

Bucking the Trend .623

Support, Structure 624

Caveat Developer .624

HTML5 627

Offline Applications .627

What Does It Mean? .627

How Do You Use It? .628

Web Storage 634

What Does It Mean? .635

How Do You Use It? .636

Web SQL Database .637

Going To Production 638

Testing .638

Signing and Distribution 638

Updates 639

Issues You May Encounter .639

Android Device Versions 639

Screen Sizes and Densities 640

Limited Platform Integration .640

Performance and Battery .641

xix

Trang 21

Download from Wow! eBook <www.wowebook.com>

Look and Feel .642

Distribution .642

HTML5 and Alternative Android Browsers 643

Firefox Mobile .643

Opera Mobile .643

Dolphin Browser HD 4.0 .643

HTML5: The Baseline 643

PhoneGap .645

What Is PhoneGap? 645

What Do You Write In? 645

What Features Do You Get? .646

What Do Apps Look Like? .647

How Does Distribution Work? 647

What About Other Platforms? .648

Using PhoneGap 648

Installation .649

Creating and Installing Your Project 649

PhoneGap/Build 650

PhoneGap and the Checklist Sample 654

Sticking to the Standards .654

Adding PhoneGap APIs .657

Issues You May Encounter .660

Security 660

Screen Sizes and Densities 661

Look and Feel .662

For More Information .663

xx

Trang 22

Download from Wow! eBook <www.wowebook.com>

Other Alternative Environments 665

Rhodes 665

Flash, Flex, and AIR .666

JRuby and Ruboto .666

MonoDroid .667

App Inventor 667

Titanium Mobile .669

Other JVM Compiled Languages .670

Dealing With Devices .673

This App Contains Explicit Instructions 673

Implied Feature Requests 675

A Guaranteed Market 676

Other Stuff That Varies 677

Bugs, Bugs, Bugs 678

Device Testing .678

Where Do We Go From Here? .681

Questions Sometimes, With Answers 681

Heading to the Source .682

Getting Your News Fix .683

xxi

Trang 23

Download from Wow! eBook <www.wowebook.com>

Trang 24

Welcome to the Warescription!

We hope you enjoy this ebook and its updates – subscribe to the Warescription newsletter on the Warescription site to learn when new editions of this book, or other books, are available

All editions of CommonsWare titles, print and ebook, follow a style numbering system Major releases (1.0, 2.0, etc.) are available in both print and ebook; minor releases (0.1, 0.9, etc.) are available in ebook form for Warescription subscribers only Releases ending in .9 are "release candidates" for the next major release, lacking perhaps an index but otherwise being complete

software-Each Warescription ebook is licensed for the exclusive use of its subscriber and is tagged with the subscriber's name We ask that you not distribute these books If you work for a firm and wish to have several employees have access, enterprise Warescriptions are available Just contact us at

You can search through the PDF using most PDF readers (e.g., Adobe Reader) If you wish to search all of the CommonsWare books at once, and

xxiii

Trang 25

Download from Wow! eBook <www.wowebook.com>

your operating system does not support that directly, you can always combine the PDFs into one, using tools like PDF Split-And-Merge or the Linux command pdftk *.pdf cat output combined.pdf

xxiv

Trang 26

Download from Wow! eBook <www.wowebook.com>

And, most of all, thanks for your interest in this book! I sincerely hope you find it useful and at least occasionally entertaining

Warescription

This book will be published both in print and in digital (ebook) form The ebook versions of all CommonsWare titles are available via an annual subscription – the Warescription

The Warescription entitles you, for the duration of your subscription, to

ebook forms of all CommonsWare titles, not just the one you are reading

xxv

Trang 27

Download from Wow! eBook <www.wowebook.com>

Presently, CommonsWare offers PDF and Kindle; other ebook formats will

be added based on interest and the openness of the format

Each subscriber gets personalized editions of all editions of each title: both those mirroring printed editions and in-between updates that are only available in ebook form That way, your ebooks are never out of date for long, and you can take advantage of new material as it is made available instead of having to wait for a whole new print edition For example, when new releases of the Android SDK are made available, this book will be quickly updated to be accurate with changes in the APIs

From time to time, subscribers will also receive access to subscriber-only online material, both short articles and not-yet-published new titles

Also, if you own a print copy of a CommonsWare book, and it is in good clean condition with no marks or stickers, you can exchange that copy for a discount off the Warescription price

If you are interested in a Warescription, visit the Warescription section of the CommonsWare Web site

You can find out when new releases of this book are available via:

• The cw-android Google Group, which is also a great place to ask questions about the book and its examples

• The commonsguy Twitter feed

• The Warescription newsletter, which you can subscribe to off of your Warescription page

Book Bug Bounty

Find a problem in one of our books? Let us know!

Be the first to report a unique concrete problem in the current digital edition, and we'll give you a coupon for a six-month Warescription as a bounty for helping us deliver a better product You can use that coupon to get a new Warescription, renew an existing Warescription, or give the

xxvi

Trang 28

Download from Wow! eBook <www.wowebook.com>

coupon to a friend, colleague, or some random person you meet on the subway

By "concrete" problem, we mean things like:

• Typographical errors

• Sample applications that do not work as advertised, in the environment described in the book

• Factual errors that cannot be open to interpretation

By "unique", we mean ones not yet reported Each book has an errata page

on the CommonsWare Web site; most known problems will be listed there One coupon is given per email containing valid bug reports

We appreciate hearing about "softer" issues as well, such as:

• Places where you think we are in error, but where we feel our interpretation is reasonable

• Places where you think we could add sample applications, or expand upon the existing material

• Samples that do not work due to "shifting sands" of the underlying environment (e.g., changed APIs with new releases of an SDK)

However, those "softer" issues do not qualify for the formal bounty program

Be sure to check the book's errata page, though, to see if your issue has already been reported

Questions about the bug bounty, or problems you wish to report for bounty consideration, should be sent to bounty@commonsware.com

Source Code And Its License

The source code samples shown in this book are available for download from the book's GitHub repository All of the Android projects are licensed under the Apache 2.0 License, in case you have the desire to reuse any of it

xxvii

Trang 29

Download from Wow! eBook <www.wowebook.com>

If you wish to use the source code from the CommonsWare Web site, bear

in mind a few things:

1 The projects are set up to be built by Ant, not by Eclipse If you wish

to use the code with Eclipse, you will need to create a suitable Android Eclipse project and import the code and other assets

2 You should delete build.xml, then run android update project -p . (where is the path to a project of interest) on those projects you wish to use, so the build files are updated for your Android SDK version

Creative Commons and the Four-to-Free

(42F) Guarantee

Each CommonsWare book edition will be available for use under the

Creative Commons Attribution-Noncommercial-ShareAlike 3.0 license as of the fourth anniversary of its publication date, or when 4,000 copies of the edition have been sold, whichever comes first That means that, once four years have elapsed (perhaps sooner!), you can use this prose for non-commercial purposes That is our Four-to-Free Guarantee to our readers and the broader community For the purposes of this guarantee, new Warescriptions and renewals will be counted as sales of this edition, starting from the time the edition is published

This edition of this book will be available under the aforementioned

Creative Commons license on 1 March 2015 Of course, watch the

CommonsWare Web site, as this edition might be relicensed sooner based

does not automatically release all editions under that license.

xxviii

Trang 30

Download from Wow! eBook <www.wowebook.com>

Trang 31

Download from Wow! eBook <www.wowebook.com>

Trang 32

PART I – Core Concepts

Trang 33

Download from Wow! eBook <www.wowebook.com>

Trang 34

CHAPTER 1

The Big Picture

Android is everywhere Phones Tablets TVs and set-top boxes powered by Google TV Soon, Android will be in cars and all sort of other places as well

However, the general theme of Android devices will be smaller screens and/or no hardware keyboard And, by the numbers, Android will probably

be most associated with smartphones for the foreseeable future

For developers, this has benefits and drawbacks

On the plus side, Android-style smartphones are sexy Offering Internet services over mobile devices dates back to the mid-1990's and the Handheld Device Markup Language (HDML) However, only in recent years have phones capable of Internet access taken off Now, thanks to trends like text messaging and to products like Apple's iPhone, phones that can serve as Internet access devices are rapidly gaining popularity So, working on Android applications gives you experience with an interesting technology (Android) in a fast-moving market segment (Internet-enabled phones), which is always a good thing

The problem comes when you actually have to program the darn things

Anyone with experience in programming for PDAs or phones has felt the

pain of phones simply being small in all sorts of dimensions:

1

Trang 35

Download from Wow! eBook <www.wowebook.com>

The Big Picture

• Screens are small (you will not get comments like, "is that a 24-inch LCD in your pocket, or ?")

• Keyboards, if they exist, are small

• Pointing devices, if they exist, are annoying (as anyone who has lost their stylus will tell you) or inexact (large fingers and "multi-touch" LCDs can sometimes be problematic)

• CPU speed and memory are tight compared to desktops and servers you may be used to

• by tying up the CPU such that calls can't be received

• by not working properly with the rest of the phone's OS, such that your application does not quietly fade to the background when a call comes in or needs to be placed

• by crashing the phone's operating system, such as by leaking memory like a sieve

Hence, developing programs for a phone is a different experience than developing desktop applications, Web sites, or back-end server processes You wind up with different-looking tools, different-behaving frameworks, and "different than you are used to" limitations on what you can do with your program

What Android tries to do is meet you halfway:

• You get a commonly-used programming language (Java) with some commonly used libraries (e.g., some Apache Commons APIs), with support for tools you may be used to (Eclipse)

2

Trang 36

Download from Wow! eBook <www.wowebook.com>

The Big Picture

• You get a fairly rigid and uncommon framework in which your programs need to run so they can be "good citizens" on the phone and not interfere with other programs or the operation of the phone itself

As you might expect, much of this book deals with that framework and how you write programs that work within its confines and take advantage of its capabilities

What Androids Are Made Of

When you write a desktop application, you are "master of your own domain" You launch your main window and any child windows – like dialog boxes – that are needed From your standpoint, you are your own world, leveraging features supported by the operating system, but largely ignorant of any other program that may be running on the computer at the same time If you do interact with other programs, it is typically through an API, such as using JDBC (or frameworks atop it) to communicate with MySQL or another database

Android has similar concepts, but packaged differently, and structured to make phones more crash-resistant

Activities

The building block of the user interface is the activity You can think of an

activity as being the Android analogue for the window or dialog in a desktop application, or the page in a classic Web app Android is designed

to support lots of cheap activities, so you can allow users to keep clicking to bring up new activities and tapping the BACK button to back up, just like they do in a Web browser

3

Trang 37

Download from Wow! eBook <www.wowebook.com>

The Big Picture

Services

Activities are short-lived and can be shut down at any time Services, on the other hand, are designed to keep running, if needed, independent of any activity You might use a service for checking for updates to an RSS feed, or

to play back music even if the controlling activity is no longer operating You will also use services for scheduled tasks ("cron jobs") and for exposing custom APIs to other applications on the device, though those are relatively advanced capabilities

Content Providers

Content providers provide a level of abstraction for any data stored on the device that is accessible by multiple applications The Android development model encourages you to make your own data available to other applications, as well as your own – building a content provider lets you do that, while maintaining complete control over how your data gets accessed

Intents

Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e.g.,

an SD card was inserted), to incoming data (e.g., an SMS message arrived),

to application events (e.g., your activity was launched from the device's main menu) Not only can you respond to an Intent, but you can create your own, to launch other activities, or to let you know when specific situations arise (e.g., raise such-and-so Intent when the user gets within 100 meters of this-and-such location)

4

Trang 38

Download from Wow! eBook <www.wowebook.com>

The Big PictureStuff At Your Disposal

Storage

You can package data files with your application, for things that do not change, such as icons or help files You also can carve out a small bit of space on the device itself, for databases or files containing user-entered or retrieved data needed by your application And, if the user supplies bulk storage, like an SD card, you can read and write files on there as needed

Network

Android devices will generally be Internet-ready, through one communications medium or another You can take advantage of the Internet access at any level you wish, from raw Java sockets all the way up

to a built-in WebKit-based Web browser widget you can embed in your application

Multimedia

Android devices have the ability to play back and record audio and video While the specifics may vary from device to device, you can query the device to learn its capabilities and then take advantage of the multimedia capabilities as you see fit, whether that is to play back music, take pictures with the camera, or use the microphone for audio note-taking

GPS

Android devices will frequently have access to location providers, such as GPS, that can tell your applications where the device is on the face of the Earth In turn, you can display maps or otherwise take advantage of the location data, such as tracking a device's movements if the device has been stolen

5

Trang 39

Download from Wow! eBook <www.wowebook.com>

The Big Picture

Phone Services

And, of course, Android devices are typically phones, allowing your software to initiate calls, send and receive SMS messages, and everything else you expect from a modern bit of telephony technology

The Big Picture Of This Book

Here is what's coming in the rest of this book:

The next two chapters are designed to get you going quickly with the Android environment, through a series of step-by-step, tutorial-style instructions for setting up the tools you need, creating your first project, and getting that first project running on the Android emulator

The three chapters that follow try to explain a bit more about what just happened in those first two chapters We examine the Android project that

we created, talk a bit more about Eclipse, and discuss some things we could

add to the project to help it run on more devices and such

The bulk of the book is exploring various capabilities of the Android APIs – how to create components like activities, how to access the Internet and local databases, how to get your location and show it on a map, and so forth

6

Trang 40

Download from Wow! eBook <www.wowebook.com>

CHAPTER 2

How To Get Started

Without further ado, let us get you set up with the pieces and parts necessary to build an Android app

NOTE: the instructions presented here are accurate as of the time of this

writing However, the tools change rapidly, and so these instructions may

be out of date by the time you read this Please refer to the Android Developers Web site for current instructions, using this as a base guideline

of what to expect

Step #1: Java

When you write Android applications, you typically write them in Java source code That Java source code is then turned into the stuff that Android actually runs (Dalvik bytecode in an APK file)

Hence, the first thing you need to do is get set up with a Java development environment and be ready to start writing Java classes

Install the JDK

You need to obtain and install the official Sun/Oracle Java SE SDK (JDK) You can obtain this from the Oracle Java Web site for Windows and Linux, and presumably from Apple for OS X The plain JDK (sans any "bundles")

7

...

by Mark L Murphy< /small>

Copyright © 2008-2011 CommonsWare, LLC All Rights Reserved.

Printed in the United States of America.

CommonsWare... 3< /span>

Download from Wow! eBook <www.wowebook.com>

The Busy Coder''s Guide to Android Development< /small>

by... are small (you will not get comments like, & #34 ;is that a 24-inch LCD in your pocket, or ?& #34 ;)

• Keyboards, if they exist, are small

• Pointing devices,

Ngày đăng: 24/04/2014, 11:14

TỪ KHÓA LIÊN QUAN