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

The busy coder’s guide to android development (2012, v 4 2, murphy m l )

1,8K 359 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
Năm xuất bản 2012
Định dạng
Số trang 1.793
Dung lượng 20,83 MB

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

Nội dung

To make the equivalent of 2,000+ pages of material manageable, the chapters are divided into the core chapters and a series of trails.. The core chapters represent many key concepts that

Trang 2

The Busy Coder's Guide to Android Development

by Mark L Murphy

Trang 3

by Mark L Murphy

Trang 4

Table of Contents

Headings formatted in bold-italic have changed since the last version.

• Preface

◦ Welcome to the Book! xxv

◦ The Book’s Structure xxv

The Trails xxvi

◦ Warescription xxx

◦ Getting Help xxxi

◦ Book Bug Bounty xxxi

◦ Source Code And Its License xxxii

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

◦ Acknowledgments xxxiii

• KeyAndroidConcepts ◦ Android Applications 1

◦ Android Devices 7

◦ Don’t Be Scared 10

• ChoosingYourIDE ◦ Eclipse 11

◦ Alternative IDEs 12

◦ IDEs… And This Book 13

◦ About App Inventor 13

• Tutorial#1-InstallingtheTools ◦ Step #1 - Checking Your Hardware Requirements 15

◦ Step #2 - Setting Up Java 16

◦ Step #3 - Install the Android SDK 16

◦ Step #4 - Install the ADT for Eclipse 18

◦ Step #5 - Install Apache Ant 20

◦ Step #6 - Set Up the Emulator 21

◦ Step #7 - Set Up the Device 28

◦ In Our Next Episode… 31

• Tutorial#2-CreatingaStubProject ◦ About Our Tutorial Project 33

◦ About the Rest of the Tutorials 34

◦ About the Eclipse Instructions 34

◦ Step #1: Creating the Project 35

◦ Step #2: Running the Project 40

Trang 5

• ContentsofAndroidProjects

Root Contents 45

◦ The Sweat Off Your Brow 46

◦ Resources 46

What You Get Out Of It 47

• InsidetheManifest ◦ An Application For Your Application 51

◦ Specifying Versions 51

◦ Supporting Multiple Screens 52

◦ Other Stuff 53

• Tutorial#3-ChangingOurManifest ◦ Step #1: Supporting Screens 55

Step #2: Validating our Minimum SDK Version 59

◦ In Our Next Episode… 60

• SomeWordsAboutResources ◦ String Theory 61

Got the Picture? 64

◦ Dimensions 66

◦ The Resource That Shall Not Be Named… Yet 67

• Tutorial#4-AdjustingOurResources ◦ Step #1: Changing the Name 69

◦ Step #2: Changing the Icon 72

◦ In Our Next Episode… 80

• TheTheoryofWidgets ◦ What Are Widgets? 81

◦ Size, Margins, and Padding 83

◦ What Are Containers? 83

◦ The Absolute Positioning Anti-Pattern 84

• TheAndroidUserInterface ◦ The Activity 87

◦ Dissecting the Activity 88

◦ Using XML-Based Layouts 89

• BasicWidgets ◦ Common Concepts 95

◦ Assigning Labels 97

◦ A Commanding Button 102

Fleeting Images 106

◦ Fields of Green Or Other Colors 111

◦ More Common Concepts 114

◦ Visit the Trails! 116

Trang 6

◦ Adapting to the Circumstances 165

◦ Lists of Naughty and Nice 167

◦ Clicks versus Selections 169

◦ Spin Control 173

◦ Grid Your Lions (Or Something Like That…) 176

◦ Fields: Now With 35% Less Typing! 180

◦ Galleries, Give Or Take The Art 185

◦ Customizing the Adapter 186

◦ Visit the Trails! 194

• TheWebViewWidget ◦ Role of WebView 195

◦ Get Thee To a Stack Trace 120

◦ The Case of the Confounding Class Cast 123

◦ Point Break 123

• LinearLayoutandtheBoxModel ◦ Concepts and Properties 125

◦ Eclipse Graphical Layout Editor 129

• OtherCommonWidgetsandContainers ◦ Just a Box to Check 131

◦ Don’t Like Checkboxes? How About Toggles? 134

◦ Turn the Radio Up 136

◦ All Things Are Relative 138

◦ Tabula Rasa 145

◦ Scrollwork 149

◦ Making Progress with ProgressBars 152

◦ Visit the Trails! 153

• Tutorial#5-MakingProgress ◦ Step #1: Removing The “Hello, World” 155

◦ Step #2: Adding a ProgressBar 157

◦ Step #3: Seeing the Results 159

◦ In Our Next Episode… 160

• GUIBuilding,Continued ◦ Making Your Selection 161

◦ Including Includes 161

◦ Wrap It Up (In a Container) 163

◦ Morphing Widgets 163

◦ Preview of Coming Attractions 164

• AdapterViewsandAdapters

Trang 7

◦ Supporting JavaScript 199

◦ Alternatives for Loading Content 200

◦ Listening for Events 201

◦ Visit the Trails! 205

• DefiningandUsingStyles ◦ Styles: DIY DRY 207

◦ Elements of Style 209

◦ Themes: Would a Style By Any Other Name… 212

• JARsandLibraryProjects ◦ The Dalvik VM 214

◦ The Easy Part 214

◦ The Outer Limits 215

◦ OK, So What is a Library Project? 216

◦ Creating a Library Project 216

◦ Using a Library Project 217

◦ Limitations of Library Projects 218

◦ The Android Support Package 218

◦ JAR Dependency Management 221

• Tutorial#6-AddingaLibrary ◦ Step #1: Downloading and Unpacking ActionBarSherlock 223

◦ Step #2: Adding the Library to Your Project 224

◦ In Our Next Episode… 227

• OptionsMenusandtheActionBar ◦ Terminology 229

◦ A Wee Spot O’ History 231

◦ Your Action Bar Options 232

◦ Setting the Target 235

◦ Minding Narrow 236

Defining the Resource 236

◦ Applying the Resource 241

◦ Responding to Events 241

Attaching to Action Layouts 242

◦ The Rest of the Sample Activity 242

◦ Visit the Trails! 250

• Tutorial#7-AddingtheActionBar ◦ Step #1: Setting Up the Target SDK Version 251

◦ Step #2: Setting the Theme and Splitting the Bar 253

◦ Step #3: Changing to SherlockFragmentActivity 255

◦ Step #4: Defining Some Options 256

◦ Step #5: Loading and Responding to Our Options 259

Trang 8

• Android’sProcessModel

◦ When Processes Are Created 263

◦ BACK, HOME, and Your Process 264

◦ Termination 265

◦ Foreground Means “I Love You” 265

◦ You and Your Heap 266

• ActivitiesandTheirLifecycles ◦ Creating Your Second (and Third and…) Activity 268

◦ Warning! Contains Explicit Intents! 273

◦ Using Implicit Intents 275

◦ Extra! Extra! 280

◦ Asynchronicity and Results 282

Schroedinger’s Activity 282

◦ Life, Death, and Your Activity 283

◦ When Activities Die 285

◦ Walking Through the Lifecycle 286

◦ Recycling Activities 289

• Tutorial#8-SettingUpAnActivity ◦ Step #1: Creating the Stub Activity Class 291

◦ Step #2: Adding the Activity to the Manifest 293

◦ Step #3: Launching Our Activity 295

◦ In Our Next Episode… 296

• TheTacticsofFragments ◦ The Six Questions 297

◦ Your First Fragment 299

◦ The Fragment Lifecycle Methods 304

◦ Your First Dynamic Fragment 305

◦ Fragments and the Action Bar 309

◦ Fragments Within Fragments: Just Say No 310

◦ Fragments and Multiple Activities 310

• Tutorial#9-StartingOurFragments ◦ Step #1: Copy In WebViewFragment 313

◦ Step #2: Examining WebViewFragment 317

◦ Step #3: Creating AbstractContentFragment 317

◦ Step #4: Examining AbstractContentFragment 319

◦ In Our Next Episode… 319

• SwipingwithViewPager ◦ Swiping Design Patterns 321

Trang 9

◦ Fragment-Free Paging 331

• Tutorial#10-RiggingUpaViewPager ◦ Step #1: Add a ViewPager to the Layout 333

◦ Step #2: Obtaining Our ViewPager 334

◦ Step #3: Creating a ContentsAdapter 335

◦ Step #4: Setting Up the ViewPager 336

◦ In Our Next Episode… 337

• ResourceSetsandConfigurations ◦ What’s a Configuration? And How Do They Change? 339

◦ Configurations and Resource Sets 340

◦ Coping with Complexity 341

◦ Default Change Behavior 343

Your Options for Configuration Changes 345

◦ Blocking Rotations 357

• DealingwithThreads ◦ The Main Application Thread 359

◦ Getting to the Background 360

◦ Asyncing Feeling 361

◦ Alternatives to AsyncTask 369

◦ And Now, The Caveats 370

• RequestingPermissions ◦ Mother, May I? 372

◦ New Permissions in Old Applications 373

◦ Permissions: Up Front Or Not At All 374

◦ Signature Permissions 375

◦ Requiring Permissions 375

• Assets,Files,andDataParsing ◦ Packaging Files with Your App 377

◦ Files and Android 379

◦ Working with Internal Storage 380

◦ Working with External Storage 382

◦ Linux Filesystems: You Sync, You Win 386

◦ StrictMode: Avoiding Janky Code 387

◦ XML Parsing Options 394

◦ JSON Parsing Options 395

• Tutorial#11-AddingSimpleContent ◦ Step #1: Adding Some Content 397

◦ Step #2: Create a SimpleContentFragment 398

◦ Step #3: Examining SimpleContentFragment 399

◦ Step #4: Using SimpleContentFragment 399

Trang 10

◦ In Our Next Episode… 403

• Tutorial#12-DisplayingtheBook ◦ Step #1: Adding a Book 405

◦ Step #2: Defining Our Model 406

◦ Step #3: Examining Our Model 408

◦ Step #4: Creating a ModelFragment 408

◦ Step #5: Examining the ModelFragment 411

◦ Step #6: Supplying the Content 412

◦ Step #7: Adapting the Content 413

◦ Step #8: Going Home, Again 415

◦ In Our Next Episode… 416

• UsingPreferences ◦ Getting What You Want 417

◦ Stating Your Preference 418

◦ Introducing PreferenceActivity 419

◦ Types of Preferences 431

◦ Intents for Headers or Preferences 434

• Tutorial#13-UsingSomePreferences ◦ Step #1: Adding a StockPreferenceFragment 438

◦ Step #2: Defining the Preference XML Files 439

◦ Step #3: Creating Our PreferenceActivity 441

◦ Step #4: Adding To Our Action Bar 442

◦ Step #5: Launching the PreferenceActivity 444

◦ Step #6: Loading Our Preferences 447

◦ Step #7: Saving the Last-Read Position 449

◦ Step #8: Restoring the Last-Read Position 450

◦ Step #9: Keeping the Screen On 450

◦ In Our Next Episode… 451

• SQLiteDatabases ◦ Introducting SQLite 453

◦ Thinking About Schemas 454

◦ Start with a Helper 454

◦ Getting Data Out 460

◦ The Rest of the CRUD 465

◦ Hey, What About Hibernate? 470

◦ Visit the Trails! 470

• Tutorial#14-SavingNotes ◦ Step #1: Adding a DatabaseHelper 471

Trang 11

◦ Step #5: Creating the NoteActivity 476

◦ Step #6: Loading and Saving Notes 477

◦ Step #7: Add Notes to the Action Bar 481

◦ Step #8: Support Deleting Notes 483

◦ In Our Next Episode… 491

• InternetAccess ◦ DIY HTTP 493

◦ HTTP via DownloadManager 504

◦ Using Third-Party JARs 505

• Intents,IntentFilters,Broadcasts,andBroadcastReceivers ◦ What’s Your Intent? 507

◦ Stating Your Intent(ions) 509

◦ Responding to Implicit Intents 510

◦ Requesting Implicit Intents 512

◦ Broadcasts and Receivers 516

◦ Example System Broadcasts 518

◦ Downloading Files 525

◦ Keeping It Local 537

• Tutorial#15-SharingYourNotes ◦ Step #1: Adding a Share Action Bar Item 541

◦ Step #2: Sharing the Note 542

◦ Step #3: Tying Them Together 543

◦ Step #4: Testing the Result 543

◦ In Our Next Episode… 545

• ServicesandtheCommandPattern ◦ Why Services? 547

◦ Setting Up a Service 548

◦ Communicating To Services 550

Scenario: The Music Player 552

◦ Communicating From Services 555

Scenario: The Downloader 557

• Tutorial#16-UpdatingtheBook ◦ Step #1: Adding a Stub DownloadCheckService 564

◦ Step #2: Tying the Service Into the Action Bar 565

◦ Step #3: Adding a Stub DownloadCompleteReceiver 566

◦ Step #4: Completing the DownloadCheckService 567

◦ Step #5: Adding a Stub DownloadInstallService 571

◦ Step #6: Completing the DownloadCompleteReceiver 572

◦ Step #7: Completing the DownloadInstallService 572

◦ Step #8: Updating ModelFragment 575

Trang 12

◦ Step #10: Discussing the Flaws 582

◦ In Our Next Episode… 582

• AlarmManagerandtheScheduledServicePattern ◦ Scenarios 583

◦ Options 584

A Simple Example 586

◦ The Four Types of Alarms 588

When to Schedule Alarms 589

Get Moving, First Thing 590

◦ Archetype: Scheduled Service Polling 593

◦ Staying Awake at Work 597

• Tutorial#17-PeriodicBookUpdates ◦ Step #1: Adding a Stub UpdateReceiver 601

◦ Step #2: Scheduling the Alarms 603

◦ Step #3: Adding the WakefulIntentService 604

Step #4: Using WakefulIntentService 604

◦ Step #5: Completing the UpdateReceiver 605

◦ In Our Next Episode… 606

• Notifications ◦ What’s a Notification? 607

Showing a Simple Notification 610

◦ Notifications and Foreground Services 615

◦ Seeking Some Order 616

Big (and Rich) Notifications 622

◦ Disabled Notifications 629

• Tutorial#18-NotifyingtheUser ◦ Step #1: Adding the InstallReceiver 631

◦ Step #2: Completing the InstallReceiver 633

◦ In Our Next Episode… 634

• Large-ScreenStrategiesandTactics ◦ Objective: Maximum Gain, Minimum Pain 635

◦ The Fragment Strategy 635

Fragment Example: The List-and-Detail Pattern 644

Showing More Pages 655

◦ Fragment FAQs 659

◦ Screen Size and Density Tactics 661

◦ Other Considerations 664

• Tutorial#19-SupportingLargeScreens

Trang 13

◦ Step #4: Loading Content Into the Sidebar 672

◦ Step #5: Removing Content From the Sidebar 675

• BackwardsCompatibilityStrategiesandTactics ◦ Think Forwards, Not Backwards 677

◦ Aim Where You Are Going 679

◦ A Target-Rich Environment 679

◦ A Little Help From Your Friends 681

◦ Avoid the New on the Old 681

◦ Testing 685

• GettingHelp ◦ Questions Sometimes, With Answers 687

◦ Heading to the Source 688

◦ Getting Your News Fix 689

• IntroducingGridLayout ◦ Prerequisites 691

◦ Issues with the Classic Containers 691

◦ The New Contender: GridLayout 693

◦ GridLayout and the Android Support Package 694

◦ Eclipse and GridLayout 695

◦ Trying to Have Some Rhythm 695

◦ Our Test App 696

◦ Replacing the Classics 698

◦ Implicit Rows and Columns 705

◦ Row and Column Spans 707

◦ Should You Use GridLayout? 710

• DialogsandDialogFragments ◦ Prerequisites 711

◦ DatePickerDialog and TimePickerDialog 711

◦ AlertDialog 718

◦ DialogFragments 719

◦ Dialogs: Modal, Not Blocking 723

• AdvancedListViews ◦ Prerequisites 725

◦ Multiple Row Types, and Self Inflation 725

◦ Choice Modes and the Activated Style 731

◦ Custom Mutable Row Contents 732

◦ From Head To Toe 738

• ActionBarNavigation ◦ Prerequisites 743

◦ List Navigation 743

Trang 14

◦ Prerequisites 818

◦ Terms, Not of Endearment 818

◦ Piling On 818

◦ The Key To It All 819

◦ The Bare Bones 820

◦ Custom Navigation 754

• ActionModesandContextMenus ◦ Prerequisites 758

◦ Another Wee Spot O’ History 758

◦ Manual Action Modes 759

◦ Multiple-Modal-Choice Action Modes 764

◦ Split Action Modes 768

◦ What Came Before: Context Menus 771

• AdvancedUsesofWebView ◦ Prerequisites 775

◦ Friends with Benefits 775

◦ Turnabout is Fair Play 780

◦ Navigating the Waters 784

◦ Settings, Preferences, and Options (Oh, My!) 784

• TheInputMethodFramework ◦ Prerequisites 787

◦ Keyboards, Hard and Soft 787

◦ Tailored To Your Needs 788

◦ Tell Android Where It Can Go 792

◦ Fitting In 794

◦ Jane, Stop This Crazy Thing! 796

• Fonts ◦ Prerequisites 799

◦ Love The One You’re With 799

◦ Here a Glyph, There a Glyph 803

• RichText ◦ Prerequisites 805

◦ The Span Concept 805

◦ Loading Rich Text 807

◦ Editing Rich Text 809

◦ Saving Rich Text 815

◦ Manipulating Rich Text 815

• MappingwithMapView

Trang 15

◦ Rugged Terrain 828

◦ Maps and Fragments 829

◦ Get to the Point 833

◦ Not-So-Tiny Bubbles 835

◦ Sign, Sign, Everywhere a Sign 846

◦ In A New York Minute Or Hopefully a Bit Faster 852

◦ A Little Touch of Noo Yawk 855

• CreatingDrawables ◦ Prerequisites 861

◦ Traversing Along a Gradient 861

◦ State Law 865

◦ A Stitch In Time Saves Nine 867

• Animators ◦ Prerequisites 879

ViewPropertyAnimator 879

The Foundation: Value and Object Animators 884

Hardware Acceleration 886

The Three-Fragment Problem 887

• LegacyAnimations ◦ Prerequisites 899

◦ It’s Not Just For Toons Anymore 899

◦ A Quirky Translation 900

◦ Fading To Black Or Some Other Color 904

◦ When It’s All Said And Done 906

◦ Loose Fill 907

◦ Hit The Accelerator 907

◦ Animate Set Match 908

◦ Active Animations 909

• CraftingYourOwnViews ◦ Prerequisites 911

◦ Pick Your Poison 911

◦ Colors, Mixed How You Like Them 913

• CustomDialogsandPreferences ◦ Prerequisites 925

◦ Your Dialog, Chocolate-Covered 925

◦ Preferring Your Own Preferences, Preferably 929

• AdvancedNotifications ◦ Prerequisites 937

◦ Custom Views: or How Those Progress Bars Work 937

Seeing It In Action 939

Trang 16

◦ The Mysterious Case of the Missing Number 945

• HomeScreenAppWidgets ◦ Prerequisites 947

◦ East is East, and West is West… 948

◦ The Big Picture for a Small App Widget 948

◦ Crafting App Widgets 949

◦ Another and Another 956

◦ App Widgets: Their Life and Times 957

◦ Controlling Your (App Widget’s) Destiny 957

◦ Change Your Look 958

◦ One Size May Not Fit All 959

◦ Being a Good Host 960

• Adapter-BasedAppWidgets ◦ Prerequisites 961

◦ New Widgets for App Widgets 961

◦ Preview Images 962

◦ Adapter-Based App Widgets 964

• AudioPlayback ◦ Prerequisites 979

◦ Get Your Media On 979

◦ MediaPlayer for Audio 980

◦ Other Ways to Make Noise 986

• VideoPlayback ◦ Prerequisites 989

◦ Moving Pictures 989

• ContentProviderTheory ◦ Prerequisites 995

◦ Using a Content Provider 995

◦ Building Content Providers 1001

◦ Issues with Content Providers 1008

• ContentProviderImplementationPatterns ◦ Prerequisites 1009

◦ The Single-Table Database-Backed Content Provider 1009

◦ The Local-File Content Provider 1017

• TheLoaderFramework ◦ Prerequisites 1023

◦ Cursors: Issues with Management 1024

◦ Introducing the Loader Framework 1024

Trang 17

◦ Inside SQLiteCursorLoader 1030

◦ What Else Is Missing? 1034

◦ Issues, Issues, Issues 1034

◦ Loaders Beyond Cursors 1034

◦ What Happens When…? 1037

• TheContactsContractProvider ◦ Prerequisites 1041

◦ Introducing You to Your Contacts 1042

◦ Pick a Peck of Pickled People 1043

◦ Spin Through Your Contacts 1046

◦ Makin’ Contacts 1055

• TheCalendarContractProvider ◦ Prerequisites 1062

◦ You Can’t Be a Faker 1062

◦ Do You Have Room on Your Calendar? 1062

◦ Penciling In an Event 1067

• EncryptedStorage ◦ Prerequisites 1070

◦ Scenarios for Encryption 1070

◦ Obtaining SQLCipher 1071

◦ Employing SQLCipher 1071

• PackagingandDistributingData ◦ Prerequisites 1077

◦ Packing a Database To Go 1077

• AdvancedPermissions ◦ Prerequisites 1081

◦ Securing Yourself 1081

◦ Signature Permissions 1084

• Tapjacking ◦ Prerequisites 1087

◦ What is Tapjacking? 1087

◦ Detecting Potential Tapjackers 1092

◦ Defending Against Tapjackers 1095

◦ Why Is This Being Discussed? 1098

◦ What Changed in 4.0.3? 1098

• AccessingLocation-BasedServices ◦ Prerequisites 1099

◦ Location Providers: They Know Where You’re Hiding 1100

Finding Yourself 1100

◦ On the Move 1102

Trang 18

◦ Testing… Testing… 1104

• WorkingwiththeClipboard ◦ Prerequisites 1105

◦ Using the Clipboard on Android 1.x/2.x 1105

◦ Advanced Clipboard on Android 3.x 1109

• Telephony ◦ Prerequisites 1115

◦ Report To The Manager 1116

◦ You Make the Call! 1116

◦ No, Really, You Make the Call! 1119

• WorkingWithSMS ◦ Prerequisites 1121

◦ Sending Out an SOS, Give or Take a Letter 1121

◦ You Can’t Get There From Here 1128

• UsingtheCamera ◦ Prerequisites 1131

◦ Letting the Camera App Do It 1131

◦ Scanning with ZXing 1133

◦ Directly Working with the Camera 1135

◦ Being Specific About Features 1135

• NFC ◦ Prerequisites 1137

◦ What Is NFC? 1137

◦ To NDEF, Or Not to NDEF 1139

◦ NDEF Modalities 1139

◦ NDEF Structure and Android’s Translation 1140

◦ The Reality of NDEF 1141

◦ Sources of Tags 1142

◦ Writing to a Tag 1143

◦ Responding to a Tag 1151

◦ Expected Pattern: Bootstrap 1152

◦ Mobile Devices are Mobile 1152

◦ Enabled and Disabled 1153

◦ Android Beam 1153

◦ Beaming Files 1160

◦ Additional Resources 1161

• DeviceAdministration ◦ Prerequisites 1163

Trang 19

◦ Mandating Quality of Security 1171

◦ Getting Along with Others 1172

• PowerManagerandWakeLocks ◦ Prerequisites 1173

◦ Keeping the Screen On, UI-Style 1173

◦ The Role of the WakeLock 1174

◦ What WakefulIntentService Does 1175

• PushNotificationswithGCM ◦ Prerequisites 1177

◦ The Precursor: C2DM 1177

◦ The Replacement: GCM 1178

◦ The Pieces of Push 1178

◦ A Simple Push 1185

◦ Message Options and Advanced Features 1192

◦ Re-Registration 1194

◦ Considering Encryption 1194

◦ Issues with GCM 1195

• PushNotificationswithC2DM ◦ Prerequisites 1199

◦ Pieces of Push 1200

◦ Getting From Here to There 1201

◦ Permissions for Push 1202

◦ Registering an Interest 1203

◦ Push It Real Good 1206

◦ A Controlled Push 1208

◦ The Right Way to Push 1210

• OtherSystemSettingsandServices ◦ Prerequisites 1211

◦ Setting Expectations 1211

◦ Can You Hear Me Now? OK, How About Now? 1216

◦ The Rest of the Gang 1219

• DealingwithDifferentHardware ◦ Prerequisites 1221

◦ Filtering Out Devices 1221

Runtime Capability Detection 1224

◦ Dealing with Device Bugs 1227

• RespondingtoURLs ◦ Prerequisites 1229

◦ Manifest Modifications 1229

◦ Creating a Custom URL 1231

Trang 20

• PluginPatterns

◦ Plugins by Remote 1235

◦ ContentProvider Plugins 1245

• PackageManagerTricks ◦ Prerequisites 1255

◦ Asking Around 1255

◦ Preferred Activities 1259

◦ Middle Management 1264

• SearchingwithSearchManager ◦ Prerequisites 1267

◦ Hunting Season 1267

◦ Search Yourself 1269

◦ Searching for Meaning In Randomness 1276

◦ May I Make a Suggestion? 1277

◦ Putting Yourself (Almost) On Par with Google 1281

• HandlingSystemEvents ◦ Prerequisites 1287

◦ I Sense a Connection Between Us… 1287

◦ Feeling Drained 1289

• RemoteServicesandtheBindingPattern ◦ Prerequisites 1297

◦ The Binding Pattern 1298

◦ When IPC Attacks! 1299

◦ A Consumer Economy 1301

◦ Service From Afar 1303

◦ Servicing the Service 1307

◦ The Bind That Fails 1314

◦ The “Everlasting Service” Anti-Pattern 1315

• AdvancedManifestTips ◦ Prerequisites 1317

◦ Just Looking For Some Elbow Room 1317

◦ Using an Alias 1326

• MiscellaneousIntegrationTips ◦ Prerequisites 1329

◦ Would You Like to See the Menu? 1329

◦ Take the Shortcut 1331

◦ Homing Beacons for Intents 1338

• ReusableComponents

Trang 21

• TheRoleofScriptingLanguages

◦ Prerequisites 1349

◦ All Grown Up 1349

◦ Following the Script 1350

◦ Going Off-Script 1351

• TheScriptingLayerforAndroid ◦ Prerequisites 1355

◦ The Role of SL4A 1355

◦ Getting Started with SL4A 1356

◦ Writing SL4A Scripts 1364

◦ Running SL4A Scripts 1369

◦ Potential Issues 1370

• JVMScriptingLanguages ◦ Prerequisites 1373

◦ Languages on Languages 1373

◦ A Brief History of JVM Scripting 1374

◦ Limitations 1375

◦ SL4A and JVM Languages 1376

◦ Embedding JVM Languages 1376

◦ Other JVM Scripting Languages 1390

• GoogleTV ◦ Prerequisites 1393

◦ What Features and Configurations Does It Use? 1394

◦ What Is Really Different? 1395

◦ Getting Your Development Environment Established 1399

◦ How Does Distribution Work? 1402

◦ Getting Help 1403

• KindleFire ◦ Prerequisites 1405

◦ What Features and Configurations Does It Use? 1405

◦ What Is Really Different? 1407

◦ Getting Your Development Environment Established 1412

◦ How Does Distribution Work? 1416

• Barnes&NobleNOOKTablet ◦ Prerequisites 1419

◦ What Features and Configurations Does It Use? 1419

◦ What Is Really Different? 1420

◦ Getting Your Development Environment Established 1421

◦ How Does Distribution Work? 1424

• RIMBlackberryPlaybook

Trang 22

◦ What Is Really Different? 1426

◦ Getting Your Development Environment Established 1427

◦ How Does Distribution Work? 1429

◦ Prerequisites 1433

◦ What Can This Thing Really Do? 1433

◦ What Are You Really Writing? 1434

◦ What Are You Not Allowed To Do? 1436

◦ Getting Your Development Environment Established 1438

◦ How Does Distribution Work? 1443

◦ Example: QR Code Keeper 1444

◦ Getting Help 1463

• SONYSmartWatchAccessory

◦ Prerequisites 1465

◦ What Can This Thing Really Do? 1465

◦ What Are You Really Writing? 1466

◦ Getting Your Development Environment Established 1467

◦ How Does Distribution Work? 1467

◦ Example: WatchAuth 1468

◦ Getting Help 1482

• JUnitandAndroid

◦ Prerequisites 1483

◦ You Get What They Give You 1483

◦ Your Test Cases 1486

◦ Your Test Suite 1491

◦ Running Your Tests 1492

Trang 23

◦ What to Fix 1510

◦ What to Configure 1510

• UsingHierarchyView

◦ Prerequisites 1515

◦ Launching Hierarchy View 1515

◦ Viewing the View Hierarchy 1516

◦ Role of Code Signing 1527

◦ What Happens In Debug Mode 1528

◦ Creating a Production Signing Key 1528

◦ Getting Things Done 1541

◦ Your UI Seems… Janky 1542

◦ Not Far Enough in the Background 1542

◦ Playing with Speed 1543

◦ The Role of the NDK 1560

◦ NDK Installation and Project Setup 1563

◦ Writing Your Makefile(s) 1567

◦ Building Your Library 1568

◦ Using Your Library Via JNI 1569

◦ Building and Deploying Your Project 1575

Trang 24

◦ Prerequisites 1577

◦ Reduce CPU Utilization 1577

◦ Reduce Time on the Main Application Thread 1582

◦ Improve Throughput and Responsiveness 1590

• IssueswithBandwidth

◦ Prerequisites 1593

◦ You’re Using Too Much of the Slow Stuff 1594

◦ You’re Using Too Much of the Expensive Stuff 1594

◦ You’re Using Too Much of Somebody Else’s Stuff 1595

◦ You’re Using Too Much… And There Is None 1596

◦ You Are in a Heap of Trouble 1627

◦ Warning: Contains Graphic Images 1628

◦ In Too Deep (on the Stack) 1629

• FindingMemoryLeakswithMAT

◦ Prerequisites 1631

◦ Setting Up MAT 1631

◦ Getting Heap Dumps 1632

◦ Basic MAT Operation 1637

◦ Some Leaks and Their MAT Analysis 1644

• IssueswithBatteryLife

◦ Prerequisites 1653

◦ You’re Getting Blamed 1654

Trang 25

◦ What Are You Talking About? 1657

◦ Running Trepn Tests 1659

◦ Recording Application States 1660

◦ Examining Trepn Results 1661

◦ PhoneGap and the Checklist Sample 1704

◦ Issues You May Encounter 1709

◦ For More Information 1712

• OtherAlternativeEnvironments

◦ Prerequisites 1713

◦ Rhodes 1713

◦ Flash, Flex, and AIR 1714

◦ JRuby and Ruboto 1714

◦ Mono for Android 1715

◦ App Inventor 1715

◦ Titanium Mobile 1717

◦ Other JVM Compiled Languages 1718

• WidgetCatalog:AdapterViewFlipper

Trang 26

◦ Key Usage Tips 1753

Trang 28

be an exciting and challenging area for exploration.

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

The Book’s Structure

Once upon a time, CommonsWare published a few books on Android development.What you are reading represents the merger of those separate titles into a singleomnibus title

To make the equivalent of 2,000+ pages of material manageable, the chapters are

divided into the core chapters and a series of trails.

The core chapters represent many key concepts that Android developers need tounderstand in order to build an app While an occasional “nice to have” topic willdrift into the core — to help illustrate a point, for example — the core chaptersgenerally are fairly essential

Trang 29

The core chapters are designed to be read in sequence and will interleave bothtraditional technical book prose with tutorial chapters (in the style of

CommonsWare’s former Android Programming Tutorials), to give you hands-on

experience with the concepts being discussed Most of the tutorials can be skipped,though the first two — covering setting up your SDK environment and creating aproject – everybody should read

The bulk of the chapters are divided into trails, covering some particular generaltopic, from data storage to advanced UI effects to performance measurement andtuning Each trail will have several chapters However, those chapters, and the trailsthemselves, are not necessarily designed to be read in any order Each chapter in thetrails will point out prerequisite chapters or concepts that you will want to havecovered in advance Hence, these chapters are mostly reference material, for whenyou specifically want to learn something about a specific topic

The core chapters will link to chapters in the trails, to show you where you can findmaterial related to the chapter you just read So between the book’s table of

contents, this preface, the search tool in your digital book reader, and the chapter links, you should have plenty of ways of finding the material you want toread

cross-You are welcome to read the entire book front-to-back if you wish The trails willappear after the core chapters Those trails will be in a reasonably logical order,though you may have to hop around a bit to cover all of the prerequisites

The Trails

Here is a list of all of the trails and the chapters that pertain to those trails, in order

of appearance (except for those appearing in the list multiple times, where they spanmajor categories):

Trang 33

You (hopefully) are reading this digital book by means of a Warescription.

The Warescription entitles you, for the duration of your subscription, to digitaleditions of this book and its updates, in PDF, EPUB, and Kindle (MOBI/KF8)

formats You also have access to other titles that CommonsWare may publish duringthat subscription period

Each subscriber gets personalized editions of all editions of each title That way,your books 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, thisbook will be quickly updated to be accurate with changes in the APIs

Subscribers also have access to “office hours” — online chats to help you get answers

to your Android application development questions You will find a calendar forthese on your Warescription page

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

1 ThecommonsguyTwitter feed

2 TheCommonsBlog

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

Warescriptionpage

Trang 34

Getting Help

If you have questions about the book examples, visitStackOverflowand ask a

question, tagged with android and commonsware.

If you have general Android developer questions, visit StackOverflow and ask a

question, tagged with android (and any other relevant tags, such as java).

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, andwe’ll give you a coupon for a six-month Warescription as a bounty for helping usdeliver a better product You can use that coupon to get a new Warescription, renew

an existing Warescription, or give the coupon to a friend, colleague, or some randomperson you meet on the subway

By “concrete” problem, we mean things like:

1 Typographical errors

2 Sample applications that do not work as advertised, in the environmentdescribed in the book

3 Factual errors that cannot be open to interpretation

By “unique”, we mean ones not yet reported Be sure to checkthebook’serratapage,though, to see if your issue has already been reported One coupon is given peremail containing valid bug reports

We appreciate hearing about “softer” issues as well, such as:

1 Places where you think we are in error, but where we feel our interpretation

is reasonable

2 Places where you think we could add sample applications, or expand uponthe existing material

3 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

Trang 35

Questions about the bug bounty, or problems you wish to report for bounty

consideration, should be sent tobounty@commonsware.com

Source Code And Its License

The source code samples shown in this book are available for download from thebook’sGitHubrepository All of the Android projects are licensed under theApache2.0License, in case you have the desire to reuse any of it

If you wish to use the source code from the CommonsWare Web site, bear in mindthat the projects are set up to be built by Eclipse Many are also set up to be built byAnt from the command line However, for command-line builds, you will need toupdate the build files to match your local environment To do this, deletebuild.xml

in your project directory, then runandroid update project -p from that samedirectory SeetheGitHubrepohomepagefor more details

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

Guarantee

Each CommonsWare book edition will be available for use under theCreative

CommonsAttribution-Noncommercial-ShareAlike3.0license as of the fourth

anniversary of its publication date, or when 4,000 copies of the edition have beensold, whichever comes first That means that, once four years have elapsed (perhapssooner!), 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 thisguarantee, 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 September 2016 Of course, watch the CommonsWare Web

site, as this edition might be relicensed sooner based on sales

For more details on the Creative Commons Attribution-Noncommercial-ShareAlike3.0 license, visit the Creative Commons Web site

Note that future editions of this book will become free on later dates, each four yearsfrom the publication of that edition or based on sales of that specific edition

Releasing one edition under the Creative Commons license does not automatically

release all editions under that license.

Trang 36

Portions of this book are reproduced from work created and shared by the AndroidOpen Source Project and used according to terms described in the Creative

Commons 2.5 Attribution License

Trang 38

Key Android Concepts

No doubt, you are in a hurry to get started with Android application development.After all, you are reading this book, aimed at busy coders

However, before we dive into getting tools set up and starting in on actual

programming, it is important that we “get on the same page” with respect to severalhigh-level Android concepts This will simplify further discussions later in the book

Android Applications

This book is focused on writing Android applications An application is somethingthat a user might install from the Play Store or otherwise download to their device.That application should have some user interface, and it might have other codedesigned to work in the background (multi-tasking)

This book is not focused on modifications to the Android firmware, such as writingdevice drivers For that, you will need to seek other resources

This book assumes that you have some hands-on experience with Android devices,and therefore you are familiar with buttons like HOME and BACK, the built-inSettings application, the concept of a home screen and launcher, and so forth If youhave never used an Android device, you are strongly encouraged to get one (e.g., aused one on eBay, Craigslist, etc.) and spend some time with it before starting in onlearning Android application development

Trang 39

Programming Language

The vast majority of Android applications are written exclusively in Java Hence, that

is what this book will spend most of its time on and will demonstrate with a

seemingly infinite number of examples

However, there are other options:

• You can write parts of the app in C/C++, for performance gains, porting overexisting code bases, etc

• You can write an entire app in C/C++, mostly for games using OpenGL for3D animations

• You can write the guts of an app in HTML, CSS, and JavaScript, using tools

to package that material into an Android application that can be distributedthrough the Play Store and similar venues

• And so on

Coverage of these non-Java alternatives will be found in the trails of this book, as thebulk of this book is focused on Java

The author assumes that you know Java at this point If you do not, you will need to

learn Java before you go much further You do not need to know everything about

Java, as Java is vast Rather, focus on:

• Languagefundamentals(flow control, etc.)

Trang 40

When you first learned Java — whether that was yesterday or back when dinosaursroamed the Earth — you probably started off with something like this:

class SillyApp {

public static void main(String[] args) {

System out println ( "Hello World!" );

}

}

In other words, the entry point into your application was apublic static void

method namedmain() that took aString array of arguments From there, you wereresponsible for doing whatever was necessary

However, depending on what else you may have done in Java, you may have

encountered other patterns For example, when writing a Java Web app, such as asimple servlet, you would not write amain() method Instead, there was some classyou had to inherit from or interface you had to implement, plus some place whereyou told some larger app where your code lived (e.g., aweb.xmlfile in a servlet’sWAR file)

Android apps are closer in spirit to the servlet approach You will not write a

public static void main() method Instead, you will create subclasses of someAndroid-supplied base classes In addition, you will create some metadata that tellsAndroid about those subclasses

These subclasses are referred to as components in Android There are four types, all

of which will be covered extensively in this book:

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, orthe page in a classic Web app

Normally, an activity will take up most of the screen, leaving space for some

“chrome” bits like the clock, signal strength indicators, and so forth

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

TỪ KHÓA LIÊN QUAN