Pro Android 4 : [Android 4 platform SDK techniques for … · 2013-05-22 · Android Emulator 8...
Transcript of Pro Android 4 : [Android 4 platform SDK techniques for … · 2013-05-22 · Android Emulator 8...
Pro Android 4
Satya Komatineni
Dave MacLean
Contents
Contents at a Glance..... iv
About the Authors xxi
About the Technical Reviewers xxii
Acknowledgments xxiv
Preface xxv
Chapter 1: Introducing the Android Computing Platform 1A New Platform for a New Personal Computer 1
Early History ofAndroid 3
Delving Into the DalvikVM 6
Understanding the Android Software Stack 6
Developing an End-User Application with the Android SDK 8
Android Emulator 8The Android Ul 9
The Android Foundational Components 10
Advanced Ul Concepts 11
Android Service Components 14
Android Media and Telephony Components 14
Android Java Packages 15
Taking Advantage of Android Source Code 20
Browsing Android Sources Online 20
Using Git to Download Android Sources 21
The Sample Projects in this Book 22
Summary 22
Chapter 2: Setting Up Your Development Environment 23Setting Up Your Environment 24
Downloading JDK 6 24
Downloading Eclipse 3.6 25
Downloading the Android SDK 25The Tools Window 28
Installing Android Development Tools (ADT) 28Learning the Fundamental Components 31
View 31
vi
ii CONTENTS
Activity 31
Fragment 32
Intent 32
Content Provider 32
Service 32
AndroidManifest.xml 33
Android Virtual Devices 33
Hello World! 33
Android Virtual Devices 39
Running on a Real Device 41
Exploring the Structure of an Android Application 42
Examining the Application Life Cycle 44
Simple Debugging 47
Launching the Emulator 48
References 49
Summary 49
Interview Questions 50
Chapter 3: Understanding Android Resources 51
Understanding Resources 51
String Resources 52
Layout Resources 54
Resource Reference Syntax 55
Defining Your Own Resource IDs for Later Use 57
Compiled and Uncompiled Android Resources 58
Enumerating Key Android Resources 59
Working with Arbitrary XML Resource Files 69
Working with Raw Resources 71
Working with Assets 71
Reviewing the Resources Directory Structure 72
Resources and Configuration Changes 72
Reference URLs 76
Summary 77
Interview Questions 77
Chapter 4: Understanding Content Providers 79
Exploring Android's Built-in Providers 80
Exploring Databases on the Emulator and Available Devices 80
Quick SQLite Primer 84
Architecture of Content Providers 84
Structure of Android Content URIs 86
Structure of Android MIME Types 87
Reading Data Using URIs 89
Using the Android Cursor 91
Working with the where Clause 92
Inserting Records 94
Adding a File to a Content Provider 95
Updates and Deletes 96
Implementing Content Providers 96
Vll
CONTENTS
Planning a Database 97
Extending ContentProvider 99
Fulfilling MIME-Type Contracts 104
Implementing the Query Method 105
Implementing an Insert Method 105
Implementing an Update Method 105
Implementing a Delete Method 1°6
Using UriMatcher to Figure Out the URIs 106
Using Projection Maps 107
Registering the Provider 108
Exercising the Book Provider 108
Adding a Book 109
Removing a Book 109
Getting a Count of the Books 110
Displaying the List of Books 110
Resources 111
Summary 111
Interview Questions 112
Chapter 5: Understanding Intents 113
Basics of Android Intents 113
Available Intents in Android 115
Exploring Intent Composition 117
Intents and Data URIs 117
Generic Actions 118
Using Extra Information 119
Using Components to Directly Invoke an Activity 121
Understanding Intent Categories 122
Rules for Resolving Intents to Their Components 125
Exercising the ACTION_PICK 127
Exercising the GET_CONTENT Action 130
Introducing Pending Intents 131
Resources 132
Summary 133
Interview Questions 133
Chapter 6: Building User Interfaces and Using Controls 135
Ul Development in Android 135
Building a Ul Completely in Code 137
Building a Ul Completely in XML 139
Building a Ul in XML with Code 140
Understanding Android's Common Controls 142
Text Controls 142
Button Controls 147
The ImageView Control 155
Date and Time Controls 156
The MapView Control 159
Understanding Adapters 159
Getting to Know SimpleCursorAdapter 160
vili
lis CONTENTS
Getting to Know ArrayAdapter 162
Using Adapters with AdapterViews 164
The Basic List Control: ListView 164
The GridView Control 172
The Spinner Control 174
The Gallery Control 176
Creating Custom Adapters 177
Other Controls in Android 182
Styles and Themes 183
Using Styles 183
Using Themes 186
Understanding Layout Managers 187
The LinearLayout Layout Manager 187
The TableLayout Layout Manager 191
The RelativeLayout Layout Manager 194
The FrameLayout Layout Manager 196
The GridLayout Layout Manager 198
Customizing the Layout for Various Device Configurations 199
References 200
Summary 201
Interview Questions 201
Chapter 7: Working with Menus 203
Understanding Android Menus 203
Creating a Menu 206
Working with Menu Groups 207
Responding to Menu Items 208
Working with Other Menu Types 210
Expanded Menus 211
Working with Icon Menus 211
Working with Submenus 212
Working with Context Menus 212
Working with Alternative Menus 216
Dynamic Menus 219
Loading Menus Through XML Files 219
Structure of an XML Menu Resource File 220
Inflating XML Menu Resource Files 221
Responding to XML-Based Menu Items 221
Pop-up Menus in 4.0 222
A Brief Introduction to Additional XML Menu Tags 224
Resources 226
Summary 226
Interview Questions 226
Chapter 8: Fragments for Tablets and More 229
What Is a Fragment? 230
When to Use Fragments 231
The Structure of a Fragment 232
A Fragment's Lifecycle 233
IX
CONTENTS
Sample Fragment App Showing the Lifecycle 238
FragmentTransactions and the Fragment Back Stack 244
Fragment Transaction Transitions and Animations 246
The FragmentManager247
Caution When Referencing Fragments 248
Saving Fragment State 249
ListFragments and <fragment> 249
Invoking a Separate Activity When Needed 251
Persistence of Fragments 253
Communications with Fragments 254
Using startActivityO and setTargetFragmentO 255
Custom Animations with ObjectAnimator 255
References 258
Summary 259
Interview Questions 260
Chapter 9: Working with Dialogs 261
Using Dialogs in Android 261
Understanding Dialog Fragments 262
DialogFragment Basics 262
DialogFragment Sample Application 267
Working with Toast 278
Dialog Fragments for Older Android 278
References 279
Summary 279
Interview Questions 280
Chapter 10: Exploring ActionBar 281
Anatomy of an ActionBar 282
Tabbed Navigation Action Bar Activity 283
Implementing Base Activity Classes 285
Assigning Uniform Behavior for the Action Bar 287
Implementing the Tabbed Listener 289
Implementing the Tabbed Action Bar Activity 290
Scrollable Debug Text View Layout 292
Action Bar and Menu Interaction 293
Android Manifest File 296
Examining the Tabbed Action Bar Activity 296
List Navigation Action Bar Activity 297
Creating a Spinner Adapter 298
Creating a List Listener 298
Setting Up a List Action Bar 299
Making Changes to BaseActionBarActivity 300
Making Changes to AndroidManifest.xml 300
Examining the List Action Bar Activity 301
Standard Navigation Action Bar Activity 303
Setting up the Standard Navigation Action Bar Activity 303
Making Changes to BaseActionBarActivity 304
Making Changes to AndroidManifesLxml 305
X
CONTENTS
Examining the Standard Action Bar activity 305
Action Bar and Search View 307
Defining a Search View Widget as a Menu Item 308
Casting a Search Results Activity 308
Customizing Search Through a Searchable XML File 309
Defining the Search Results Activity in the Manifest File 310
Identifying the Search Target for the Search View Widget 310
The Action Bar and Fragments 311
References 311
Summary 312
Interview Questions 312
Chapter 11: Advanced Debugging and Analysis 315
Enabling Advanced Debugging 315
The Debug Perspective 316
The DDMS Perspective 317
The Hierarchy View Perspective 320
Pixel Perfect View 321
Traceview 321
Theadb Command 323
The Emulator Console 323
StrictMode 323
StrictMode Policies 324
Turning Off StrictMode 325
StrictMode with Old Android Versions 326
StrictMode Exercise 327
References 328
Summary 328
Interview Questions 329
Chapter 12: Responding to Configuration Changes... 331
The Configuration Change Process 331
The Destroy/Create Cycle of Activities 333
The Destroy/Create Cycle of Fragments 334
Using FragmentManager to Save Fragment State 335
Using setRetainlnstance on a Fragment 336
Deprecated Configuration Change Methods 336
References 336
Summary 336
Interview Questions 337
Chapter 13: Working with Preferences and Saving State 339
Exploring the Preferences Framework 339
Understanding ListPreference 340
Understanding CheckBoxPreference 348
Understanding EditTextPreference 350
Understanding RingtonePreference and MultiSelectListPreference 351
Organizing Preferences 351
Using PreferenceCategory 352
Creating Child Preferences with Dependency 355
XI
:CONTENTS
Preferences with Headers35b
Manipulating Preferences Programmatically357
Saving State with Preferences358
Using DialogPreference359
Reference360
Summary360
Interview Questions360
Chapter 14: Exploring Security and Permissions 363
Understanding the Android Security Model 363
Overview of Security Concepts 363
Signing Applications for Deployment364
Performing Runtime Security Checks371
Understanding Security at the Process Boundary 371
Declaring and Using Permissions 372
Understanding and Using Custom Permissions 374
Understanding and Using URI Permissions 379
References381
Summary382
Interview Questions 382
Chapter 15: Building and Consuming Services 383
Consuming HTTP Services 383
Using the HttpClient for HTTP GET Requests 384
Using the HttpClient for HTTP POST Requests (a Multipart Example) 386
SOAP, JSON, and XML Parsers 388
Dealing with Exceptions 389
Addressing Multithreading Issues 391
Fun with Timeouts 394
Using the HttpURLConnection 395
Using the AndroidHttpClient 395
Using Background Threads (AsyncTask) 396
Getting Files Using DownloadManager 403
Using Android Services 409
Understanding Services in Android 409
Understanding Local Services 410
Understanding AIDL Services 417
Defining a Service Interface in AIDL 418
Implementing an AIDL Interface 421
Calling the Service from a Client Application 423
Passing Complex Types to Services 427
References 437
Summary 437
Interview Questions 438
Chapter 16: Exploring Packages 441
Packages and Processes 441
Details of a Package Specification 441
Translating the Package Name to a Process Name 442
Listing Installed Packages 442
xii
»COHTENTS
Deleting a Package Through the Package Browser 443
Revisiting the Package Signing Process 443
Understanding Digital Signatures: Scenario 1 444
Understanding Digital Signatures: Scenario 2 444
A Pattern for Understanding Digital Signatures 445
So How Do You Digitally Sign? 445
Implications of the Signing Process 446
Sharing Data Among Packages 446
The Nature of Shared User IDs 447
A Code Pattern for Sharing Data 447
Library Projects 449
What Is a Library Project? 449
Library Project Predicates 450
Creating a Library Project 452
Creating an Android Project That Uses a Library 455
Caveats to Using Library Projects 464
References 465
Summary 466
Interview Questions 466
Chapter 17: Exploring Handlers 469
Android Components and Threading 469
Activities Run on the Main Thread 470
Broadcast Receivers Run on the Main Thread 471
Services Run on the Main Thread 471
Content Provider Runs on the Main Thread 471
Implications of a Singular Main Thread 471
Thread Pools, Content Providers, and External Service Components 472
Thread Utilities: Discovering Your Threads 472
Handlers 473
Implications of Holding the Main Thread 475
Using a Handler to Defer Work on the Main Thread 475
Sample Handler Source Code That Defers Work 476
Constructing a Suitable Message Object 477
Sending Message Objects to the Queue 478
Responding to the handleMessage Callback 478
Using Worker Threads 479
Invoking a Worker Thread from a Menu 480
Communicating Between the Worker and the Main Threads 481
Component and Process Lifetimes 483
Activity Life Cycle 484
Service Life Cycle 485
Receiver Life Cycle 485
Provider Life Cycle 486
References 486
Summary 487
Interview Questions 487
Xlil
CONTENTS
Chapter 18: Exploring the AsyncTask 489
Implementing a simple AsyncTask 490
GettingPpast the Generics in AsyncTask 490
Subclassing an Async Task 491
Implementing Your First Async Task 492
Calling an Async Task 494
onPreExecuteO Callback and Progress Dialog 494
ctolnBackgroundO method 495
Triggering onProgressUpdateO 496
onPostExecuteO Method 496
Upgrading to the Deterministic Progress Dialog 496
Nature of an Async Task 499
Device Rotation and AsyncTask 500
Life Cycle Methods and AsyncTask 501
References 501
Summary 502
Interview Questions 502
Chapter 19: Broadcast Receivers and Long-Running Services 503
Broadcast Receivers 503
Sending a Broadcast 504
Coding a Simple Receiver: Sample Code 504
Registering a Receiver in the Manifest File 505
Accommodating Multiple Receivers 506
Out-of-Process Receivers 508
Using Notifications from a Receiver 508
Monitoring Notifications Through the Notification Manager 509
Sending a Notification 511
Starting an Activity in a Broadcast Receiver 513
Long-Running Receivers and Services 514
Long-Running Broadcast Receiver Protocol 515
IntentService 516
IntentService Source Code 517
Extending IntentService for a Broadcast Receiver 519
Long-Running Broadcast Service Abstraction 519
A Long-Running Receiver 521
Abstracting a Wake Lock with LightedGreenRoom 523
Long-Running Service Implementation 529
Details of a Nonsticky Service 530
Details of a Sticky Service 531
A Variation of Nonsticky; Redeliver Intents 531
Specifying Service Flags in OnStartCommand 531
Picking Suitable Stickiness 532
Controlling the Wake Lockfrom Two Places 532
Long-Running Service Implementation 532
Testing Long-Running Services 534
Your Responsibilities 534
Framework Responsiblities 535
xiv
iCONTENTS
A Few Notes about the Project Download File 535
References 536
Summary 537
Interview Questions 537
Chapter 20: Exploring the Alarm Manager 539
Alarm Manager Basics: Setting Up a Simple Alarm 539
Getting Access to the Alarm Manager 540
Setting Up the Time for the Alarm 540
Creating a Receiver for the Alarm 541
Creating a Pendinglntent Suitable for an Alarm 541
Setting the Alarm 542
Test Project 542
Exploring Alarm Manager Alternate Scenarios 544
Setting Off an Alarm Repeatedly 544
Cancelling an Alarm 545
Working with Multiple Alarms 546
Intent Primacy in Setting Off Alarms 548
Persistence of Alarms 551
Alarm Manager Predicates 551
References 552
Summary 552
Interview Questions 552
Chapter 21: Exploring 2D Animation 555
Frame-by-Frame Animation 556
Planning for Frame-by-Frame Animation 556
Creating the Activity 557
Adding Animation to the Activity 559
Layout Animation 562
Basic Tweening Animation Types 562
Planning the Layout Animation Test Harness 563
Creating the Activity and the ListView 564
Animating the ListView 566
Using Interpolators 569
View Animation 571
Understanding View Animation 571
Adding Animation 574
Using Camera to Provide Depth Perception in 2D 577
Exploring the AnimationListener Class 579
Notes on Transformation Matrices 579
Property Animations: The New Animation API 580
Property Animation 581
Planning a Test Bed for Property Animation 582
Basic View Animation with Object Animators 585
Sequential Animation with AnimatorSet 586
Setting Animation Relationships with AnimationSetBuiider 587
Using XML to Load Animators 588
Using PropertyValuesHolder 589
XV
CONTENTS
View Properties Animation 590
Type Evaluators 591
Key Frames 594
Layout Transitions 595
Resources 596
Summary 596
Interview Questions 597
Chapter 22: Exploring Maps and Location-based Services 599
Understanding the Mapping Package 600
Obtaining a Maps API Key from Google 600
Understanding MapView and MapActivity 602
Adding Markers Using Overlays 608
Understanding the Location Package 614
Geocoding with Android 614
Geocoding with Background Threads 618
Understanding the LocationManager Service 621
Showing Your Location Using MyLocationOverlay 629
Using Proximity Alerts 633
References 637
Summary 638
Interview Questions 639
Chapter 23: Using the Telephony APIs 641
Working with SMS 641
Sending SMS Messages 641
Monitoring Incoming SMS Messages 645
Working with SMS Folders 647
Sending E-mail 649
Working with the Telephony Manager 650
Session Initiation Protocol (SIP) 653
Experimenting with SipDemo 654
The android.net.sip package 655
References 656
Summary 657
interview Questions 657
Chapter 24: Understanding the Media Frameworks 659
Using the MediaAPIs 659
Using SD Cards 660
Playing Media 665
Playing Audio Content 665
Playing Video Content 678
Recording Media 680
Exploring Audio Recording with MediaRecorder 681
Recording Audio with AudioRecord 685
Exploring Video Recording 689
Exploring the MediaStore Class 699
Recording Audio Using an Intent 700
Adding Media Content to the Media Store 703
xvi
il CONTENTS
Triggering MediaScanner for the Entire SD Card 706
References 706
Summary 707
Interview Questions 708
Chapter 25: Home Screen Widgets 709
Architecture of Home Screen Widgets 709
What Are Home Screen Widgets? 710
User Experience with Home Screen Widgets 710
Life Cycle of a Widget 714
A Sample Widget Application 721
Defining the Widget Provider 723
Defining Widget Size 724
Widget Layout-Related Files 725
Implementing a Widget Provider, 727
Implementing Widget Models 728
Implementing Widget Configuration Activity 736
Widget Preview Tool 740
Widget Limitations and Extensions 740
Collection-Based Widgets 741
Resources 741
Summary 741
Interview Questions 742
Chapter 26: Exploring List Widgets 745
A Quick Note on Remote Views 745
Working with Lists in Remote Views 746
Preparing a Remote Layout 748
Loading a Remote Layout 751
Setting Up RemoteViewsService 752
Setting Up RemoteViewsFactory 753
Setting Up onClick Events 757
Responding to onClick Events 760
Working Sample: Test Home Screen List Widget 761
Creating the Test Widget Provider 762
Creating the Remote Views Factory 765
Coding Remote Views Service 767
Main Widget Layout File 768
Widget Provider Metadata 768
AndroidManlfest.xml 769
Testing the Test List Widget 769
References 772
Summary 773
Interview Questions 773
Chapter 27: Touch Screens 775
Understanding MotionEvents 775
The MotionEvent Object 775
Recycling MotionEvents 787
Using VelocityTracker 788
xvll
< CONTENTS
Multitouch 790
The Basics of Multitouch 790
Touches with Maps 797
Gestures 799
The Pinch Gesture 800
GestureDetector and OnGestureListeners 800
Custom Gestures 803
The Gestures Builder Application 803
References 810
Summary 810
Interview Questions 811
Chapter 28: Implementing Drag and Drop 813
Exploring Drag and Drop 813
Basics of Drag and Drop in 3.0+ 819
Drag-and-Drop Example Application 820
List of Files 821
Laying Outthe Example Drag-and-drop Application 821
Responding to onDrag in the Dropzone 823
Setting Up the Drag Source Views 826
Testing the Example Drag-and-Drop Application 830
References 831
Summary 831
Interview Questions 831
Chapter 29: Using Sensors 833
What Is a Sensor? 833
Detecting Sensors 834
What Can We Know About a Sensor? 834
Getting Sensor Events 837
Issues with Getting Sensor Data 839
Interpreting Sensor Data 840
Light Sensors 840
Proximity Sensors 841
Temperature Sensors 841
Pressure Sensors 842
Gyroscope Sensors 842
Accelerometers 842
Magnetic Field Sensors 849
Using Accelerometers and Magnetic Field Sensors Together 849
Orientation Sensors 850
Magnetic Declination and GeomagneticField 856
Gravity Sensors 857
Linear Acceleration Sensors 857
Rotation Vector Sensors 857
Near Field Communication Sensors 858
References 870
Summary 870Interview Questions 871
xviii
m. CONTENTS
i Chapter 30: Exploring the Contacts API 873
Understanding Accounts 874
A Quick Tour of Account Screens 874
Relevance of Accounts to Contacts 878
Enumerating Accounts 878
Understanding the Contacts Application 880
Introducing the Personal Profile 881
Showing Contacts 883
Showing Contact Details 883
Editing Contact Details 885
Setting a Contact's Photo 886
Exporting Contacts 886
Various Contact Data Types 888
Understanding Contacts 889
Examining the Contacts SQLite Database 889
Raw Contacts 890
Data Table 892
Aggregated Contacts 893
view_contacts 895
contact_entities_view 896
Working with the Contacts API 897
Exploring Accounts 897
Exploring Aggregated Contacts 900
Exploring Raw Contacts 908
Exploring Raw Contact Data 912
Adding a Contact and Its Details 915
Controlling Aggregation 917
Impacts of Syncing 917
Understanding the Personal Profile 918
Reading Profile Raw Contacts 919
Reading Profile Contact Data 920
Adding Data to the Personal Profile 921
References 922
Summary 923
Interview Questions 924
Chapter 31: Deploying Your Application: Android Market and Beyond 927
Becoming a Publisher 928
Following the Rules 928
Developer Console 931
Preparing Your Application for Sale.., 933
Testing for Different Devices 934
Supporting Different Screen Sizes 934
Preparing AndroidManifest.xml for Uploading 935
Localizing Your Application 936
Preparing Your Application Icon 937
Considerations for Making Money from Apps 937
Directing Users Back to the Market 938
xix
: CONTENTS
The Android Licensing Service 939
Using ProGuard for Optimizing, Fighting Piracy 939
Preparing Your .apk File for Uploading 941
Uploading Your Application 942
Graphics 942
Listing Details 943
Publishing Options 944
Contact Information 945
Consent 945
User Experience on Android Market 945
Beyond Android Market 947
References 948
Summary 948
Interview Questions 949
Index 951
xx