32,99 €
The comprehensive developer guide to the latest Android features and capabilities Professional Android, 4th Edition shows developers how to leverage the latest features of Android to create robust and compelling mobile apps. This hands-on approach provides in-depth coverage through a series of projects, each introducing a new Android platform feature and highlighting the techniques and best practices that exploit its utmost functionality. The exercises begin simply, and gradually build into advanced Android development. Clear, concise examples show you how to quickly construct real-world mobile applications. This book is your guide to smart, efficient, effective Android development. * Learn the best practices that get more out of Android * Understand the anatomy, lifecycle, and UI metaphor of Android apps * Design for all mobile platforms, including tablets * Utilize both the Android framework and Google Play services
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1203
Veröffentlichungsjahr: 2018
Cover
Introduction
1 Hello, Android
ANDROID APPLICATION DEVELOPMENT
A LITTLE BACKGROUND
THE ANDROID ECOSYSTEM
PRE-INSTALLED ANDROID APPLICATIONS
ANDROID SDK FEATURES
WHAT DOES ANDROID RUN ON?
WHY DEVELOP FOR MOBILE?
WHY DEVELOP FOR ANDROID?
INTRODUCING THE DEVELOPMENT FRAMEWORK
2 Getting Started
GETTING STARTED DEVELOPING ANDROID APPS
DEVELOPING FOR ANDROID
DEVELOPING FOR MOBILE AND EMBEDDED DEVICES
ANDROID DEVELOPMENT TOOLS
3 Applications and Activities and Fragments, Oh My!
APPLICATIONS, ACTIVITIES, AND FRAGMENTS
THE COMPONENTS OF AN ANDROID APPLICATION
THE ANDROID APPLICATION LIFE CYCLE, PRIORITY, AND PROCESS STATES
INTRODUCING THE ANDROID APPLICATION CLASS
A CLOSER LOOK AT ANDROID ACTIVITIES
INTRODUCING FRAGMENTS
BUILDING AN EARTHQUAKE VIEWER APPLICATION
4 Defining the Android Manifest and Gradle Build Files, and Externalizing Resources
THE MANIFEST, BUILD FILES, AND RESOURCES
INTRODUCING THE ANDROID MANIFEST
CONFIGURING THE GRADLE BUILD
EXTERNALIZING RESOURCES
5 Building User Interfaces
FUNDAMENTAL ANDROID DESIGN
DENSITY-INDEPENDENT DESIGN
ANDROID USER INTERFACE FUNDAMENTALS
INTRODUCING LAYOUTS
THE ANDROID WIDGET TOOLBOX
WORKING WITH LISTS AND GRIDS
INTRODUCING DATA BINDING
CREATING NEW VIEWS
6 Intents and Broadcast Receivers
USING INTENTS AND BROADCAST RECEIVERS
USING INTENTS TO LAUNCH ACTIVITIES
CREATING INTENT FILTERS TO RECEIVE IMPLICIT INTENTS
INTRODUCING LINKIFY
USING INTENTS TO BROADCAST EVENTS
INTRODUCING THE LOCAL BROADCAST MANAGER
INTRODUCING PENDING INTENTS
7 Using Internet Resources
CONNECTING TO THE INTERNET
CONNECTING, DOWNLOADING, AND PARSING INTERNET RESOURCES
USING THE DOWNLOAD MANAGER
BEST PRACTICES FOR DOWNLOADING DATA WITHOUT DRAINING THE BATTERY
AN INTRODUCTION TO INTERNET SERVICES AND CLOUD COMPUTING
8 Files, Saving State, and User Preferences
SAVING FILES, STATES, AND PREFERENCES
SAVING AND RESTORING ACTIVITY AND FRAGMENT INSTANCE STATE USING THE LIFECYCLE HANDLERS
RETAINING INSTANCE STATE WITH HEADLESS FRAGMENTS AND VIEW MODELS
CREATING AND SAVING SHARED PREFERENCES
RETRIEVING SHARED PREFERENCES
INTRODUCING ON SHARED PREFERENCE CHANGE LISTENERS
CONFIGURING AUTO BACKUP OF APPLICATION FILES AND SHARED PREFERENCES
BUILDING A PREFERENCE UI
CREATING A SETTINGS ACTIVITY FOR THE EARTHQUAKE MONITOR
INCLUDING STATIC FILES AS RESOURCES
WORKING WITH THE FILESYSTEM
SHARING FILES USING FILE PROVIDER
ACCESSING FILES FROM OTHER APPLICATIONS USING THE STORAGE ACCESS FRAMEWORK
USING URI-BASED PERMISSIONS
9 Creating and Using Databases
INTRODUCING STRUCTURED DATA STORAGE IN ANDROID
STORING DATA USING THE ROOM PERSISTENCE LIBRARY
PERSISTING EARTHQUAKES TO A DATABASE WITH ROOM
WORKING WITH SQLITE DATABASES
INTRODUCING THE FIREBASE REALTIME DATABASE
10 Content Providers and Search
INTRODUCING CONTENT PROVIDERS
WHY SHOULD I USE CONTENT PROVIDERS?
CREATING CONTENT PROVIDERS
ACCESSING CONTENT PROVIDERS WITH CONTENT RESOLVERS
USING NATIVE ANDROID CONTENT PROVIDERS
ADDING SEARCH TO YOUR APPLICATION
11 Working in the Background
WORKING IN THE BACKGROUND
USING BACKGROUND THREADS
SCHEDULING BACKGROUND JOBS
USING NOTIFICATIONS TO NOTIFY USERS
USING FIREBASE CLOUD MESSAGING
USING ALARMS
INTRODUCING SERVICES
12 Implementing the Android Design Philosophy
INTRODUCING THE ANDROID DESIGN PHILOSOPHY
DESIGNING FOR EVERY SCREEN
INTRODUCING MATERIAL DESIGN
MATERIAL DESIGN UI ELEMENTS
13 Implementing a Modern Android User Experience
THE MODERN ANDROID UI
CREATING CONSISTENT, MODERN USER INTERFACES USING APPCOMPAT
ADDING A MENU AND ACTIONS TO THE APP BAR
GOING BEYOND THE DEFAULT APP BAR
IMPROVING THE EARTHQUAKE MONITOR’S APP BAR
APP NAVIGATION PATTERNS
ADDING TABS TO THE EARTHQUAKE MONITOR
CHOOSING THE RIGHT LEVEL OF INTERRUPTION
14 Advanced Customization of Your User Interface
EXPANDING THE USER EXPERIENCE
SUPPORTING ACCESSIBILITY
INTRODUCING ANDROID TEXT-TO-SPEECH
USING SPEECH RECOGNITION
CONTROLLING DEVICE VIBRATION
GOING FULL SCREEN
WORKING WITH PROPERTY ANIMATIONS
ENHANCING YOUR VIEWS
ADVANCED CANVAS DRAWING
COMPOSITE DRAWABLE RESOURCES
COPY, PASTE, AND THE CLIPBOARD
15 Location, Contextual Awareness, and Mapping
ADDING LOCATION, MAPS, AND CONTEXTUAL AWARENESS TO YOUR APPLICATIONS
INTRODUCING GOOGLE PLAY SERVICES
FINDING DEVICE LOCATION USING GOOGLE LOCATION SERVICES
SETTING AND MANAGING GEOFENCES
USING THE LEGACY PLATFORM LOCATION-BASED SERVICES
USING THE GEOCODER
CREATING MAP-BASED ACTIVITIES
MAPPING THE EARTHQUAKE EXAMPLE
ADDING CONTEXTUAL AWARENESS
16 Hardware Sensors
INTRODUCING ANDROID SENSORS
TESTING SENSORS WITH THE ANDROID VIRTUAL DEVICE AND EMULATOR
BEST PRACTICES FOR WORKING WITH SENSORS
MONITORING A DEVICE’S MOVEMENT AND ORIENTATION
USING THE ENVIRONMENTAL SENSORS
USING BODY SENSORS
USER ACTIVITY RECOGNITION
17 Audio, Video, and Using the Camera
PLAYING AUDIO AND VIDEO, AND USING THE CAMERA
PLAYING AUDIO AND VIDEO
USING THE MEDIA ROUTER AND CAST APPLICATION FRAMEWORK
BACKGROUND AUDIO PLAYBACK
USING THE MEDIA RECORDER TO RECORD AUDIO
USING THE CAMERA FOR TAKING PICTURES
RECORDING VIDEO
ADDING MEDIA TO THE MEDIA STORE
18 Communicating with Bluetooth, NFC, and Wi-Fi Peer-to-Peer
NETWORKING AND PEER-TO-PEER COMMUNICATION
TRANSFERRING DATA USING BLUETOOTH
TRANSFERRING DATA USING WI-FI PEER-TO-PEER
USING NEAR FIELD COMMUNICATION
USING ANDROID BEAM
19 Invading the Home Screen
CUSTOMIZING THE HOME SCREEN
INTRODUCING HOME SCREEN WIDGETS
CREATING AN EARTHQUAKE WIDGET
INTRODUCING COLLECTION VIEW WIDGETS
CREATING LIVE WALLPAPER
CREATING APP SHORTCUTS
20 Advanced Android Development
ADVANCED ANDROID
PARANOID ANDROID
DEALING WITH DIFFERENT HARDWARE AND SOFTWARE AVAILABILITY
OPTIMIZING UI PERFORMANCE WITH STRICT MODE
TELEPHONY AND SMS
21 Releasing, Distributing, and Monitoring Applications
PREPARING FOR RELEASE
UPDATING APPLICATION METADATA IN YOUR APPLICATION MANIFEST
SIGNING PRODUCTION BUILDS OF YOUR APPLICATION
DISTRIBUTING YOUR APPLICATION ON THE GOOGLE PLAY STORE
AN INTRODUCTION TO MONETIZING APPLICATIONS
APPLICATION MARKETING, PROMOTION, AND DISTRIBUTION STRATEGIES
USING FIREBASE TO MONITOR YOUR APPLICATION
Index
End User License Agreement
Chapter 4
TABLE 4-1: Animation Type Attributes
Chapter 16
TABLE 16-1 Sensor Return Values
Chapter 1
FIGURE 1-1
Chapter 2
FIGURE 2-1
FIGURE 2-2
FIGURE 2-3
FIGURE 2-4
FIGURE 2-5
FIGURE 2-6
FIGURE 2-7
FIGURE 2-8
FIGURE 2-9
FIGURE 2-10
FIGURE 2-11
FIGURE 2-12
FIGURE 2-13
FIGURE 2-14
FIGURE 2-15
FIGURE 2-16
FIGURE 2-17
FIGURE 2-18
FIGURE 2-19
FIGURE 2-20
FIGURE 2-21
FIGURE 2-22
FIGURE 2-23
FIGURE 2-24
FIGURE 2-25
Chapter 3
FIGURE 3-1
FIGURE 3-2
FIGURE 3-3
FIGURE 3-4
FIGURE 3-5
FIGURE 3-6
FIGURE 3-7
Chapter 4
FIGURE 4-1
FIGURE 4-2
FIGURE 4-3
FIGURE 4-4
FIGURE 4-5
Chapter 5
FIGURE 5-1
FIGURE 5-2
FIGURE 5-3
FIGURE 5-4
FIGURE 5-5
Chapter 6
FIGURE 6-1
FIGURE 6-2
Chapter 7
FIGURE 7-1
FIGURE 7-2
FIGURE 7-3
FIGURE 7-4
Chapter 8
FIGURE 8-1
FIGURE 8-2
FIGURE 8-3
FIGURE 8-4
Chapter 9
FIGURE 9-1
FIGURE 9-2
FIGURE 9-3
FIGURE 9-4
FIGURE 9-5
FIGURE 9-6
FIGURE 9-7
FIGURE 9-8
Chapter 10
FIGURE 10-1
FIGURE 10-2
FIGURE 10-3
FIGURE 10-4
FIGURE 10-5
Chapter 11
FIGURE 11-1
FIGURE 11-2
FIGURE 11-3
FIGURE 11-4
FIGURE 11-5
FIGURE 11-6
FIGURE 11-7
FIGURE 11-8
FIGURE 11-9
FIGURE 11-10
Chapter 12
FIGURE 12-1
FIGURE 12-2
FIGURE 12-3
FIGURE 12-4
FIGURE 12-5
FIGURE 12-6
FIGURE 12-7
FIGURE 12-8
FIGURE 12-9
FIGURE 12-10
FIGURE 12-11
FIGURE 12-12
FIGURE 12-13
FIGURE 12-14
Chapter 13
FIGURE 13-1
FIGURE 13-2
FIGURE 13-3
FIGURE 13-4
FIGURE 13-5
FIGURE 13-6
FIGURE 13-7
FIGURE 13-8
FIGURE 13-9
FIGURE 13-10
FIGURE 13-11
FIGURE 13-12
FIGURE 13-13
Chapter 14
FIGURE 14-1
FIGURE 14-2
FIGURE 14-3
Chapter 15
FIGURE 15-1
FIGURE 15-2
FIGURE 15-3
FIGURE 15-4
FIGURE 15-5
FIGURE 15-6
FIGURE 15-7
FIGURE 15-8
FIGURE 15-9
FIGURE 15-10
FIGURE 15-11
FIGURE 15-12
FIGURE 15-13
FIGURE 15-14
FIGURE 15-15
FIGURE 15-16
FIGURE 15-17
Chapter 16
FIGURE 16-1
FIGURE 16-2
FIGURE 16-3
FIGURE 16-4
Chapter 17
FIGURE 17-1
Chapter 18
FIGURE 18-1
FIGURE 18-2
FIGURE 18-3
FIGURE 18-4
Chapter 19
FIGURE 19-1
FIGURE 19-2
FIGURE 19-3
FIGURE 19-4
FIGURE 19-5
FIGURE 19-6
Chapter 20
FIGURE 20-1
FIGURE 20-2
FIGURE 20-3
Chapter 21
FIGURE 21-1
FIGURE 21-2
FIGURE 21-3
FIGURE 21-4
FIGURE 21-5
FIGURE 21-6
FIGURE 21-7
FIGURE 21-8
FIGURE 21-9
FIGURE 21-10
FIGURE 21-11
FIGURE 21-12
FIGURE 21-13
FIGURE 21-14
FIGURE 21-15
FIGURE 21-16
FIGURE 21-17
FIGURE 21-18
FIGURE 21-19
FIGURE 21-20
FIGURE 21-21
FIGURE 21-22
FIGURE 21-23
FIGURE 21-24
FIGURE 21-25
FIGURE 21-26
FIGURE 21-27
FIGURE 21-28
Cover
Table of Contents
Begin Reading
C1
v
vi
vii
ix
xi
xiii
xv
xxxi
xxxii
xxxiii
xxxiv
xxxv
xxxvi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
465
466
468
469
470
471
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
E1
Fourth Edition
Reto Meier
Ian Lake
For many people, smartphones have become an extension of themselves. Now running on over 2 billion monthly-active devices, Android is the most common smartphone operating system in use world-wide, with users installing an average of 50 apps each, resulting in over 94 billion apps downloaded from the Play app store in 2017 alone.
Ubiquitous and indispensable, smartphones are so advanced and personal that studies have shown people become anxious if they misplace their device, lose connectivity, or run low on battery.
In the 10 years since launching in 2008, Android has expanded beyond mobile phones to become a development platform for a wide range of hardware, with 24,000 devices from over 1,300 brands, including everything from tablets to televisions, watches, cars, and Internet of Things (IoT) devices. Over the same period, there have been 28 platform and SDK releases.
These innovations, combined with the size of the ecosystem, provide unparalleled opportunities for developers to create innovative new applications for a global audience of users.
Android offers an open platform for mobile application development. Without artificial barriers, Android developers are free to write apps that take full advantage of an incredible range of devices. Using Google Play for distribution, developers can distribute free and paid applications to compatible Android devices globally.
This book is a hands-on guide to building Android applications for all Android devices. It’s written based on version 8.1 of the Android SDK, using Android Studio 3.1. Chapter by chapter, it takes you through a series of sample projects, each introducing new features and techniques to get the most out of Android. It covers all the basic functionality to get started, as well as the information for experienced mobile developers to take full advantage of the features of Android, to enhance existing products or create innovative new ones.
The Android team releases a new major platform every year, a new version of Android Studio every few months, and incremental changes to Jetpack, such as the support library and Android Architecture Components, many times each year. With such rapid release cycles, there are regular changes, additions, and improvements to the tools, platform APIs, and development libraries you’ll use—and which are described in this book. To minimize the impact of these changes, the Android engineering team works hard to ensure backward compatibility.
However, future releases will date some of the information provided in this book, and not all active Android devices will be running the latest platform release. To mitigate this, wherever possible, we have used backward-compatible support libraries, and included details on which platform releases support the functionality described—and which alternatives may exist to provide support for users of devices running earlier platforms.
Further, the explanations and examples included will give you the grounding and knowledge needed to write compelling mobile applications using the current SDK, along with the flexibility to quickly adapt to future enhancements.
This book is for anyone interested in creating applications for the Android platform. It includes information that will be valuable, whether you’re an experienced mobile developer on other platforms, making your first foray into writing mobile apps, and if you have some Android development experience.
It will help if you’ve used a smartphone (particularly an Android device), but it’s not necessary, nor is prior experience in mobile application development.
It’s expected that you’ll have experience in software development and be familiar with basic object-oriented paradigms. An understanding of Java syntax is expected, though not a strict necessity.
Chapters 1 and 2 introduce mobile development and the Android development platform, and contain instructions to get you started. Beyond that, there’s no requirement to read the chapters in order, although a good understanding of the core components described in Chapters 3–7 is important before you venture into the remaining chapters. Chapter 11 covers important details on how to ensure your apps are responsive and efficient, while Chapters 12–14 describe how to provide a rich and consistent user experience. The remaining chapters cover a variety of functionality whose relevance will vary based on your application, and can be read in whatever order interest or need dictates.
Chapter 1 introduces Android, including what it is and how it fits into the mobile development ecosystem. What Android offers as a development platform and why it’s an exciting opportunity for creating mobile phone applications are then examined in greater detail.
Chapter 2 covers some best practices for mobile development and explains how to download and install Android Studio and the Android SDK. It then introduces some of the tools and features included with Android Studio, and demonstrates how they can be used to create and debug new applications.
Chapters 3–7 take an in-depth look at the fundamental Android application components—starting by examining the components that make up an Android application, and then moving on to “Activities” and “Fragments,” and their associated lifetimes and lifecycles.
You’ll then be introduced to the application manifest and the Gradle build system, before learning more about the external resource framework used to support devices used in different counties, with different languages, and in a variety of shapes and sizes.
You’ll learn how to create basic user interfaces with layouts, Views, and Fragments, before being introduced to the Intent and Broadcast Receiver mechanisms used to perform actions and send messages between application components. Accessing Internet resources is then covered, followed by a detailed look at data storage, retrieval, and sharing. You’ll start with the preference-saving mechanism and then move on to file handling, databases, and Content Providers—including accessing data from the native databases.
This section finishes with an examination of how to ensure your app is always responsive, and is efficient in its use of battery when running in the background. You’ll be introduced to threading APIs that enable asynchronous execution, and mechanisms that support efficient scheduling of background work. You’ll also learn how to create and display interactive Notifications.
Chapters 12–14 build on the UI framework introduced in Chapter 5. You’ll learn to enhance the user experience through the principles of material design and to make your applications accessible and optimized for a variety of screen sizes and resolutions. You’ll further improve the user experience by understanding the variety of navigation options available, adding movement through animations, and the use of Toolbars and Menus.
Chapters 15–19 look at more advanced topics. You’ll learn how to use Google Play services to add interactive maps, find the user’s location, and how to create geo- and awareness-fences. Using movement and environmental Sensors—including the compass, accelerometers, and the barometer—you’ll make your applications react to their environment.
After looking at how to play and record multimedia, as well as how to use the camera to take pictures and record video, you’ll be introduced to Android’s communication capabilities, including Bluetooth, NFC, and Wi-Fi Direct. Next, you’ll learn how your applications can interact with users directly from the home screen using dynamic Widgets, Live Wallpaper, and the Application Shortcuts.
Chapter 20 discusses several advanced development topics, including security, using the fingerprint sensor, and Strict Mode, followed by the telephony APIs and the APIs used to send and receive SMS messages.
Finally, Chapter 21 examines the process for building, releasing, monitoring, and monetizing your applications. In particular, it includes details for publishing and distributing your applications within Google Play.
This book is structured in a logical sequence to help readers of different development backgrounds learn how to write advanced Android applications. There’s no requirement to read each chapter sequentially, but several of the sample projects are developed over the course of multiple chapters, adding new functionality and other enhancements at each stage.
Experienced mobile developers who have already installed Android Studio, and those with a working knowledge of Android development, can skim the first two chapters—which are an introduction to mobile development and instructions for creating your development environment—and then dive in at Chapters 3–7. These chapters cover the fundamentals of Android development, so it’s important to have a solid understanding of the concepts they describe.
With this covered, you can move on to the remaining chapters, which look at material design, maps, location-based services, background applications, and more advanced topics, such as hardware interaction and networking.
To use the code samples in this book, you will need to create an Android development environment by downloading Android Studio and the Android SDK. It’s also possible to use other IDEs, or even to build your apps from the command-line. We’ll assume, however, you’re using Android Studio.
Android development is supported on Windows, macOS, and Linux, with Android Studio and the SDK available from the Android website.
You do not need an Android device to use this book or develop Android applications—though it can be useful, particularly when testing.
Chapter 2 outlines these requirements in more detail and describes where to download and how to install each component.
To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.
Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
WARNING Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
As for styles in the text:
We show file names, URLs, and code within the text like so:
persistence.properties
.
To help readability, class names in text are often represented using a regular font but capitalized like so: Content Provider.
We present code in two different ways:
We use a monofont type with no highlighting for most code examples.
We use bold to indicate changes or additions from a similar previous code snippet.
In some code samples, you’ll see lines marked as follows:
[… Existing code …]
or
[… Implement something here …]
These represent instructions to replace the entire line (including the square brackets) with actual code, either from a previous code snippet (in the former case) or with your own implementation (in the latter).
To keep the code samples reasonably concise, we have not always included every
package
definition or
import
statement required in the code snippets. The downloadable code samples described below include all the required
import
statements. Additionally, if you are developing using Android Studio, you can enable auto-import or use the keyboard shortcut Ctrl+Space (Cmd+Space) to add the required
import
statements.
As you work through the examples in this book, you may choose either to type in all the code manually, or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com. When at the site, simply locate the book’s title (use the Search box or one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.
Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
A background of mobile application development
What is Android?
Which devices Android runs on
Why you should develop for mobile and Android
An introduction to the Android SDK and development framework
Whether you’re an experienced mobile engineer, a desktop or web developer, or a complete programming novice, Android represents an exciting opportunity to write applications for an audience of over two billion Android device users.
You’re probably already familiar with Android, the most common software powering mobile phones. If not, and you purchased this book in the hope that Android development would help you create an unstoppable army of emotionless robot warriors on a relentless quest to cleanse the earth of the scourge of humanity, you should reconsider this book purchase (and your life choices.)
When announcing Android at its launch in 2007, Andy Rubin described it as follows:
The first truly open and comprehensive platform for mobile devices. It includes an operating system, user-interface and applications—all of the software to run a mobile phone but without the proprietary obstacles that have hindered mobile innovation.
—WHERE’S MY GPHONE?
(http://googleblog.blogspot.com/2007/11/wheres-my-gphone.html)
Since then, Android has expanded beyond mobile phones to provide a development platform for an increasingly wide range of hardware, including tablets, televisions, watches, cars, and Internet-of-Things (IoT) devices.
Android is an open source software stack that includes an operating system, middleware, and key applications for mobile and embedded devices.
Critically, for us as developers, it also includes a rich set of API libraries that make it possible to write applications that can shape the look, feel, and function of the Android devices on which they run.
In Android, system, bundled, and all third-party applications are written with the same APIs and executed on the same run time. These APIs feature hardware access, video recording, location-based services, support for background services, maps, notifications, sensors, relational databases, inter-application communication, Bluetooth, NFC, and 2D and 3D graphics.
This book describes how to use these APIs to create your own Android applications. In this chapter you learn some guidelines for mobile and embedded hardware development, and are introduced to some of the platform features available to Android developers.
Android has powerful APIs, a huge and diverse ecosystem of users, excellent documentation, a thriving developer community, and has no required costs for development or distribution. As the Android device ecosystem continues to grow, you have the opportunity to create innovative applications for users, no matter what your development experience.
In the days before Instagram, Snapchat, and Pokémon Go, when Google was still a twinkle in its founders’ eyes and dinosaurs roamed the earth, mobile phones were just that—portable phones small enough to fit inside a briefcase, featuring batteries that could last up to several hours. They did, however, offer the freedom to make calls without being physically connected to a landline.
In the 10 years since the first Android device was launched, smart phones have become ubiquitous and indispensable. Hardware advancements have made devices more powerful, featuring bigger, brighter screens and featuring advanced hardware including accelerometers, fingerprint scanners, and ultra-high-resolution cameras.
These same advances have more recently resulted in a proliferation of additional form factors for Android devices, including a large variety of smart-phones, tablets, watches, and televisions.
These hardware innovations offer fertile ground for software development, providing many opportunities to create innovative new applications.
In the early days of native phone application development, developers, generally coding in low-level C or C++, needed to understand the specific hardware they were coding for, typically a single device or possibly a range of devices from a single manufacturer. The complexity inherent in this approach meant the applications written for these devices often lagged behind their hardware counterparts. As hardware technology and mobile Internet access have advanced, this closed approach has become outmoded.
The next significant advancement in mobile phone application development was the introduction of Java-hosted MIDlets. MIDlets were executed on a Java virtual machine (JVM), a process that abstracted the underlying hardware and let developers create applications that ran on many devices that supported the Java run time.
Unfortunately, this convenience came at the price of more heavily restricted access to the device hardware. Similarly, it was considered normal for third-party applications to receive different hardware access and execution rights from those given to native applications written by the phone manufacturers, with MIDlets often receiving few of either.
The introduction of Java MIDlets expanded developers’ audiences, but the lack of low-level hardware access and sandboxed execution meant that most mobile applications were regular desktop programs or websites designed to render on a smaller screen, and didn’t take advantage of the inherent mobility of the handheld platform.
At its introduction, Android was part of a new wave of modern mobile operating systems designed specifically to support application development on increasingly powerful mobile hardware.
Android offers an open development platform built on an open source Linux kernel. Hardware access is available to all applications through a series of API libraries, and application interaction, while carefully controlled, is fully supported.
In Android, all applications have equal standing. Third-party and native Android applications are written with the same APIs and are executed on the same run time. Users can replace most system application with a third-party developer’s alternative; indeed, even the dialer and home screens can be replaced.
The Android ecosystem is made up of a combination of three components:
A free, open source operating system for embedded devices
An open source development platform for creating applications
Devices that run the Android operating system (and the applications created for it)
More specifically, Android is made up of several necessary and dependent parts, including the following:
A Compatibility Definition Document (CDD) and Compatibility Test Suite (CTS) that describe the capabilities required for a device to support the Android software stack.
A Linux operating system kernel that provides a low-level interface with the hardware, memory management, and process control, all optimized for mobile and embedded devices.
Open source libraries for application development, including SQLite, WebKit, OpenGL, and a media manager.
A run time used to execute and host Android applications, including the Android Run Time (ART) and the core libraries that provide Android-specific functionality. The run time is designed to be small and efficient for use on embedded devices.
An application framework that agnostically exposes system services to the application layer, including the Window Manager and Location Manager, databases, telephony, and sensors.
A user interface framework used to host and launch applications.
A set of core preinstalled applications.
A software development kit (SDK) used to create applications, including the related tools, IDE, sample code, and documentation.
What really makes Android compelling is its open philosophy, which ensures that you can fix any deficiencies in user interface or native application design by writing an extension or replacement. Android provides you, as a developer, with the opportunity to create applications designed to look, feel, and function exactly as you imagine them.
With more than 2 billion monthly active users of devices running the Android operating system, installing over 82 billion apps and games in from Google Play in 2016 alone, the Android ecosystem represents an unparalleled chance to create apps that can affect and improve billions of people’s lives.
Android devices typically come with a suite of preinstalled applications that users expect. On smart phones these typically include:
A phone dialer
An SMS management application
A web browser
An e-mail client
A calendar
A contacts list
A music player and picture gallery
A camera and video recording application
A calculator
A home screen
An alarm clock
In many cases Android devices also ship with the following proprietary Google mobile applications:
The Google Play Store for downloading third-party Android applications
The Google Maps application, including StreetView, driving directions, and turn-by-turn navigation, satellite views, and traffic conditions
The Gmail email client
The YouTube video player
The Google Chrome browser
The Google home screen and Google Assistant
The data stored and used by many of these native applications—such as contact details—are also available to third-party applications.
The exact makeup of the applications available on new Android devices is likely to vary based on the hardware manufacturer, the carrier or distributor, and the type of device.
The open source nature of Android means that carriers and OEMs can customize the user interface and the applications bundled with each Android device.
It’s important to note that for compatible devices, the underlying platform and SDK remains consistent across OEM and carrier variations. The look and feel of the user interface may vary, but your applications will function in the same way across all compatible Android devices.
For us developers, the true appeal of Android lies in its APIs.
As an application-neutral platform, Android gives you the opportunity to create applications that are as much a part of the phone as anything provided out-of-the-box. The following list highlights some of the most noteworthy Android features:
Transparent access to telephony and Internet resources through GSM, EDGE, 3G, 4G, LTE, and Wi-Fi network support, enabling your app to send and retrieve data across mobile and Wi-Fi networks
Comprehensive APIs for location-based services such as GPS and network-based location detection
Full support for integrating maps within the user interface
Full multimedia hardware control, including playback and recording with the camera and microphone
Media libraries for playing and recording a variety of audio/video or still-image formats
APIs for using sensor hardware, including accelerometers, compasses, barometers, and fingerprint sensors
Libraries for using Wi-Fi, Bluetooth, and NFC hardware
Shared data stores and APIs for contacts, calendar, and multi-media
Background services and an advanced notification system
An integrated web browser
Mobile-optimized, hardware-accelerated graphics, including a path-based 2D graphics library and support for 3D graphics using OpenGL ES 2.0
Localization through a dynamic resource framework
The first Android mobile handset, the T-Mobile G1, was released in the United States in October 2008. By the end of 2017 there are more than 2 billion monthly active Android devices globally, making it the most common smart phone operating system in use world-wide.
Rather than being a mobile OS created for a single hardware implementation, Android is designed to support a large variety of hardware platforms, from smart phones to tablets, televisions, watches, and IoT devices.
With no licensing fees or proprietary software, the cost to handset manufacturers for providing Android devices is comparatively low, which, combined with a massive ecosystem of powerful applications, has encouraged device manufacturers to produce increasingly diverse and tailored hardware.
As a result, hundreds of manufacturers, including Samsung, LG, HTC, and Motorola, are creating Android devices. These devices are distributed to users via hundreds of carriers world-wide.
Smart phones have become so advanced and personal to us that for many people they’ve become an extension of themselves. Studies have shown that many mobile phone users become anxious if they misplace their device, lose connectivity, or their battery runs out.
The ubiquity of mobile phones, and our attachment to them, makes them a fundamentally different platform for development from PCs. With a microphone, camera, touchscreen, location detection, and environmental sensors, a phone can effectively become an extra-sensory perception device.
Smart phone ownership easily surpasses computer ownership in many countries, with more than 3 billion mobile phone users worldwide. 2009 marked the year that more people accessed the Internet for the first time from a mobile phone rather than a PC.
The increasing popularity of smart phones, combined with the increasing availability of high-speed mobile data and Wi-Fi hotspots, has created a huge opportunity for advanced mobile applications.
Smartphone applications have changed the way people use their phones. This gives you, the application developer, a unique opportunity to create dynamic, compelling new applications that become a vital part of people’s lives.
In addition to providing access to the largest ecosystem of smart phone users, Android represents a dynamic framework for app development based on the reality of modern mobile devices designed by developers, for developers.
With a simple, powerful, and open SDK, no licensing fees, excellent documentation, a diverse range of devices and form-factors, and a thriving developer community, Android represents an opportunity to create software that can change people’s lives.
The barrier to entry for new Android developers is minimal:
No certification is required to become an Android developer.
The Google Play Store provides free, up-front purchase, in-app billing, and subscription options for distribution and monetization of your applications.
There is no approval process for application distribution.
Developers have total control over their brands.
From a commercial perspective, Android represents the most common smart phone operating system, and provides access to over 2 billion monthly active Android devices globally, offering unparalleled reach to make your applications available to users around the world.
Android applications normally are written using the Java or Kotlin programming languages, and are executed by means of the Android Run Time (ART).
Historically, Android apps were written primarily using Java language syntax. More recently, Android Studio 3.0 introduced full support for Kotlin as an official first class language for application development. Kotlin is a JVM language, which is interoperable with existing Android languages and the Android Run Time, allowing you to use both Java and Kotlin syntax within the same applications.
Each Android application runs in a separate process, relinquishing all responsibility for memory and process management to the Android Run Time, which stops and kills processes as necessary to manage resources.
ART sits on top of a Linux kernel that handles low-level hardware interaction, including drivers and memory management, while a set of APIs provides access to all the underlying services, features, and hardware.
The Android SDK includes everything you need to start developing, testing, and debugging Android applications:
The Android API Libraries
—The core of the SDK is the Android API libraries that provide developer access to the Android stack. These are the same libraries that Google uses to create native Android applications.
Development tools
—The SDK includes the Android Studio IDE and several other development tools that let you compile and debug your applications to turn Android source code into executable applications. You learn more about the developer tools in
Chapter 2
, “Getting Started.”
The Android Virtual Device Manager and Emulator
—The Android Emulator is a fully interactive mobile device emulator featuring several alternative skins. The Emulator runs within an Android Virtual Device (AVD) that simulates a device hardware configuration. Using the Emulator you can see how your applications will look and behave on a real Android device. All Android applications run within ART, so the software emulator is an excellent development environment—in fact, because it’s hardware-neutral, it provides a better independent test environment than any single hardware implementation.
Full documentation
—The SDK includes extensive code-level reference information detailing exactly what’s included in each package and class and how to use them. In addition to the code documentation, Android’s reference documentation and developer guides explain how to get started, give detailed explanations of the fundamentals behind Android development, highlight best practices, and provide deep-dives into framework topics.
Sample code
—The Android SDK includes a selection of sample applications that demonstrate some of the possibilities available with Android, as well as simple programs that highlight how to use individual API features.
Online support
—Android has vibrant developer communities on most online social networks, Slack, and many developer forums. Stack Overflow (
www.stackoverflow.com/questions/tagged/android
) is a hugely popular destination for Android questions and a great place to find answers to beginner questions. Many Android engineers from Google are active on Stack Overflow and Twitter.
The Android software stack is a Linux kernel and a collection of C/C++ libraries exposed through an application framework that provides services for, and management of, the run time and applications, as shown in Figure 1-1.
FIGURE 1-1
Linux kernel
—Core services (including hardware drivers, process and memory management, security, network, and power management) are handled by a Linux kernel (the specific kernel version depends on the Android platform version and hardware platform).
Hardware Application Layer (HAL)
—The HAL provides an abstraction layer between the underlying physical device hardware and the remainder of the stack.
Libraries
—Running on top of the kernel and HAL, Android includes various C/C++ core libraries such as libc and SSL, as well as the following:
A media library for playback of audio and video media
A surface manager to provide display management
Graphics libraries that include SGL and OpenGL for 2D and 3D graphics
SQLite for native database support
SSL and WebKit for integrated web browser and Internet security
Android Run Time
—The run time is what makes an Android phone an Android phone rather than a mobile Linux implementation. Including the core libraries, the Android Run Time is the engine that powers your applications and forms the basis for the application framework.
Core libraries
—Although most Android application development is written using the Java or Kotlin JVM languages, ART is not a Java VM. The core Android libraries provide most of the functionality available in the core Java libraries, as well as the Android-specific libraries.
Application framework
—The application framework provides the classes used to create Android applications. It also provides a generic abstraction for hardware access and manages the user interface and application resources.
Application layer
—All applications, both native and third-party, are built on the application layer by means of the same API libraries. The application layer runs within the Android Run Time, using the classes and services made available from the application framework.
One of the key elements of Android is the Android Run Time (ART). Rather than using a traditional Java VM such as Java ME, Android uses its own custom run time designed to ensure that multiple instances run efficiently on a single device.
ART uses the device’s underlying Linux kernel to handle low-level functionality, including security, threading, and process and memory management. It’s also possible to write C/C++ applications that run closer to the underlying Linux OS. Although you can do this, in most cases there’s no reason you should need to.
If the speed and efficiency of C/C++ is required for your application, Android provides a native development kit (NDK). The NDK is designed to enable you to create C++ libraries using the libc and libm libraries, along with native access to OpenGL.
This book focuses exclusively on writing applications that run within ART using the SDK; NDK development is not within the scope of this book. If your inclinations run toward NDK development, exploring the Linux kernel and C/C++ underbelly of Android, modifying ART, or otherwise tinkering with things under the hood, check out the Android Open Source Project at source.android.com.
All Android hardware and system service access is managed using ART as a middle tier. By using this run time to host application execution, developers have an abstraction layer that ensures they should never have to worry about a particular hardware implementation.
ART executes Dalvik executable files (.dex)—named after an earlier virtual machine implementation named “Dalvik”—a format optimized to ensure minimal memory footprint. You create .dex executables by transforming Java or Kotlin language compiled classes using the tools supplied within the SDK.
You learn more about how to create Dalvik executables in Chapter 2.
Android’s architecture encourages component reuse, enabling you to publish and share Activities, Services, and data with other applications, with access managed by the security restrictions you define.
The same mechanism that enables you to produce a replacement contact manager or phone dialer can let you expose your application’s components in order to let other developers build on them by creating new UI front ends or functionality extensions.
The following application services are the architectural cornerstones of all Android applications, providing the framework you’ll be using for your own software:
Activity Manager and Fragment Manager
—Activities and Fragments are used to define the user interface of your apps. The Activity and Fragment Managers control the life cycle of your Activities and Fragments, respectively, including management of the Activity stack (described in
Chapters 3
and
5
).
Views
—Used to construct the user interfaces controls within your Activities and Fragments, as described in
Chapter 5
.
Notification Manager
—Provides a consistent and nonintrusive mechanism for signaling your users, as described in
Chapter 11
.
Content Providers
—Lets your applications share data, as described in
Chapter 10
.
Resource Manager
—Enables non-code resources, such as strings and graphics, to be externalized, as shown in
Chapter 4
.
Intents
—Provides a mechanism for transferring data between applications and their components, as described in
Chapter 6
.
Android offers a number of APIs for developing your applications. Rather than list them all here, check out the documentation at developer.android.com/reference/packages.html, which gives a complete list of packages included in the Android SDK.
Android is intended to target a wide range of mobile hardware, so be aware that the suitability and implementation of some of the advanced or optional APIs may vary depending on the host device.
Installing the Android SDK and Android Studio development environment
Creating and debugging your projects
Writing Android apps using Kotlin
Using the Android Support Library
Understanding mobile design considerations
The importance of optimizing for speed and efficiency
Designing for small screens and mobile data connections
Introducing Android Virtual Devices and the Emulator
Tips for using Android Studio and improving build performance
Understanding app performance using the Android Profiler
Introducing Gradle builds and app testing
The downloads for this chapter are found at www.wrox.com. The code for this chapter is divided into the following major examples:
Snippets_ch2.zip
HelloWorld.zip
All you need to start writing your own Android applications is a copy of the Android SDK and a Java Development Kit (JDK). Unless you’re a masochist, you’ll also want to use an integrated development environment (IDE)—we strongly recommend using Android Studio, Google’s officially supported IDE for Android app development that includes an integrated JDK and manages the installation of the Android SDK and associated tools.
Android Studio, the Android SDK, and a JDK are each available for Windows, MacOS, and Linux, so you can explore Android from the comfort of whatever operating system (OS) you favor. Android applications themselves are run within the ART managed runtime, optimized for resource-constrained mobile devices, so there’s no advantage to developing on any particular OS.
Traditionally, Android code is written using Java language syntax—until 2017 Android app development required the use of Java. Android Studio 3.0 added Kotlin as a fully supported language alternative, allowing you to write Android app in part, or entirely, using Kotlin.
Kotlin is a statically typed language that is fully interoperable with Java source files and the Android runtime. It’s considered expressive and concise and introduces improvements including reduced language verbosity, null-pointer safety, extension functions, and infix notation.
At the time of writing this book Java was still the default for new projects, and most existing Android projects were written predominantly using Java syntax. Accordingly, we’ve used Java syntax for the code snippets and sample projects featured within this book.
Given the advantages of Kotlin, we expect its use to increase quickly, and highly recommend you familiarize yourself with the Kotlin language for writing Android apps. More details on using Kotlin for your Android Apps are available in the aptly named section, “Getting Started Writing Android Apps Using Kotlin.”
The core Android libraries include most of the features from the core Java APIs in addition to the rich suite of Android-specific APIs. You can access all these libraries using either Java or Kotlin when writing your apps.
Although it’s possible to download and install the Android SDK and JDK separately, installing and using Android Studio simplifies the process of getting started. Android Studio includes an integrated OpenJDK and manages the installation of the Android SDK components and tools using the integrated Android SDK Manager.
The SDK Manager is used to download Android framework SDK libraries and optional add-ons (including the Google APIs and support libraries). It also includes the platform and development tools you will use to write and debug your applications, such as the Android Emulator to run your projects and the Android Profiler to profile CPU, memory, and network use. All these tools are integrated directly into Android Studio for your convenience.
By the end of this chapter, you’ll have installed Android Studio, the Android SDK and its add-ons, and the development tools. You’ll have set up your development environment, built your first Hello World application in Java and Kotlin, and run and debugged it using the DDMS and Emulator running on an Android Virtual Device (AVD).
If you’ve developed for mobile devices before, you already know that their small form factor, limited battery life, and restricted processing power and memory create some unique design challenges. Even if you’re new to the game, it’s obvious that some of the things you can take for granted on the desktop, web, or server—such as always-on Internet and power—aren’t applicable when writing apps for mobile or embedded devices.
The user environment brings its own challenges in addition to those introduced by hardware limitations. Many Android devices are used on the move and are often a distraction rather than the focus of attention, so your application needs to be fast, responsive, and easy to learn. Even if your application is designed for devices more conducive to an immersive experience, such as tablets or televisions, the same design principles can be critical for delivering a high-quality user experience.
The Android SDK includes all the tools and APIs you need to write compelling and powerful mobile applications. The biggest challenge with Android, as with any new development toolkit, is learning the features and limitations of those APIs.
Since Android Studio 3.0, it’s possible to write Android apps using Java, Kotlin, or a combination of both languages. If you have experience in Java or Kotlin development, you’ll find that the syntax and grammar you’ve been using will translate directly into Android. If you don’t have experience with Java, but have used other object-oriented languages (such as C#), you should find the transition to either Java or Kotlin syntax straightforward.