-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservices.html
More file actions
837 lines (787 loc) · 90.6 KB
/
services.html
File metadata and controls
837 lines (787 loc) · 90.6 KB
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
198
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
434
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
464
465
466
467
468
469
470
471
472
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
508
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Android Development: Lecture Notes</title>
<meta name="description" content="Lecture Notes for INFO 448: Android Development.">
<meta name="generator" content="bookdown 0.5 and GitBook 2.6.7">
<meta property="og:title" content="Android Development: Lecture Notes" />
<meta property="og:type" content="book" />
<meta property="og:url" content="https://info448.github.io/" />
<meta property="og:image" content="https://info448.github.io/img/android_icon_transparent.png" />
<meta property="og:description" content="Lecture Notes for INFO 448: Android Development." />
<meta name="github-repo" content="info448/book" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Android Development: Lecture Notes" />
<meta name="twitter:description" content="Lecture Notes for INFO 448: Android Development." />
<meta name="twitter:image" content="https://info448.github.io/img/android_icon_transparent.png" />
<meta name="author" content="Joel Ross">
<meta name="date" content="2018-11-19">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="img/android_icon_transparent.png" type="image/x-icon">
<link rel="prev" href="location.html">
<link rel="next" href="sensors.html">
<script src="libs/jquery-2.2.3/jquery.min.js"></script>
<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-98444716-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; } /* Keyword */
code > span.dt { color: #902000; } /* DataType */
code > span.dv { color: #40a070; } /* DecVal */
code > span.bn { color: #40a070; } /* BaseN */
code > span.fl { color: #40a070; } /* Float */
code > span.ch { color: #4070a0; } /* Char */
code > span.st { color: #4070a0; } /* String */
code > span.co { color: #60a0b0; font-style: italic; } /* Comment */
code > span.ot { color: #007020; } /* Other */
code > span.al { color: #ff0000; font-weight: bold; } /* Alert */
code > span.fu { color: #06287e; } /* Function */
code > span.er { color: #ff0000; font-weight: bold; } /* Error */
code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #880000; } /* Constant */
code > span.sc { color: #4070a0; } /* SpecialChar */
code > span.vs { color: #4070a0; } /* VerbatimString */
code > span.ss { color: #bb6688; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #19177c; } /* Variable */
code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code > span.op { color: #666666; } /* Operator */
code > span.bu { } /* BuiltIn */
code > span.ex { } /* Extension */
code > span.pp { color: #bc7a00; } /* Preprocessor */
code > span.at { color: #7d9029; } /* Attribute */
code > span.do { color: #ba2121; font-style: italic; } /* Documentation */
code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
</style>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="book without-animation with-summary font-size-2 font-family-1" data-basepath=".">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li><a href="./" class="title">Android Development</a></li>
<li class="divider"></li>
<li class="chapter" data-level="" data-path="index.html"><a href="index.html"><i class="fa fa-check"></i>About this Book</a></li>
<li class="part"><span><b>I Lectures</b></span></li>
<li class="chapter" data-level="1" data-path="introduction.html"><a href="introduction.html"><i class="fa fa-check"></i><b>1</b> Introduction</a><ul>
<li class="chapter" data-level="1.1" data-path="introduction.html"><a href="introduction.html#android-history"><i class="fa fa-check"></i><b>1.1</b> Android History</a><ul>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#android-versions"><i class="fa fa-check"></i>Android Versions</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#legal-battles"><i class="fa fa-check"></i>Legal Battles</a></li>
</ul></li>
<li class="chapter" data-level="1.2" data-path="introduction.html"><a href="introduction.html#building-apps"><i class="fa fa-check"></i><b>1.2</b> Building Apps</a><ul>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#creating-a-project"><i class="fa fa-check"></i>Creating a Project</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#running-the-app"><i class="fa fa-check"></i>Running the App</a></li>
</ul></li>
<li class="chapter" data-level="1.3" data-path="introduction.html"><a href="introduction.html#app-source-code"><i class="fa fa-check"></i><b>1.3</b> App Source Code</a><ul>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#xml-resources"><i class="fa fa-check"></i>XML Resources</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#the-manifest"><i class="fa fa-check"></i>The Manifest</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#java-activities"><i class="fa fa-check"></i>Java Activities</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#gradle-scripts"><i class="fa fa-check"></i>Gradle Scripts</a></li>
</ul></li>
<li class="chapter" data-level="1.4" data-path="introduction.html"><a href="introduction.html#logging-adb"><i class="fa fa-check"></i><b>1.4</b> Logging & ADB</a><ul>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#log-methods"><i class="fa fa-check"></i>Log Methods</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#logcat"><i class="fa fa-check"></i>Logcat</a></li>
<li class="chapter" data-level="" data-path="introduction.html"><a href="introduction.html#toast"><i class="fa fa-check"></i>Toast</a></li>
</ul></li>
<li class="chapter" data-level="1.5" data-path="introduction.html"><a href="introduction.html#adding-interaction"><i class="fa fa-check"></i><b>1.5</b> Adding Interaction</a></li>
<li class="chapter" data-level="1.6" data-path="introduction.html"><a href="introduction.html#kotlin-setup"><i class="fa fa-check"></i><b>1.6</b> Kotlin</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html"><i class="fa fa-check"></i><b>2</b> Resources and Layouts</a><ul>
<li class="chapter" data-level="2.1" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#resources"><i class="fa fa-check"></i><b>2.1</b> Resources</a><ul>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#r"><i class="fa fa-check"></i>R</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#alternative-resources"><i class="fa fa-check"></i>Alternative Resources</a></li>
</ul></li>
<li class="chapter" data-level="2.2" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#views"><i class="fa fa-check"></i><b>2.2</b> Views</a><ul>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#view-properties"><i class="fa fa-check"></i>View Properties</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#views-and-java"><i class="fa fa-check"></i>Views and Java</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#practice"><i class="fa fa-check"></i>Practice</a></li>
</ul></li>
<li class="chapter" data-level="2.3" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#layouts"><i class="fa fa-check"></i><b>2.3</b> Layouts</a><ul>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#linearlayout"><i class="fa fa-check"></i>LinearLayout</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#relativelayout"><i class="fa fa-check"></i>RelativeLayout</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#constraintlayout"><i class="fa fa-check"></i>ConstraintLayout</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#other-layouts"><i class="fa fa-check"></i>Other Layouts</a></li>
<li class="chapter" data-level="" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#combining-and-inflating-layouts"><i class="fa fa-check"></i>Combining and Inflating Layouts</a></li>
</ul></li>
<li class="chapter" data-level="2.4" data-path="resources-and-layouts.html"><a href="resources-and-layouts.html#inputs"><i class="fa fa-check"></i><b>2.4</b> Inputs</a></li>
</ul></li>
<li class="chapter" data-level="3" data-path="activities.html"><a href="activities.html"><i class="fa fa-check"></i><b>3</b> Activities</a><ul>
<li class="chapter" data-level="3.1" data-path="activities.html"><a href="activities.html#making-activities"><i class="fa fa-check"></i><b>3.1</b> Making Activities</a></li>
<li class="chapter" data-level="3.2" data-path="activities.html"><a href="activities.html#the-activity-lifecycle"><i class="fa fa-check"></i><b>3.2</b> The Activity Lifecycle</a><ul>
<li class="chapter" data-level="" data-path="activities.html"><a href="activities.html#overriding-the-callback-methods"><i class="fa fa-check"></i>Overriding the Callback Methods</a></li>
<li class="chapter" data-level="" data-path="activities.html"><a href="activities.html#saving-and-restoring-activity-state"><i class="fa fa-check"></i>Saving and Restoring Activity State</a></li>
</ul></li>
<li class="chapter" data-level="3.3" data-path="activities.html"><a href="activities.html#context"><i class="fa fa-check"></i><b>3.3</b> Context</a></li>
<li class="chapter" data-level="3.4" data-path="activities.html"><a href="activities.html#multiple-activities"><i class="fa fa-check"></i><b>3.4</b> Multiple Activities</a><ul>
<li class="chapter" data-level="" data-path="activities.html"><a href="activities.html#activity-intents"><i class="fa fa-check"></i>Intents</a></li>
<li class="chapter" data-level="" data-path="activities.html"><a href="activities.html#back-tasks"><i class="fa fa-check"></i>Back & Tasks</a></li>
<li class="chapter" data-level="" data-path="activities.html"><a href="activities.html#up-navigation"><i class="fa fa-check"></i>Up Navigation</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="4" data-path="data-views.html"><a href="data-views.html"><i class="fa fa-check"></i><b>4</b> Data-Driven Views</a><ul>
<li class="chapter" data-level="4.1" data-path="data-views.html"><a href="data-views.html#listviews-and-adapters"><i class="fa fa-check"></i><b>4.1</b> ListViews and Adapters</a></li>
<li class="chapter" data-level="4.2" data-path="data-views.html"><a href="data-views.html#networking-with-volley"><i class="fa fa-check"></i><b>4.2</b> Networking with Volley</a><ul>
<li class="chapter" data-level="" data-path="data-views.html"><a href="data-views.html#using-volley"><i class="fa fa-check"></i>Using Volley</a></li>
<li class="chapter" data-level="" data-path="data-views.html"><a href="data-views.html#requestqueue-singletons"><i class="fa fa-check"></i>RequestQueue Singletons</a></li>
<li class="chapter" data-level="" data-path="data-views.html"><a href="data-views.html#downloading-images"><i class="fa fa-check"></i>Downloading Images</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="5" data-path="material-design.html"><a href="material-design.html"><i class="fa fa-check"></i><b>5</b> Material Design</a><ul>
<li class="chapter" data-level="5.1" data-path="material-design.html"><a href="material-design.html#the-material-design-language"><i class="fa fa-check"></i><b>5.1</b> The Material Design Language</a></li>
<li class="chapter" data-level="5.2" data-path="material-design.html"><a href="material-design.html#material-styles-icons"><i class="fa fa-check"></i><b>5.2</b> Material Styles & Icons</a></li>
<li class="chapter" data-level="5.3" data-path="material-design.html"><a href="material-design.html#design-support-libraries"><i class="fa fa-check"></i><b>5.3</b> Design Support Libraries</a><ul>
<li class="chapter" data-level="" data-path="material-design.html"><a href="material-design.html#widgets"><i class="fa fa-check"></i>Widgets</a></li>
<li class="chapter" data-level="" data-path="material-design.html"><a href="material-design.html#coordinator-layout"><i class="fa fa-check"></i>Coordinator Layout</a></li>
</ul></li>
<li class="chapter" data-level="5.4" data-path="material-design.html"><a href="material-design.html#animations"><i class="fa fa-check"></i><b>5.4</b> Animations</a></li>
<li class="chapter" data-level="" data-path="material-design.html"><a href="material-design.html#resources-1"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="6" data-path="fragments.html"><a href="fragments.html"><i class="fa fa-check"></i><b>6</b> Fragments</a><ul>
<li class="chapter" data-level="6.1" data-path="fragments.html"><a href="fragments.html#creating-a-fragment"><i class="fa fa-check"></i><b>6.1</b> Creating a Fragment</a><ul>
<li class="chapter" data-level="" data-path="fragments.html"><a href="fragments.html#activity-to-fragment-communication"><i class="fa fa-check"></i>Activity-to-Fragment Communication</a></li>
</ul></li>
<li class="chapter" data-level="6.2" data-path="fragments.html"><a href="fragments.html#dynamic-fragments"><i class="fa fa-check"></i><b>6.2</b> Dynamic Fragments</a><ul>
<li class="chapter" data-level="" data-path="fragments.html"><a href="fragments.html#instantiating-fragments"><i class="fa fa-check"></i>Instantiating Fragments</a></li>
<li class="chapter" data-level="" data-path="fragments.html"><a href="fragments.html#transactions"><i class="fa fa-check"></i>Transactions</a></li>
<li class="chapter" data-level="" data-path="fragments.html"><a href="fragments.html#inter-fragment-communication"><i class="fa fa-check"></i>Inter-Fragment Communication</a></li>
<li class="chapter" data-level="" data-path="fragments.html"><a href="fragments.html#the-back-stack"><i class="fa fa-check"></i>The Back Stack</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="7" data-path="intents.html"><a href="intents.html"><i class="fa fa-check"></i><b>7</b> Intents</a><ul>
<li class="chapter" data-level="7.1" data-path="intents.html"><a href="intents.html#intents-for-another-activity-explicit"><i class="fa fa-check"></i><b>7.1</b> Intents for Another Activity (Explicit)</a><ul>
<li class="chapter" data-level="" data-path="intents.html"><a href="intents.html#extras"><i class="fa fa-check"></i>Extras</a></li>
</ul></li>
<li class="chapter" data-level="7.2" data-path="intents.html"><a href="intents.html#intents-for-another-app-implicit"><i class="fa fa-check"></i><b>7.2</b> Intents for Another App (Implicit)</a></li>
<li class="chapter" data-level="7.3" data-path="intents.html"><a href="intents.html#intents-for-a-response"><i class="fa fa-check"></i><b>7.3</b> Intents for a Response</a></li>
<li class="chapter" data-level="7.4" data-path="intents.html"><a href="intents.html#listening-for-intents"><i class="fa fa-check"></i><b>7.4</b> Listening for Intents</a></li>
<li class="chapter" data-level="7.5" data-path="intents.html"><a href="intents.html#broadcasts-and-receivers"><i class="fa fa-check"></i><b>7.5</b> Broadcasts and Receivers</a></li>
<li class="chapter" data-level="7.6" data-path="intents.html"><a href="intents.html#menus"><i class="fa fa-check"></i><b>7.6</b> Menus</a><ul>
<li class="chapter" data-level="" data-path="intents.html"><a href="intents.html#action-views"><i class="fa fa-check"></i>Action Views</a></li>
<li class="chapter" data-level="" data-path="intents.html"><a href="intents.html#context-menus"><i class="fa fa-check"></i>Context Menus</a></li>
</ul></li>
<li class="chapter" data-level="7.7" data-path="intents.html"><a href="intents.html#an-intent-example-sms"><i class="fa fa-check"></i><b>7.7</b> An Intent Example: SMS</a></li>
</ul></li>
<li class="chapter" data-level="8" data-path="notifications-settings.html"><a href="notifications-settings.html"><i class="fa fa-check"></i><b>8</b> Notifications & Settings</a><ul>
<li class="chapter" data-level="8.1" data-path="notifications-settings.html"><a href="notifications-settings.html#dialogs"><i class="fa fa-check"></i><b>8.1</b> Dialogs</a><ul>
<li class="chapter" data-level="" data-path="notifications-settings.html"><a href="notifications-settings.html#dialogfragments"><i class="fa fa-check"></i>DialogFragments</a></li>
</ul></li>
<li class="chapter" data-level="8.2" data-path="notifications-settings.html"><a href="notifications-settings.html#notifications"><i class="fa fa-check"></i><b>8.2</b> Notifications</a><ul>
<li class="chapter" data-level="8.2.1" data-path="notifications-settings.html"><a href="notifications-settings.html#tap-actions"><i class="fa fa-check"></i><b>8.2.1</b> Tap Actions</a></li>
</ul></li>
<li class="chapter" data-level="8.3" data-path="notifications-settings.html"><a href="notifications-settings.html#settings"><i class="fa fa-check"></i><b>8.3</b> Settings</a><ul>
<li class="chapter" data-level="" data-path="notifications-settings.html"><a href="notifications-settings.html#sharedpreferences"><i class="fa fa-check"></i>SharedPreferences</a></li>
<li class="chapter" data-level="" data-path="notifications-settings.html"><a href="notifications-settings.html#preference-settings"><i class="fa fa-check"></i>Preference Settings</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="9" data-path="loaders.html"><a href="loaders.html"><i class="fa fa-check"></i><b>9</b> Providers and Loaders</a><ul>
<li class="chapter" data-level="9.1" data-path="loaders.html"><a href="loaders.html#content-providers-intro"><i class="fa fa-check"></i><b>9.1</b> Content Providers</a></li>
<li class="chapter" data-level="9.2" data-path="loaders.html"><a href="loaders.html#cursors"><i class="fa fa-check"></i><b>9.2</b> Cursors</a></li>
<li class="chapter" data-level="9.3" data-path="loaders.html"><a href="loaders.html#loaders"><i class="fa fa-check"></i><b>9.3</b> Loaders</a></li>
<li class="chapter" data-level="9.4" data-path="loaders.html"><a href="loaders.html#other-provider-actions"><i class="fa fa-check"></i><b>9.4</b> Other Provider Actions</a></li>
</ul></li>
<li class="chapter" data-level="10" data-path="files-and-permissions.html"><a href="files-and-permissions.html"><i class="fa fa-check"></i><b>10</b> Files and Permissions</a><ul>
<li class="chapter" data-level="10.1" data-path="files-and-permissions.html"><a href="files-and-permissions.html#file-storage-locations"><i class="fa fa-check"></i><b>10.1</b> File Storage Locations</a></li>
<li class="chapter" data-level="10.2" data-path="files-and-permissions.html"><a href="files-and-permissions.html#permissions"><i class="fa fa-check"></i><b>10.2</b> Permissions</a></li>
<li class="chapter" data-level="10.3" data-path="files-and-permissions.html"><a href="files-and-permissions.html#external-storage"><i class="fa fa-check"></i><b>10.3</b> External Storage</a></li>
<li class="chapter" data-level="10.4" data-path="files-and-permissions.html"><a href="files-and-permissions.html#internal-storage-cache"><i class="fa fa-check"></i><b>10.4</b> Internal Storage & Cache</a></li>
<li class="chapter" data-level="10.5" data-path="files-and-permissions.html"><a href="files-and-permissions.html#example-saving-pictures"><i class="fa fa-check"></i><b>10.5</b> Example: Saving Pictures</a><ul>
<li class="chapter" data-level="10.5.1" data-path="files-and-permissions.html"><a href="files-and-permissions.html#fileproviders"><i class="fa fa-check"></i><b>10.5.1</b> FileProviders</a></li>
</ul></li>
<li class="chapter" data-level="10.6" data-path="files-and-permissions.html"><a href="files-and-permissions.html#sharing-files"><i class="fa fa-check"></i><b>10.6</b> Sharing Files</a></li>
</ul></li>
<li class="chapter" data-level="11" data-path="databases.html"><a href="databases.html"><i class="fa fa-check"></i><b>11</b> Providers and Databases</a><ul>
<li class="chapter" data-level="11.1" data-path="databases.html"><a href="databases.html#review-providers-and-loaders"><i class="fa fa-check"></i><b>11.1</b> Review: Providers and Loaders</a></li>
<li class="chapter" data-level="11.2" data-path="databases.html"><a href="databases.html#sqlite-databases"><i class="fa fa-check"></i><b>11.2</b> SQLite Databases</a></li>
<li class="chapter" data-level="11.3" data-path="databases.html"><a href="databases.html#implementing-a-contentprovider"><i class="fa fa-check"></i><b>11.3</b> Implementing a ContentProvider</a><ul>
<li class="chapter" data-level="" data-path="databases.html"><a href="databases.html#uris-and-types"><i class="fa fa-check"></i>URIs and Types</a></li>
<li class="chapter" data-level="" data-path="databases.html"><a href="databases.html#query-methods"><i class="fa fa-check"></i>Query Methods</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="12" data-path="location.html"><a href="location.html"><i class="fa fa-check"></i><b>12</b> Location</a><ul>
<li class="chapter" data-level="12.1" data-path="location.html"><a href="location.html#localization-techniques"><i class="fa fa-check"></i><b>12.1</b> Localization Techniques</a><ul>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#gps"><i class="fa fa-check"></i>GPS</a></li>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#cell-tower-localization"><i class="fa fa-check"></i>Cell Tower Localization</a></li>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#wifi-localization"><i class="fa fa-check"></i>WiFi Localization</a></li>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#representing-location"><i class="fa fa-check"></i>Representing Location</a></li>
</ul></li>
<li class="chapter" data-level="12.2" data-path="location.html"><a href="location.html#android-location"><i class="fa fa-check"></i><b>12.2</b> Android Location</a><ul>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#google-play-services"><i class="fa fa-check"></i>Google Play Services</a></li>
<li class="chapter" data-level="" data-path="location.html"><a href="location.html#accessing-location"><i class="fa fa-check"></i>Accessing Location</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="13" data-path="services.html"><a href="services.html"><i class="fa fa-check"></i><b>13</b> Threads and Services</a><ul>
<li class="chapter" data-level="13.1" data-path="services.html"><a href="services.html#threads-and-processes"><i class="fa fa-check"></i><b>13.1</b> Threads and Processes</a><ul>
<li class="chapter" data-level="" data-path="services.html"><a href="services.html#java-threads"><i class="fa fa-check"></i>Java Threads</a></li>
<li class="chapter" data-level="" data-path="services.html"><a href="services.html#android-threads"><i class="fa fa-check"></i>Android Threads</a></li>
</ul></li>
<li class="chapter" data-level="13.2" data-path="services.html"><a href="services.html#intentservices"><i class="fa fa-check"></i><b>13.2</b> IntentServices</a><ul>
<li class="chapter" data-level="" data-path="services.html"><a href="services.html#the-service-lifecycle"><i class="fa fa-check"></i>The Service Lifecycle</a></li>
</ul></li>
<li class="chapter" data-level="13.3" data-path="services.html"><a href="services.html#example-a-music-service"><i class="fa fa-check"></i><b>13.3</b> Example: A Music Service</a><ul>
<li class="chapter" data-level="" data-path="services.html"><a href="services.html#mediaplayer"><i class="fa fa-check"></i>MediaPlayer</a></li>
<li class="chapter" data-level="" data-path="services.html"><a href="services.html#creating-a-service"><i class="fa fa-check"></i>Creating a Service</a></li>
</ul></li>
<li class="chapter" data-level="13.4" data-path="services.html"><a href="services.html#foreground-services"><i class="fa fa-check"></i><b>13.4</b> Foreground Services</a></li>
<li class="chapter" data-level="13.5" data-path="services.html"><a href="services.html#bound-services"><i class="fa fa-check"></i><b>13.5</b> Bound Services</a></li>
</ul></li>
<li class="chapter" data-level="14" data-path="sensors.html"><a href="sensors.html"><i class="fa fa-check"></i><b>14</b> Sensors</a><ul>
<li class="chapter" data-level="14.1" data-path="sensors.html"><a href="sensors.html#motion-sensors"><i class="fa fa-check"></i><b>14.1</b> Motion Sensors</a><ul>
<li class="chapter" data-level="" data-path="sensors.html"><a href="sensors.html#accessing-sensors"><i class="fa fa-check"></i>Accessing Sensors</a></li>
<li class="chapter" data-level="" data-path="sensors.html"><a href="sensors.html#composite-sensors"><i class="fa fa-check"></i>Composite Sensors</a></li>
</ul></li>
<li class="chapter" data-level="14.2" data-path="sensors.html"><a href="sensors.html#rotation"><i class="fa fa-check"></i><b>14.2</b> Rotation</a><ul>
<li class="chapter" data-level="" data-path="sensors.html"><a href="sensors.html#coordinates"><i class="fa fa-check"></i>Coordinates</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="15" data-path="graphics.html"><a href="graphics.html"><i class="fa fa-check"></i><b>15</b> Graphics and Touch</a><ul>
<li class="chapter" data-level="15.1" data-path="graphics.html"><a href="graphics.html#drawing-graphics"><i class="fa fa-check"></i><b>15.1</b> Drawing Graphics</a><ul>
<li class="chapter" data-level="" data-path="graphics.html"><a href="graphics.html#custom-views"><i class="fa fa-check"></i>Custom Views</a></li>
<li class="chapter" data-level="" data-path="graphics.html"><a href="graphics.html#surfaceviews"><i class="fa fa-check"></i>SurfaceViews</a></li>
</ul></li>
<li class="chapter" data-level="15.2" data-path="graphics.html"><a href="graphics.html#touch-and-gestures"><i class="fa fa-check"></i><b>15.2</b> Touch and Gestures</a><ul>
<li class="chapter" data-level="" data-path="graphics.html"><a href="graphics.html#advanced-gestures"><i class="fa fa-check"></i>Advanced Gestures</a></li>
</ul></li>
<li class="chapter" data-level="15.3" data-path="graphics.html"><a href="graphics.html#property-animation"><i class="fa fa-check"></i><b>15.3</b> Property Animation</a></li>
</ul></li>
<li class="part"><span><b>II Additional Topics (Labs)</b></span></li>
<li class="chapter" data-level="16" data-path="styles-themes.html"><a href="styles-themes.html"><i class="fa fa-check"></i><b>16</b> Styles & Themes</a><ul>
<li class="chapter" data-level="16.1" data-path="styles-themes.html"><a href="styles-themes.html#defining-styles"><i class="fa fa-check"></i><b>16.1</b> Defining Styles</a><ul>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#style-inheritance"><i class="fa fa-check"></i>Style Inheritance</a></li>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#built-in-styles"><i class="fa fa-check"></i>Built-in Styles</a></li>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#styles-for-text-views"><i class="fa fa-check"></i>Styles for Text Views</a></li>
</ul></li>
<li class="chapter" data-level="16.2" data-path="styles-themes.html"><a href="styles-themes.html#themes"><i class="fa fa-check"></i><b>16.2</b> Themes</a><ul>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#material-themes"><i class="fa fa-check"></i>Material Themes</a></li>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#theme-attributes"><i class="fa fa-check"></i>Theme Attributes</a></li>
</ul></li>
<li class="chapter" data-level="" data-path="styles-themes.html"><a href="styles-themes.html#resources-2"><i class="fa fa-check"></i>Resources</a></li>
</ul></li>
<li class="chapter" data-level="17" data-path="fragment-viewpager.html"><a href="fragment-viewpager.html"><i class="fa fa-check"></i><b>17</b> Fragments: ViewPager</a><ul>
<li class="chapter" data-level="17.1" data-path="fragment-viewpager.html"><a href="fragment-viewpager.html#define-a-searchfragment"><i class="fa fa-check"></i><b>17.1</b> Define a SearchFragment</a></li>
<li class="chapter" data-level="17.2" data-path="fragment-viewpager.html"><a href="fragment-viewpager.html#add-the-viewpager-and-adapter"><i class="fa fa-check"></i><b>17.2</b> Add the ViewPager and Adapter</a></li>
<li class="chapter" data-level="17.3" data-path="fragment-viewpager.html"><a href="fragment-viewpager.html#add-user-interaction"><i class="fa fa-check"></i><b>17.3</b> Add User Interaction</a></li>
</ul></li>
<li class="chapter" data-level="18" data-path="bluetooth.html"><a href="bluetooth.html"><i class="fa fa-check"></i><b>18</b> Bluetooth</a></li>
<li class="chapter" data-level="19" data-path="maps.html"><a href="maps.html"><i class="fa fa-check"></i><b>19</b> Maps</a><ul>
<li class="chapter" data-level="19.1" data-path="maps.html"><a href="maps.html#create-a-map-activity"><i class="fa fa-check"></i><b>19.1</b> Create a Map Activity</a><ul>
<li class="chapter" data-level="" data-path="maps.html"><a href="maps.html#getting-an-api-key"><i class="fa fa-check"></i>Getting an API Key</a></li>
<li><a href="maps.html#the-supportmapfragment">The <code>SupportMapFragment</code></a></li>
</ul></li>
<li class="chapter" data-level="19.2" data-path="maps.html"><a href="maps.html#specifying-the-user-interface"><i class="fa fa-check"></i><b>19.2</b> Specifying the User Interface</a></li>
<li class="chapter" data-level="19.3" data-path="maps.html"><a href="maps.html#markers-and-drawings"><i class="fa fa-check"></i><b>19.3</b> Markers and Drawings</a><ul>
<li class="chapter" data-level="" data-path="maps.html"><a href="maps.html#drawing-shapes"><i class="fa fa-check"></i>Drawing Shapes</a></li>
</ul></li>
</ul></li>
<li class="chapter" data-level="20" data-path="memory.html"><a href="memory.html"><i class="fa fa-check"></i><b>20</b> Memory Management</a><ul>
<li class="chapter" data-level="20.1" data-path="memory.html"><a href="memory.html#memory-allocation"><i class="fa fa-check"></i><b>20.1</b> Memory Allocation</a></li>
<li class="chapter" data-level="20.2" data-path="memory.html"><a href="memory.html#the-memory-monitor"><i class="fa fa-check"></i><b>20.2</b> The Memory Monitor</a><ul>
<li class="chapter" data-level="" data-path="memory.html"><a href="memory.html#garbage-collection"><i class="fa fa-check"></i>Garbage Collection</a></li>
</ul></li>
<li class="chapter" data-level="20.3" data-path="memory.html"><a href="memory.html#memory-leaks"><i class="fa fa-check"></i><b>20.3</b> Memory Leaks</a></li>
</ul></li>
<li class="chapter" data-level="21" data-path="multi-touch.html"><a href="multi-touch.html"><i class="fa fa-check"></i><b>21</b> Multi-Touch</a><ul>
<li class="chapter" data-level="21.1" data-path="multi-touch.html"><a href="multi-touch.html#identifying-fingers"><i class="fa fa-check"></i><b>21.1</b> Identifying Fingers</a></li>
<li class="chapter" data-level="21.2" data-path="multi-touch.html"><a href="multi-touch.html#drawing-touches"><i class="fa fa-check"></i><b>21.2</b> Drawing Touches</a></li>
<li class="chapter" data-level="21.3" data-path="multi-touch.html"><a href="multi-touch.html#moving-fingers"><i class="fa fa-check"></i><b>21.3</b> Moving Fingers</a></li>
<li class="chapter" data-level="21.4" data-path="multi-touch.html"><a href="multi-touch.html#other-multi-touch-gestures"><i class="fa fa-check"></i><b>21.4</b> Other Multi-Touch Gestures</a></li>
</ul></li>
<li class="appendix"><span><b>Appendix</b></span></li>
<li class="chapter" data-level="A" data-path="java-review.html"><a href="java-review.html"><i class="fa fa-check"></i><b>A</b> Java Review</a><ul>
<li class="chapter" data-level="A.1" data-path="java-review.html"><a href="java-review.html#building-apps-with-gradle"><i class="fa fa-check"></i><b>A.1</b> Building Apps with Gradle</a></li>
<li class="chapter" data-level="A.2" data-path="java-review.html"><a href="java-review.html#class-basics"><i class="fa fa-check"></i><b>A.2</b> Class Basics</a></li>
<li class="chapter" data-level="A.3" data-path="java-review.html"><a href="java-review.html#inheritance"><i class="fa fa-check"></i><b>A.3</b> Inheritance</a></li>
<li class="chapter" data-level="A.4" data-path="java-review.html"><a href="java-review.html#interfaces"><i class="fa fa-check"></i><b>A.4</b> Interfaces</a></li>
<li class="chapter" data-level="A.5" data-path="java-review.html"><a href="java-review.html#polymorphism"><i class="fa fa-check"></i><b>A.5</b> Polymorphism</a></li>
<li class="chapter" data-level="A.6" data-path="java-review.html"><a href="java-review.html#abstract-methods-and-classes"><i class="fa fa-check"></i><b>A.6</b> Abstract Methods and Classes</a></li>
<li class="chapter" data-level="A.7" data-path="java-review.html"><a href="java-review.html#generics"><i class="fa fa-check"></i><b>A.7</b> Generics</a></li>
<li class="chapter" data-level="A.8" data-path="java-review.html"><a href="java-review.html#nested-classes"><i class="fa fa-check"></i><b>A.8</b> Nested Classes</a></li>
</ul></li>
<li class="chapter" data-level="B" data-path="java-swing.html"><a href="java-swing.html"><i class="fa fa-check"></i><b>B</b> Java Swing Framework</a><ul>
<li class="chapter" data-level="B.1" data-path="java-swing.html"><a href="java-swing.html#events"><i class="fa fa-check"></i><b>B.1</b> Events</a></li>
<li class="chapter" data-level="B.2" data-path="java-swing.html"><a href="java-swing.html#layouts-and-composites"><i class="fa fa-check"></i><b>B.2</b> Layouts and Composites</a></li>
</ul></li>
<li class="chapter" data-level="C" data-path="publishing.html"><a href="publishing.html"><i class="fa fa-check"></i><b>C</b> Publishing</a><ul>
<li class="chapter" data-level="C.1" data-path="publishing.html"><a href="publishing.html#signing-an-app"><i class="fa fa-check"></i><b>C.1</b> Signing an App</a><ul>
<li><a href="publishing.html#release-.apk">Release <code>.apk</code></a></li>
</ul></li>
</ul></li>
<li class="divider"></li>
<li><a href="https://github.com/rstudio/bookdown" target="blank">Published with bookdown</a></li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i><a href="./">Android Development: Lecture Notes</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<section class="normal" id="section-">
<div id="services" class="section level1">
<h1><span class="header-section-number">Lecture 13</span> Threads and Services</h1>
<p>This lecture discusses a component of Android development that is <strong><em>not</em></strong> immediately visible to users: <a href="https://developer.android.com/guide/components/services.html"><strong>Services</strong></a><a href="#fn40" class="footnoteRef" id="fnref40"><sup>40</sup></a>. <em>Services</em> are sort of like Activities that don’t have a user interface or user interaction directly tied to them. Services can be launched by Activities or Applications, but then do their own thing in the background <em>even after the starting component is closed</em>. Once a Service is started, it keeps running until it is explicitly stopped (Services can be destroyed by the OS to save memory, similar to an Activity, but Services have higher <a href="https://developer.android.com/guide/topics/processes/process-lifecycle.html">“priority”</a> and so aren’t killed as readily).</p>
<p>Some common uses for a Service include:</p>
<ul>
<li>Downloading or uploading data from/to a network in the background even if the app is closed</li>
<li>Saving data to a database without crashing if the user leaves the app</li>
<li>Running some other kind of long-running, “background” task even after the app is closed, such as playing music!</li>
</ul>
<p>The most common use of Services is to regularly perform a background task in a way that doesn’t block the main UI interaction. This lecture thus begins with a discussion of threads and processes in Android, before detailing how to implement a Service.</p>
<p class="alert alert-info">
This lecture references code found at <a href="https://github.com/info448/lecture13-services" class="uri">https://github.com/info448/lecture13-services</a>.
</p>
<div id="threads-and-processes" class="section level2">
<h2><span class="header-section-number">13.1</span> Threads and Processes</h2>
<p><strong>Concurrency</strong> is the process by which we have multiple <em>processes</em> (think: methods) running at the same time. This can be contrasted with processes that run <strong>serially</strong>, or one after another.</p>
<p>For example, if you call two methods one after the other, then the second method execute will “wait” for the first one to finished:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">countUp</span>() {
<span class="kw">for</span>(<span class="dt">int</span> i=<span class="dv">0</span>; i<<span class="dv">1000</span>; i++){
<span class="bu">System</span>.<span class="fu">out</span>.<span class="fu">println</span>(i);
}
}
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">countDown</span>() {
<span class="kw">for</span>(<span class="dt">int</span> i=<span class="dv">0</span>; i> -<span class="dv">1000</span>; i--){
<span class="bu">System</span>.<span class="fu">out</span>.<span class="fu">println</span>(i);
}
}
<span class="fu">countUp</span>(); <span class="co">//start counting up</span>
<span class="fu">countDown</span>(); <span class="co">//start counting down (once finished going up)</span></code></pre></div>
<p>Computers as a general rule do exactly one thing a time: your central processing unit (CPU) just adds two number together over and over again, billions of times a second</p>
<ul>
<li>The standard measure for <em>rate</em> (how many times per second) is the <code>hertz</code> (Hz). So a 2 gigahertz (GHz) processor can do 2 billion operations per second.</li>
</ul>
<p>However, we don’t realize that computers do only one thing at a time! This is because computers are really good at <em>multitasking</em>: they will do a tiny bit of one task, and then jump over to another task and do a little of that, and then jump over to another task and do a little of that, and then back to the first task, and so on.</p>
<div class="figure">
<img src="img/threads/thread-switching.jpg" alt="Diagram of thread switching (source unknown)" />
<p class="caption">Diagram of thread switching (source unknown)</p>
</div>
<p>These “tasks” are divided up into two types: <strong>processes</strong> and <strong>threads</strong>. <strong><em>Read <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html">this brief summary</a> of the difference between them</em></strong>.</p>
<p>By breaking up a program into threads (which are “interwoven”), we can in effect cause the computer to do two tasks at once. This is <em>especially</em> useful if one of the “tasks” might take a really long time—rather than <strong>blocking</strong> the application, we can let other tasks also make some progress while we’re waiting for the long task to finish.</p>
<div id="java-threads" class="section level3 unnumbered">
<h3>Java Threads</h3>
<p>In Java, we create a Thread by creating a class that <code>implements</code> the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html"><strong><code>Runnable</code></strong></a> interface. This represents a class that can be “run” in a separate thread! The <code>run()</code> method required by the interface acts a bit like the “main” method for that Thread: when we start the Thread running, that is the method that will get called.</p>
<p>If we just instantiate the <code>Runnable()</code> and call its <code>run()</code> method, that won’t actually execute the method on a different thread (remember: an interface is just a “sign”; we could have called the interface and method whatever we wanted and it would still compile). Instead, we execute code on a separate thread by using an instance of the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html"><strong><code>Thread</code></strong></a> class. This class actually does the work of running code on a separate thread.</p>
<p><code>Thread</code> has a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable-">constructor</a> that takes in a <code>Runnable</code> instance as a parameter—you pass an object representing the “code to run” to the <code>Thread</code> object (this is an example of the <em>Strategy Pattern</em>). You then can actually <strong>start</strong> the <code>Thread</code> by calling its <code>.start()</code> method (<em>not</em> the <code>run</code> method!).</p>
<ul>
<li>Anonymous variables will be useful here; you don’t need to assign a variable name to the <code>Runnable</code> objects or even the <code>Thread</code> objects if you just use them directly.</li>
</ul>
<p>For example, making the above <code>countUp()</code> and <code>countDown()</code> methods run on separate threads can cause the the output to be “interwoven”, showing some positive then some negative numbers (you may need to increase the count or slow down the operation to see it in action, so one thread doesn’t finish before the “switch”).</p>
<!-- TODO: example detail -->
</div>
<div id="android-threads" class="section level3 unnumbered">
<h3>Android Threads</h3>
<p>Android apps run by default on the <strong><em>Main Thread</em></strong> (also called the <strong><em>UI Thread</em></strong>). This thread is in charge of all user interactions—handling button presses, scrolls, drags, etc.—but also UI <em>output</em> like drawing and displaying text! See <a href="https://developer.android.com/guide/components/processes-and-threads.html#Threads">Android Threads</a> for more details.</p>
<ul>
<li>As mentioned above, a thread is a piece of a program that is independently scheduled by the processor. Computers do exactly one thing at a time, but make it look like they are doing lots of tasks simultaneously by switching between them (i.e., between processes) really fast. Threads are a way that we can break up a single application or process into little “sub-process” that can be run simultaneously—by switching back and forth periodically so everyone has a chance to work</li>
</ul>
<p>Within a single thread, all method calls are <strong>synchronous</strong>—that is, one has to finish before the next occurs. You can’t get to step 4 without finishing step 3. With an event-driven system like Android, each method call is fast enough that this isn’t a problem (you’re done handling one click by the time the next occurs). But long, drawn-out processes like network access, processing bitmaps, or accessing a database could cause other tasks to have to wait. It’s like a traffic jam!</p>
<ul>
<li>Tasks such as network access are <strong>blocking</strong> method calls, which stop the Thread from continuing. A blocked <em>Main Thread</em> will lead to the infamous <strong>“Application not responding” (ANR)</strong> error!</li>
</ul>
<p>Thus we need to move any “slow” code (such as network access) <em>off</em> the Main Thread, onto a <strong>background thread</strong>, thereby allowing it to run without blocking the user interaction that occurs on the Main Thread. To do this in Android, we use a class called <a href="https://developer.android.com/reference/android/os/AsyncTask.html"><code>ASyncTask</code></a><a href="#fn41" class="footnoteRef" id="fnref41"><sup>41</sup></a> to perform a task (such as network access) asynchronously—without waiting for other Threads.</p>
<p class="alert alert-info">
Learning Android Development involves knowing about what classes exist, and can be used to solve problems, but how were we able to learn about the existing of this highly useful (and specialized) <code>ASyncTask</code> class? We started from the official API Guide on <a href="https://developer.android.com/guide/components/processes-and-threads.html">Processes and Threads Guide</a><a href="#fn42" class="footnoteRef" id="fnref42"><sup>42</sup></a>, which introduces this class! Thus to learn about new Android options, <em>read the docs</em>.
</p>
<p>Note that an <code>ASyncTask</code> background thread will be <em>tied to the lifecycle of the Activity</em>: if we close the Activity, the network connection will die as well. A better option is often to use a <code>Service</code>, described below.</p>
<p><code>ASyncTask</code> can be fairly complicated, but is a good candidate to practice learning from the API documentation. Looking at that documentation, the first thing you should notice (or would if the API was a little more readable) is that <code>ASyncTask</code> is <strong><code>abstract</code></strong>, meaning you’ll need to <em>subclass</em> it in order to use it. Thus you can subclass it as an <em>inner</em> class inside the Activity that will use it.</p>
<!-- TODO: example detail -->
<p>You should also notice that <code>ASyncTask</code> is a <em>generic</em> class with three (3) generic parameters: the type of the Parameter to the task, the type of the Progress measurement reported by the task, and the type of the task’s Result. We can fill in what types of Parameter and Result we want from our asynchronous method (e.g., take in a <code>String</code> and return a <code>String[]</code>). You can use the <code>Void</code> type for an unspecified type, such as with Progress measurement if you aren’t tracking that.</p>
<ul>
<li>We can actually pass in multiple <code>String</code> arguments using the <code>String... params</code> spread operator syntax (representing an arbitrary number of items of that type). See <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs">here</a> for details. The value that the <code>ASyncTask</code> methods <em>actually</em> get is an array of the arguments.</li>
</ul>
<p>When you “run” an AsyncTask, it will do four (4) things, represented by four methods:</p>
<ol style="list-style-type: decimal">
<li><code>onPreExecute()</code> is called <em>on the UI thread</em> before it runs the task. This method can be used to perform any setup for the task.</li>
<li><code>doInBackground(Params...)</code> is called <em>on the background thread</em> to do the work you want to be performed asynchronously. You <strong>must</strong> override this method (it’s <code>abstract</code>!) The params and return type for the method need to match the <code>ASyncTask</code> generic types.</li>
<li><code>onProgressUpdate()</code> can be indirectly called <em>on the UI thread</em> if we want to update our progress (e.g., update a progress bar). Note that UI changes can <strong>only</strong> be made on the UI thread!</li>
<li><code>onPostExecute(Result)</code> is called <em>on the UI thread</em> to process any task results, which are passed as parameters to this method when <code>doInBackground</code> is finished.</li>
</ol>
<p>The <code>doInBackground()</code> is what occurs on the background thread (and is the heart of the task), so you would put e.g., network or database accessing method calls in there.</p>
<p>We can then <em>instantiate</em> a new <code>ASyncTask</code> object in the Activity’s <code>onCreate()</code> callback, and call <code>ASyncTask#execute(params)</code> to start the task running on its own thread.</p>
<p>In order to get any results back into the rendered View, you utilize the <code>doPostExecute()</code> method. This method is run on the <em>UI Thread</em> so you can use it to update the View (we can <em>only</em> change the View on the UI Thread, to avoid collisions). It also gets the results <em>returned</em> by <code>doInBackground()</code> passed to it automatically!</p>
<ul>
<li>E.g., you can take a resulting <code>String[]</code> and put that into an <code>Adapter</code> for a <code>ListView</code>.</li>
</ul>
<p><code>ASyncTask</code> is the simplest, general way to do some work on a background thread. However, it has a few limitations:</p>
<ul>
<li><p>The lifecycle of an <code>ASyncTask</code> is tied to that of its containing Activity. This means that if the containing Activity is destroyed (e.g., is <code>finished()</code>), then the the ASyncTask is as well—you would lose any data you were downloading or might corrupt your database in some way.</p></li>
<li><p>To handle lots of different background tasks, you would need to do your own task management.</p></li>
</ul>
<p>As such, repeated or longer-lasting tasks (such as large file downloads) are often better handled through <strong>Services</strong>.</p>
</div>
</div>
<div id="intentservices" class="section level2">
<h2><span class="header-section-number">13.2</span> IntentServices</h2>
<p>As mentioned above, a Service is an application component (like an Activity) that runs in the “background”, even if the user switches to another application. Services do not normally have an associated user interface, but instead are simply was to group and manage large amounts of data processing (e.g., for network downloads, media processing, or database access).</p>
<ul>
<li>An important thing to note about Services: a Service is <strong>not</strong> a separate process; it runs in the same process as the app that starts it (unless otherwise specified). Similarly, a Service is <strong>not</strong> a Thread, and in fact doesn’t need to run outside the UI thread! However, we quite often <em>do</em> want to run the service outside of the UI Thread, and so often have it spawn and run a new <code>Runnable</code> Thread. When we say a Service runs “in the background”, we mean from a user’s perspective rather than necessarily on a background thread.</li>
</ul>
<p>To create a Service, we’re going to subclass <a href="https://developer.android.com/reference/android/app/Service.html"><code>Service</code></a> and override some <em>lifecycle callbacks</em>, just like we’ve done with <code>Activity</code>, <code>Fragment</code>, <code>BroadcastReceiver</code>, and most other Android components. In this sense, Services are in fact implemented like Activities that run without a user interface (“in the background”).</p>
<p>Because Services will be performing extra background computation, it’s important to also create a separate background thread so that you don’t block the Main Thread. Since making a Service that does some (specific) task in a background thread is so common, Android includes a <code>Service</code> subclass we can use to do exactly this work. This class is called <a href="https://developer.android.com/reference/android/app/IntentService.html"><code>IntentService</code></a>—a service that responds to <code>Intents</code> and does some work in response to them.</p>
<ul>
<li>An IntentService does a similar job to <code>ASyncTask</code>, but with the advantage that it will keep doing that work even if the Activity is destroyed!</li>
<li><p><code>IntentService</code> will listen to any incoming “requests” (<code>Intents</code>) and “queue” them up, handling each one at a time. Once the service is out of tasks to do, the service will shut itself down to save memory (though it will restart if more <code>Intents</code> are sent to it). Basically, it handles a lot of the setup and cleanup involved in using a Service on its own!</p></li>
<li><p>(This lecture will start with <code>IntentService</code> because it’s simpler, and then move into the more generic, complex version of Services).</p></li>
</ul>
<p>We create an IntentService by defining a new class (e.g., <code>CountingService</code>) that subclasses <code>IntentService</code>.</p>
<ul>
<li>Implement a default <em>constructor</em> that can call <code>super(String nameForDebugging)</code>. This allows the class to be instantiated (by the Android framework; again, like an Activity).</li>
<li><p>Also implement the <code>onHandleIntent(Intent)</code> method. Incoming <code>Intents</code> will wait their turn in line, and then each is delivered to this method in turn. Note that all this work (delivery and execution) will happen in a <strong>background thread</strong> supplied by <code>IntentService</code>.</p>
<p>For example, we can have the Service (when started) log out a count, pausing for a few seconds between. This will represent “expensive” logic to perform, a la accessing a network or a database.</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
<span class="kw">for</span>(<span class="dt">int</span> count=<span class="dv">0</span>; count<=<span class="dv">10</span>; count++){
Log.<span class="fu">v</span>(TAG, <span class="st">"Count: "</span>+count);
<span class="kw">try</span> {
<span class="bu">Thread</span>.<span class="fu">sleep</span>(<span class="dv">2000</span>); <span class="co">//sleep for 2 seconds</span>
} <span class="kw">catch</span> (<span class="bu">InterruptedException</span> e) {
<span class="bu">Thread</span>.<span class="fu">currentThread</span>().<span class="fu">interrupt</span>();
}
}</code></pre></div>
<div class="sourceCode"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><span class="co">//kotlin</span>
<span class="cf">for</span> (count <span class="kw">in</span> <span class="dv">0</span>..<span class="dv">10</span>) {
Log.v(TAG, <span class="st">"Count: $count"</span>)
<span class="cf">try</span> {
Thread.sleep(<span class="dv">2000</span>) <span class="co">//sleep for 2 seconds</span>
} <span class="cf">catch</span> (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}</code></pre></div></li>
</ul>
<p>Just like with Activities, we also need to declare the <code><service></code> in the Manifest, as a child of the <code><application></code>:</p>
<div class="sourceCode"><pre class="sourceCode xml"><code class="sourceCode xml"><span class="kw"><service</span><span class="ot"> android:name=</span><span class="st">".CountingService"</span> <span class="kw">/></span></code></pre></div>
<p>Finally, we can send an <code>Intent</code> to the Service by using the <code>startService()</code> method. This is similar to <code>startActivity()</code>, but for Services! We can use explicit intents just like with Activities, and could even include Extras if we wanted to label and track the specific Intents sent to the Service.</p>
<ul>
<li>When the Service starts, we can see it start counting (but without blocking the UI Thread). We can also destroy the Activity and see that the Service keeps running.</li>
</ul>
<p>If we want to have the Service interact with the user interface (e.g., display a Toast), we will need to make sure that occurs on the UI Thread (you cannot change the UI on a separate thread). This requires <em>inter-thread communication</em>: we need to get a message (a function call) from the background thread to the UI Thread.</p>
<ul>
<li>This is what various <code>ASyncTask</code> UI thread methods (such as <code>onProgressUpdate()</code>) do for us.</li>
</ul>
<p>We can perform this communication using a <a href="https://developer.android.com/reference/android/os/Handler.html"><code>Handler</code></a>, which is an object used to pass messages between Threads—it “handles” the messages!</p>
<ul>
<li><p>We instantiate a <code>new Handler()</code> object (e.g., in the Service’s <code>onCreate()</code> callback), calling a method on that object when we want to “send” a message. The easiest way to send a message is to use the <code>post()</code> function, which takes a <code>Runnable()</code> method which will be executed <em>on the Main Thread</em>:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
mHandler.<span class="fu">post</span>(<span class="kw">new</span> <span class="bu">Runnable</span>() {
<span class="at">@Override</span>
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">run</span>() {
Toast.<span class="fu">makeText</span>(CountingService.<span class="fu">this</span>, <span class="st">"Count: "</span> + count, Toast.<span class="fu">LENGTH_SHORT</span>).<span class="fu">show</span>();
}
});</code></pre></div>
<div class="sourceCode"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><span class="co">//kotlin</span>
mHandler.post {
Toast.makeText(this<span class="at">@CountingService</span>, <span class="st">"Count: $count"</span>, Toast.LENGTH_SHORT).show()
Log.v(TAG, <span class="st">""</span> + count)
}</code></pre></div></li>
</ul>
<div id="the-service-lifecycle" class="section level3 unnumbered">
<h3>The Service Lifecycle</h3>
<p>Having demonstrated the basic usage of a service, consider what is going on “under the hood”—starting with the <a href="https://developer.android.com/guide/components/services.html#LifecycleCallbacks">Service lifecycle</a>. There are actually two different “types” of Services, with different variations of the lifecycle. <strong>Started Services</strong> (or “unbound” Services) are those that are initiated via the <code>startService()</code> function, as in the above example. The other option, <strong>Bound Services</strong>, are Services that have “client” Activities bound to them to interact with; see below for details.</p>
<div class="figure">
<img src="img/services/service_lifecycle.png" alt="Service lifecycle diagram, from Google" />
<p class="caption">Service lifecycle diagram, from Google<a href="#fn43" class="footnoteRef" id="fnref43"><sup>43</sup></a></p>
</div>
<ul>
<li><p>Just like with Activities, Services have an <code>onCreate()</code> method that is called when the Service is first created. Since Services don’t have a user interface to set up, so we don’t often do a lot in here.</p>
<ul>
<li>IntentService already overrides this in order to set up a “message queue” so that it can queue up Intents (tasks) to run one at a time.</li>
</ul></li>
<li><p>The most important callback for a <em>Started Service</em> is called <code>onStartCommand()</code>. This method is called when the Service is <strong>sent a command</strong> by another component (via an Intent). Importantly, <code>onStartCommand()</code> is not only called when the Service is started for the first time, but whenever the Service receives an Intent to start (even if the Service was already running)! These Intents are those sent via <code>startService()</code>.</p>
<ul>
<li>Note that when working with an <em><code>IntentService</code></em> specifically, <code>onStartCommand()</code> will “queue” any incoming Intents. When it is the specific Intent’s turn to be “run”, that Intent is automatically passed to the <code>onHandleIntent()</code> method, which executes on a <em>background thread</em> (similar to <code>AsyncTask#doInBackground()</code>). This callback is not part of the normal Service lifecycle, but is a special helper method used by IntentService—similar to how <code>onCreateDialog()</code> is a special method used by <code>DialogFragments</code>.</li>
</ul></li>
<li><p>The <code>onBind()</code> and <code>onUnbind()</code> callbacks are used for bound services, and are discussed below.</p>
<ul>
<li>IntentService does have a default <code>onBind()</code> implementation that returns <code>null</code>.</li>
</ul></li>
<li><p>Finally, Services have an <code>onDestroy()</code> callback, which is again equivalent to the Activity callback.</p>
<ul>
<li>In general, Services have to be manually told to <strong>stop</strong>. We stop a Service by using <code>stopService(Intent)</code> to send that Service a “stop” Intent. The Service can also stop itself by calling <code>stopSelf()</code>.</li>
<li><em>Important</em>: When told to stop, an <code>IntentService</code> will finish up handling any Intents that are currently “running”, but any other Intents that are “queued” will be removed. Once there are no more queued Intents, an IntentService will call <code>stopSelf()</code>, thereby causing the <code>onDestroy()</code> callback to be executed.</li>
</ul></li>
</ul>
<p><strong><em>Practice:</em></strong> fill in the callback functions with Log or Toast messages to see how and when they are executed. For example:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
<span class="kw">public</span> <span class="dt">int</span> <span class="fu">onStartCommand</span>(Intent intent, <span class="dt">int</span> flags, <span class="dt">int</span> startId) {
Toast.<span class="fu">makeText</span>(<span class="kw">this</span>, <span class="st">"Intent received"</span>, Toast.<span class="fu">LENGTH_SHORT</span>).<span class="fu">show</span>();
<span class="kw">return</span> <span class="kw">super</span>.<span class="fu">onStartCommand</span>(intent, flags, startId);
}</code></pre></div>
<p>As a last point to note about the Service lifecycle consider the <code>int</code> that is returned by <code>onStartCommand()</code>. This <code>int</code> is a flag that indicates how the Service should <a href="https://developer.android.com/guide/components/services.html#ExtendingService">behave</a><a href="#fn44" class="footnoteRef" id="fnref44"><sup>44</sup></a> when it is “restarted” after having been destroyed:</p>
<ul>
<li><p><a href="https://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY"><code>START_NOT_STICKY</code></a> indicates that if the Service is destroyed by the system, it should not be recreated. This is the “safest option” to avoid extraneous service executions; instead, just have the application restart the Service.</p></li>
<li><p><a href="https://developer.android.com/reference/android/app/Service.html#START_STICKY"><code>START_STICKY</code></a> indicates that if the Service is destroyed by the system, it should be recreated when possible. At that point, <code>onStartCommand()</code> will be called by delivering a <code>null</code> Intent (unless there were other start Intents waiting to be delivered, in which case those are used). This option works well for media players or similar services that are running indefinitely (rather than executing specific commands).</p></li>
<li><p><a href="https://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT"><code>START_REDELIVER_INTENT</code></a> indicates that if the Service is destroyed by the system, it should be recreated when possible. At that point, <code>onStartCommand()</code> will be called with the <em>last</em> Intent that was delivered to the Service (and any other Intents are delivered in turn). This option is good for Services that actively perform jobs that need to be resumed, such as downloading a file.</p></li>
</ul>
<p>In other words: services may get killed, but we can specify how they get resurrected! And of course, we can and should return different values for different starting commands (Intents): so the Intent to download a music file might return <code>START_REDELIVER_INTENT</code>, but the Intent to play the music file might return <code>START_STICKY</code>.</p>
<!-- TODO continue editing -->
</div>
</div>
<div id="example-a-music-service" class="section level2">
<h2><span class="header-section-number">13.3</span> Example: A Music Service</h2>
<p>One of the classic uses for a background service is to play music, so we will use that as an example. It is possible to play music directly from an Activity, and the music will even keep playing as long as the Activity is alive. But remember that Activities are fragile, and can be destroyed at any moment (whether by us or by the system to save resources). So in order to keep our music playing even as we go about other tasks, we should <a href="http://developer.android.com/guide/topics/media/mediaplayer.html#mpandservices">use a Service</a>. Services have higher “priority” in the eyes of the Android system, and so don’t get sacrificed for resources as readily as normal Activities.</p>
<div id="mediaplayer" class="section level3 unnumbered">
<h3>MediaPlayer</h3>
<p>In order to make a music service, we need to briefly explain how to play music with <a href="https://developer.android.com/guide/topics/media/mediaplayer.html"><code>MediaPlayer</code></a>. This is the main API for playing sound and video (e.g., if you want to play <code>.mp3</code> files).</p>
<p class="alert alert-info">
Android actually has a total of three (3) audio APIs! The <a href="https://developer.android.com/reference/android/media/SoundPool.html"><code>SoundPool</code></a> API is great for short sound effects that play simultaneously (though you need to do extra work to load those clips ahead of time), such as for simple games. The <a href="http://developer.android.com/reference/android/media/AudioTrack.html"><code>AudioTrack</code></a> API allows you to play audio at a very low level (e.g., by “pushing” bytes to a stream). This is useful for generated Audio (like MIDI music) or if you’re trying to do some other kind of low-level stuff.
</p>
<p><code>MediaPlayer</code> is very simple to use, particularly when playing a locally defined resource (e.g., something in <code>res/raw/</code>). You simply use a factory to make a new <code>MediaPlayer</code> object, and then call <code>.play()</code> on it:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java">MediaPlayer mediaPlayer = MediaPlayer.<span class="fu">create</span>(context, R.<span class="fu">raw</span>.<span class="fu">my_sound_file</span>);
mediaPlayer.<span class="fu">start</span>(); <span class="co">// no need to call prepare(); create() does that for you</span></code></pre></div>
<p>We can also call <code>.pause()</code> to pause the music, <code>.seekTo()</code> to jump to a particular millisecond, and <code>.stop()</code> to stop the music.</p>
<ul>
<li>Note that when we <code>stop()</code>, we also need to release any resources used by the <code>MediaPlayer</code> (to free up memory):</li>
</ul>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java">mediaPlayer.<span class="fu">release</span>();
mediaPlayer = <span class="kw">null</span>;</code></pre></div>
<p>We can also implement and register a <code>MediaPlayer.OnCompletionListener</code> to do something when a song finishes playing.</p>
<p>Finally, it is possible to use <code>MediaPlayer</code> to play files from a <code>ContentProvider</code> or even off the Internet!</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
<span class="bu">String</span> url = <span class="st">"http://........"</span>; <span class="co">// your URL here</span>
MediaPlayer mediaPlayer = <span class="kw">new</span> <span class="fu">MediaPlayer</span>();
mediaPlayer.<span class="fu">setAudioStreamType</span>(AudioManager.<span class="fu">STREAM_MUSIC</span>);
mediaPlayer.<span class="fu">setDataSource</span>(url);
mediaPlayer.<span class="fu">prepareAsync</span>(); <span class="co">//prepare media in the background (buffering, etc)</span>
<span class="co">//.prepare() for synchronous buffering</span>
mediaPlayer.<span class="fu">setOnPreparedListener</span>(<span class="kw">this</span>); <span class="co">//handle when file is buffered</span>
mediaPlayer.<span class="fu">start</span>();</code></pre></div>
</div>
<div id="creating-a-service" class="section level3 unnumbered">
<h3>Creating a Service</h3>
<p>In order to make our music service, we are going to subclass the <code>Service</code> class itself (<em>don’t forget to include the Service in the <code>Manifest</code></em>) and manually set up all the pieces. Specifically, we will fill in the lifecycle callbacks:</p>
<ul>
<li><code>onCreate()</code> we can include, though it doesn’t need to do anything.</li>
<li><p><code>onStartCommand()</code> should create and start our MediaPlayer. We can return <code>START_NOT_STICKY</code> so the music doesn’t start up again randomly if the system needs to destroy the Service (since it won’t get recreated).</p>
<p><em>Important:</em> Normally with a Service we would create a background thread to handle any extraneous work (such as preparing the music to play, as done with the <code>create()</code> method). However, this may not be necessary for MediaPlayer when loading resources.</p></li>
<li><p><code>onDestroy()</code> can stop, release, and clean-up the MediaPlayer. We can implement this in a separate helper function for reuse.</p>
<ul>
<li>If we want to handle pausing, we can specify that in the Intent we send to the service (e.g., via a custom ACTION or an Extra). But a more effective approach is to use Service Binding; see below for details.</li>
</ul></li>
</ul>
<p>We can now have our Activity <code>startService()</code> and <code>stopService()</code> in order to play our music in the “background”, even if we leave and return to the Activity!</p>
</div>
</div>
<div id="foreground-services" class="section level2">
<h2><span class="header-section-number">13.4</span> Foreground Services</h2>
<p>Services are normally “background” tasks, that run without any user interface and that the user isn’t aware of (e.g., for downloading or uploading data, etc). But music playing is definitely something that the user <em>is</em> aware of, and in fact may want to interact with it! So we’d like the Service to have some kind of user interface, but we’d like to still keep that Service separated from an Activity (so that it can run with the Activity being active).</p>
<p>To do this, we use what is called a <a href="https://developer.android.com/guide/components/services.html#Foreground"><strong>Foreground Service</strong></a>. Foreground Services represent Services that are divorced from Activities (they <em>are</em> Services after all), but the user is aware of them—and accordingly, have an even higher survival <a href="https://developer.android.com/guide/topics/processes/process-lifecycle.html">priority</a> if the OS gets low on memory!</p>
<p>Foreground services require a <strong>Notification</strong> in the status bar, similar to the Notifications we’ve created before. This Notification will effectively act as the “user interface” for the Service, and let the user see and be aware of its execution!</p>
<p>We create this Notification inside the Service’s <code>onStartCommand()</code> method, then pass it to the <code>startForeground()</code> method in order to put our Service in the foreground:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java, pre-Oreo</span>
<span class="bu">String</span> songName = <span class="st">"The Entertainer"</span>;
PendingIntent pendingIntent = PendingIntent.<span class="fu">getActivity</span>(<span class="fu">getApplicationContext</span>(), <span class="dv">0</span>,
<span class="kw">new</span> <span class="fu">Intent</span>(<span class="fu">getApplicationContext</span>(), MainActivity.<span class="fu">class</span>), PendingIntent.<span class="fu">FLAG_UPDATE_CURRENT</span>);
<span class="bu">Notification</span> notification = <span class="kw">new</span> NotificationCompat.<span class="fu">Builder</span>(<span class="kw">this</span>)
.<span class="fu">setSmallIcon</span>(android.<span class="fu">R</span>.<span class="fu">drawable</span>.<span class="fu">ic_media_play</span>)
.<span class="fu">setContentTitle</span>(<span class="st">"Music Player"</span>)
.<span class="fu">setContentText</span>(<span class="st">"Now playing: "</span>+songName)
.<span class="fu">setContentIntent</span>(pendingIntent)
.<span class="fu">setOngoing</span>(<span class="kw">true</span>) <span class="co">//cannot be dismissed by the user</span>
.<span class="fu">build</span>();
<span class="fu">startForeground</span>(NOTIFICATION_ID, notification); <span class="co">//make this a foreground service!</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><span class="co">//kotlin</span>
<span class="kw">val</span> <span class="va">songName</span> = <span class="st">"The Entertainer"</span>
<span class="kw">val</span> <span class="va">pendingIntent</span> = PendingIntent.getActivity(applicationContext, <span class="dv">0</span>,
Intent(applicationContext, MainActivity::<span class="kw">class</span>.java), PendingIntent.FLAG_UPDATE_CURRENT)
if (<span class="va">android</span>.<span class="va">os</span>.<span class="va">Build</span>.<span class="va">VERSION</span>.<span class="va">SDK_INT</span> >= android.os.Build.VERSION_CODES.O) {
<span class="kw">val</span> <span class="va">channel</span> = NotificationChannel(NOTIFICATION_CHANNEL_ID, <span class="st">"Demo channel"</span>, NotificationManager.IMPORTANCE_LOW)
<span class="kw">val</span> <span class="va">notificationManager</span> = getSystemService(Context.NOTIFICATION_SERVICE) <span class="kw">as</span> NotificationManager
notificationManager.createNotificationChannel(channel)
}
<span class="kw">val</span> <span class="va">notification</span> = NotificationCompat.Builder(<span class="kw">this</span>, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentTitle(<span class="st">"Music Player"</span>)
.setContentText(<span class="st">"Now playing: $songName"</span>)
.setContentIntent(pendingIntent)
.setOngoing(<span class="kw">true</span>) <span class="co">//cannot be dismissed by the user</span>
.build()
startForeground(NOTIFICATION_ID, notification) <span class="co">//make this a foreground service!</span></code></pre></div>
<p>Some details about this Notification:</p>
<ul>
<li>We build and set the icon, title, and text as in the previous lecture.</li>
<li>We give the Notification a <code>PendingIntent</code> to run when selected. This PendingIntent can just open up our <code>MainActivity</code>, allowing us to control the Player. (Alternatively, we could use <a href="https://developer.android.com/guide/topics/ui/notifiers/notifications.html#controllingMedia">Notification Actions</a> to control the music directly).</li>
<li>We set the Notification to be <em>ongoing</em>, in order to enforce that it cannot be dismissed by the user.</li>
</ul>
<p><em>Importantly</em>, once we are done doing foreground work (e.g., playing music), we should call <code>stopForeground(true)</code> to get rid of the foreground service. This is a good thing to do in our <code>stopMusic()</code> helper (called from <code>onDestroy()</code>).</p>
<p class="alert alert-info">
There are a couple of other details that you should handle if you’re making a full-blown music player app, including: keeping the phone from going to sleep, playing other audio at the same time (e.g., notification sounds; ringtones), switching to external speakers, etc. See the <a href="https://developer.android.com/guide/topics/media/mediaplayer.html">guide</a> for more details.
</p>
</div>
<div id="bound-services" class="section level2">
<h2><span class="header-section-number">13.5</span> Bound Services</h2>
<p>As mentioned above, there are two “types” of Services: <strong>Started Services</strong> (Services launched with <code>startService()</code>) and <strong>Bound Services</strong>. A <a href="https://developer.android.com/guide/components/bound-services.html">Bound Service</a> is a Service that acts as the “server” in a client-server setup: it allows for client Activities to “connect” to it (<strong><em>bind it</em></strong>) and then exchange messages with it—primarily by calling methods on the Service. These messages can even be <em>across processes</em>, allowing for <a href="https://en.wikipedia.org/wiki/Inter-process_communication">interprocess communication</a>! This is useful when you want interact with the Service from an Activity in some way (e.g., if we want to <code>pause()</code> our music), or if we want to make the service’s capabilities available to other applications.</p>
<p>We make a Bound Service by having the Service implement and utilize the <strong><code>onBind()</code></strong> callback. This method returns an <code>IBinder</code> object (the <code>I</code> indicates that it’s an <em>Interface</em>, following a Java convention common in enterprise software). When Activities connect to this Service (using the <code>bindService()</code> method), this <code>IBinder</code> object is passed to them, and they can use it to get access to the Service process to call methods on it. Effectively, the binding process produces an <em>object</em> that represents that Service, so Activities can call methods on the Service without needing to send it Intents!</p>
<p>As an example, let’s add the ability to “pause” the music being played as a bound service:</p>
<p>The first thing we need to do is have our Service implement the <code>onBind()</code> method. To do this, we will need an <code>IBinder</code> object to return (that is: an object of a class that implements the <code>IBinder</code> interface). For “local services” (e.g., Services that are run <em>in the same process</em>), the easiest way to get an <code>IBinder</code> is to extend the <code>Binder</code> class:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//kotlin</span>
<span class="kw">public</span> <span class="kw">class</span> MyBinder <span class="kw">extends</span> <span class="bu">Binder</span> { <span class="co">//implements IBinder</span>
<span class="co">//binder class methods will go here!</span>
}
<span class="kw">private</span> <span class="dt">final</span> IBinder mBinder = <span class="kw">new</span> <span class="fu">MyBinder</span>(); <span class="co">//singleton instance variable</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><span class="co">//kotlin</span>
<span class="kw">class</span> LocalBinder : <span class="dt">Binder</span>() {
<span class="co">//binder class methods will go here!</span>
}
<span class="kw">private</span> <span class="kw">val</span> <span class="va">mLocalBinder</span> = LocalBinder() <span class="co">//singleton instance variable</span></code></pre></div>
<ul>
<li>Our local version starts “empty” for now; we’ll add details below.</li>
<li>We will just return this object from <code>onBind()</code>.</li>
</ul>
<p>Because the Activity is given a copy of this <code>MyBinder</code> object, that class can be designed to support the Activity communicating with the Service in a couple of different ways:</p>
<ol style="list-style-type: decimal">
<li><p>The <code>IBinder</code> can provide <code>public</code> methods for the Activity to call. These methods can then access instance variables of the Service (since the <code>MyBinder</code> is a nested class). This causes the <code>IBinder</code> to literally act as the “public interface” for the Service!</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//in MyBinder</span>
<span class="kw">public</span> <span class="bu">String</span> <span class="fu">getSongName</span>() {
<span class="kw">return</span> songName; <span class="co">//access Service instance variable</span>
}</code></pre></div></li>
<li><p>The <code>IBinder</code> can provide access to the Service itself (via a getter that returns the <code>Service</code> object). The Activity can then call any public methods provided by that <code>Service</code> class.</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//in MyBinder</span>
<span class="kw">public</span> MusicService <span class="fu">getService</span>() {
<span class="co">// Return this instance of this Service so clients can call public methods on it!</span>
<span class="kw">return</span> MusicService.<span class="fu">this</span>;
}</code></pre></div></li>
<li><p>The <code>IBinder</code> can provide access to some other object “owned” by the Service, which the Activity can then call methods on (e.g., the <code>MediaPlayer</code>). This is somewhat like a compromise between the first two options: you don’t need to implement a specific public interface on the <code>IBinder</code>, but you also don’t have to provide full access to your Service object! This is good for only exposing part of the Service.</p></li>
</ol>
<p>In the Activity, we need to do a bit more work in order to interact with the bound Service. We bind to a Service using <a href="http://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)"><code>bindService(Intent, ServiceConnection, flag)</code></a>. We can do this whenever we want the Service to be available (<code>onStart()</code> is a good option, so it is available when the Activity is active).</p>
<ul>
<li>The Intent parameter should be addressed to the Service we want to bind.</li>
<li><p>The <code>ServiceConnection</code> parameter is a reference to an object that implements the <code>ServiceConnection</code> interface, providing callbacks that can be executed when the Activity connects to the Service. We can have the Activity implement the interface, or create a separate anonymous class:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="co">//java</span>
<span class="co">/**</span> Defines callbacks for service binding<span class="co">,</span> passed to bindService<span class="co">()</span> <span class="co">*/</span>
<span class="co">/**</span> From Android documentation <span class="co">*/</span>
<span class="kw">private</span> ServiceConnection mConnection = <span class="kw">new</span> <span class="fu">ServiceConnection</span>() {
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">onServiceConnected</span>(ComponentName className, IBinder service) {
<span class="co">// We've bound to LocalService, cast the IBinder and get LocalService instance</span>
MyBinder binder = (MyBinder) service;
mService = binder.<span class="fu">getService</span>();
mBound = <span class="kw">true</span>;
}
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">onServiceDisconnected</span>(ComponentName arg0) {
mBound = <span class="kw">false</span>;
}
};</code></pre></div>
<div class="sourceCode"><pre class="sourceCode kotlin"><code class="sourceCode kotlin"><span class="co">//kotlin</span>
<span class="co">/** Defines callbacks for service binding, passed to bindService() */</span>
<span class="co">/** From Android documentation */</span>
<span class="kw">private</span> <span class="kw">val</span> <span class="va">mConnection</span> = <span class="kw">object</span> : <span class="dt">ServiceConnection</span> {
<span class="kw">override</span> <span class="kw">fun</span> <span class="fu">onServiceConnected</span>(<span class="va">className</span>: <span class="dt">ComponentName</span>, <span class="va">service</span>: <span class="dt">IBinder</span>) {
<span class="co">// We've bound to LocalService, cast the IBinder and get LocalService instance</span>
<span class="kw">val</span> <span class="va">binder</span> = service <span class="kw">as</span> LocalService.LocalBinder
mService = binder.getService()
mBound = <span class="kw">true</span>
}
<span class="kw">override</span> <span class="kw">fun</span> <span class="fu">onServiceDisconnected</span>(<span class="va">arg0</span>: <span class="dt">ComponentName</span>) {
mBound = <span class="kw">false</span>
}
} </code></pre></div>
<p>The <code>onServiceConnected()</code> callback handles the actual connection, and is where we get access to that <code>IBinder</code>. We can use that <code>IBinder</code> to fetch the Service object to call methods on, saving that as an instance variable to do stuff to it! We’ll also track whether or not the Service has been bound to avoid any <code>null</code> errors.</p></li>
<li><p>Finally, the <code>flag</code> parameter indicates some options for how the Service should be bound (e.g., for specifying survival priority). <code>Conetxt.BIND_AUTO_CREATE</code> is a good default, specifying that the binding should create the Service object if needed.</p></li>
</ul>
<p>Once a Service is bound, we can call methods on that Service (which must exist!)—allowing us to support the “pause” button.</p>
<p>We should also call <code>unbindService()</code> when the Activity stops, in order to free up resources:</p>
<div class="sourceCode"><pre class="sourceCode java"><code class="sourceCode java"><span class="kw">protected</span> <span class="dt">void</span> <span class="fu">onStop</span>() {
<span class="kw">if</span> (mBound) {
<span class="fu">unbindService</span>(<span class="kw">this</span>);
}
<span class="kw">super</span>.<span class="fu">onStop</span>();
}</code></pre></div>
<p class="alert alert-info">
Keep in mind that binding a Service <strong>DOES NOT</strong> call <code>onStartCommand()</code>, but simply creates the Service and gives us access to it! Bound Services are not by default considered “started”, and are generally kept around by the OS as long as they are bound. If we do “start” a Bound Service (e.g., with <code>startService()</code>), we will need to remember to stop it later!
</p>
<p>This example is just for <em>local services</em> (that are accessed within the same process—within the same Application). If we want the Service to be available to other processes (i.e., other Applications), we need to do more work. Specifically, we use <code>Handler</code> and <code>Messenger</code> objects to pass messages between these processes (similar to the example we did for passing messages between threads); for more details, see <a href="https://developer.android.com/guide/components/bound-services.html#Messenger">the example in the guide</a>, as well as the complete sample classes <a href="https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.java"><code>MessengerService</code></a> and <a href="https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java"><code>MessengerServiceActivities</code></a>.</p>
</div>
</div>
<div class="footnotes">
<hr />
<ol start="40">
<li id="fn40"><p><a href="https://developer.android.com/guide/components/services.html" class="uri">https://developer.android.com/guide/components/services.html</a><a href="services.html#fnref40">↩</a></p></li>
<li id="fn41"><p><a href="https://developer.android.com/reference/android/os/AsyncTask.html" class="uri">https://developer.android.com/reference/android/os/AsyncTask.html</a><a href="services.html#fnref41">↩</a></p></li>
<li id="fn42"><p><a href="https://developer.android.com/guide/components/processes-and-threads.html" class="uri">https://developer.android.com/guide/components/processes-and-threads.html</a><a href="services.html#fnref42">↩</a></p></li>
<li id="fn43"><p><a href="https://developer.android.com/images/service_lifecycle.png" class="uri">https://developer.android.com/images/service_lifecycle.png</a><a href="services.html#fnref43">↩</a></p></li>
<li id="fn44"><p><a href="https://developer.android.com/guide/components/services.html#ExtendingService" class="uri">https://developer.android.com/guide/components/services.html#ExtendingService</a><a href="services.html#fnref44">↩</a></p></li>
</ol>
</div>
</section>
</div>
</div>
</div>
<a href="location.html" class="navigation navigation-prev " aria-label="Previous page"><i class="fa fa-angle-left"></i></a>
<a href="sensors.html" class="navigation navigation-next " aria-label="Next page"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="libs/gitbook-2.6.7/js/app.min.js"></script>
<script src="libs/gitbook-2.6.7/js/lunr.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-search.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-sharing.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-fontsettings.js"></script>
<script src="libs/gitbook-2.6.7/js/plugin-bookdown.js"></script>
<script src="libs/gitbook-2.6.7/js/jquery.highlight.js"></script>
<script>
gitbook.require(["gitbook"], function(gitbook) {
gitbook.start({
"sharing": {
"github": true,
"facebook": false,
"twitter": false,
"google": false,
"weibo": false,
"instapper": false,
"vk": false,
"all": ["github", "facebook", "twitter", "google"]
},
"fontsettings": {
"theme": "white",
"family": "sans",
"size": 2
},
"edit": {
"link": "https://github.com/info448/book/edit/master/services.Rmd",
"text": "Edit"
},
"download": ["android-development.pdf", "android-development.epub"],
"toc": {
"collapse": "section",
"scroll_highlight": true
}
});
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.bootcss.com/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML";
if (location.protocol !== "file:" && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>