-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathservices.Rmd
More file actions
463 lines (319 loc) · 38.6 KB
/
services.Rmd
File metadata and controls
463 lines (319 loc) · 38.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
# Threads and Services {#services}
<p class="alert alert-warning">This lecture is currently under revision.</p>
This lecture discusses a component of Android development that is ___not___ immediately visible to users: [**Services**](https://developer.android.com/guide/components/services.html)^[https://developer.android.com/guide/components/services.html]. _Services_ 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 _even after the starting component is closed_. 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 ["priority"](https://developer.android.com/guide/topics/processes/process-lifecycle.html) and so aren't killed as readily).
Some common uses for a Service include:
- Downloading or uploading data from/to a network in the background even if the app is closed
- Saving data to a database without crashing if the user leaves the app
- Running some other kind of long-running, "background" task even after the app is closed, such as playing music!
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 class="alert alert-info">This lecture references code found at <https://github.com/info448/lecture13-services>.</p>
## Threads and Processes
**Concurrency** is the process by which we have multiple _processes_ (think: methods) running at the same time. This can be contrasted with processes that run **serially**, or one after another.
For example, if you call two methods one after the other, then the second method execute will "wait" for the first one to finished:
```java
//java
public void countUp() {
for(int i=0; i<1000; i++){
System.out.println(i);
}
}
public void countDown() {
for(int i=0; i> -1000; i--){
System.out.println(i);
}
}
countUp(); //start counting up
countDown(); //start counting down (once finished going up)
```
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
- The standard measure for _rate_ (how many times per second) is the `hertz` (Hz). So a 2 gigahertz (GHz) processor can do 2 billion operations per second.
However, we don't realize that computers do only one thing at a time! This is because computers are really good at _multitasking_: 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.

These "tasks" are divided up into two types: **processes** and **threads**. ___Read [this brief summary](https://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html) of the difference between them___.
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 _especially_ useful if one of the "tasks" might take a really long time—rather than **blocking** the application, we can let other tasks also make some progress while we're waiting for the long task to finish.
### Java Threads {-}
In Java, we create a Thread by creating a class that `implements` the [**`Runnable`**](https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) interface. This represents a class that can be "run" in a separate thread! The `run()` 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.
If we just instantiate the `Runnable()` and call its `run()` 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 [**`Thread`**](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html) class. This class actually does the work of running code on a separate thread.
`Thread` has a [constructor](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable-) that takes in a `Runnable` instance as a parameter—you pass an object representing the "code to run" to the `Thread` object (this is an example of the _Strategy Pattern_). You then can actually **start** the `Thread` by calling its `.start()` method (_not_ the `run` method!).
- Anonymous variables will be useful here; you don't need to assign a variable name to the `Runnable` objects or even the `Thread` objects if you just use them directly.
For example, making the above `countUp()` and `countDown()` 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").
<!-- TODO: example detail -->
### Android Threads {-}
Android apps run by default on the ___Main Thread___ (also called the ___UI Thread___). This thread is in charge of all user interactions—handling button presses, scrolls, drags, etc.—but also UI _output_ like drawing and displaying text! See [Android Threads](https://developer.android.com/guide/components/processes-and-threads.html#Threads) for more details.
- 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
Within a single thread, all method calls are **synchronous**—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!
- Tasks such as network access are **blocking** method calls, which stop the Thread from continuing. A blocked _Main Thread_ will lead to the infamous **"Application not responding" (ANR)** error!
Thus we need to move any "slow" code (such as network access) _off_ the Main Thread, onto a **background thread**, 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 [`ASyncTask`](https://developer.android.com/reference/android/os/AsyncTask.html)^[https://developer.android.com/reference/android/os/AsyncTask.html] to perform a task (such as network access) asynchronously—without waiting for other Threads.
<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) `ASyncTask` class? We started from the official API Guide on [Processes and Threads Guide](https://developer.android.com/guide/components/processes-and-threads.html)^[https://developer.android.com/guide/components/processes-and-threads.html], which introduces this class! Thus to learn about new Android options, _read the docs_.</p>
Note that an `ASyncTask` background thread will be _tied to the lifecycle of the Activity_: if we close the Activity, the network connection will die as well. A better option is often to use a `Service`, described below.
`ASyncTask` 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 `ASyncTask` is **`abstract`**, meaning you'll need to _subclass_ it in order to use it. Thus you can subclass it as an _inner_ class inside the Activity that will use it.
<!-- TODO: example detail -->
You should also notice that `ASyncTask` is a _generic_ 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 `String` and return a `String[]`). You can use the `Void` type for an unspecified type, such as with Progress measurement if you aren't tracking that.
- We can actually pass in multiple `String` arguments using the `String... params` spread operator syntax (representing an arbitrary number of items of that type). See [here](https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs) for details. The value that the `ASyncTask` methods _actually_ get is an array of the arguments.
When you "run" an AsyncTask, it will do four (4) things, represented by four methods:
1. `onPreExecute()` is called _on the UI thread_ before it runs the task. This method can be used to perform any setup for the task.
2. `doInBackground(Params...)` is called _on the background thread_ to do the work you want to be performed asynchronously. You **must** override this method (it's `abstract`!) The params and return type for the method need to match the `ASyncTask` generic types.
3. `onProgressUpdate()` can be indirectly called _on the UI thread_ if we want to update our progress (e.g., update a progress bar). Note that UI changes can **only** be made on the UI thread!
4. `onPostExecute(Result)` is called _on the UI thread_ to process any task results, which are passed as parameters to this method when `doInBackground` is finished.
The `doInBackground()` 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.
We can then _instantiate_ a new `ASyncTask` object in the Activity's `onCreate()` callback, and call `ASyncTask#execute(params)` to start the task running on its own thread.
In order to get any results back into the rendered View, you utilize the `doPostExecute()` method. This method is run on the _UI Thread_ so you can use it to update the View (we can _only_ change the View on the UI Thread, to avoid collisions). It also gets the results _returned_ by `doInBackground()` passed to it automatically!
- E.g., you can take a resulting `String[]` and put that into an `Adapter` for a `ListView`.
`ASyncTask` is the simplest, general way to do some work on a background thread. However, it has a few limitations:
- The lifecycle of an `ASyncTask` is tied to that of its containing Activity. This means that if the containing Activity is destroyed (e.g., is `finished()`), then the the ASyncTask is as well—you would lose any data you were downloading or might corrupt your database in some way.
- To handle lots of different background tasks, you would need to do your own task management.
As such, repeated or longer-lasting tasks (such as large file downloads) are often better handled through **Services**.
## IntentServices
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).
- An important thing to note about Services: a Service is **not** a separate process; it runs in the same process as the app that starts it (unless otherwise specified). Similarly, a Service is **not** a Thread, and in fact doesn't need to run outside the UI thread! However, we quite often _do_ want to run the service outside of the UI Thread, and so often have it spawn and run a new `Runnable` Thread. When we say a Service runs "in the background", we mean from a user's perspective rather than necessarily on a background thread.
To create a Service, we're going to subclass [`Service`](https://developer.android.com/reference/android/app/Service.html) and override some _lifecycle callbacks_, just like we've done with `Activity`, `Fragment`, `BroadcastReceiver`, and most other Android components. In this sense, Services are in fact implemented like Activities that run without a user interface ("in the background").
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 `Service` subclass we can use to do exactly this work. This class is called [`IntentService`](https://developer.android.com/reference/android/app/IntentService.html)—a service that responds to `Intents` and does some work in response to them.
- An IntentService does a similar job to `ASyncTask`, but with the advantage that it will keep doing that work even if the Activity is destroyed!
- `IntentService` will listen to any incoming "requests" (`Intents`) 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 `Intents` are sent to it). Basically, it handles a lot of the setup and cleanup involved in using a Service on its own!
- (This lecture will start with `IntentService` because it's simpler, and then move into the more generic, complex version of Services).
We create an IntentService by defining a new class (e.g., `CountingService`) that subclasses `IntentService`.
- Implement a default _constructor_ that can call `super(String nameForDebugging)`. This allows the class to be instantiated (by the Android framework; again, like an Activity).
- Also implement the `onHandleIntent(Intent)` method. Incoming `Intents` 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 **background thread** supplied by `IntentService`.
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.
```java
//java
for(int count=0; count<=10; count++){
Log.v(TAG, "Count: "+count);
try {
Thread.sleep(2000); //sleep for 2 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
```
```kotlin
//kotlin
for (count in 0..10) {
Log.v(TAG, "Count: $count")
try {
Thread.sleep(2000) //sleep for 2 seconds
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}
```
Just like with Activities, we also need to declare the `<service>` in the Manifest, as a child of the `<application>`:
```xml
<service android:name=".CountingService" />
```
Finally, we can send an `Intent` to the Service by using the `startService()` method. This is similar to `startActivity()`, 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.
- 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.
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 _inter-thread communication_: we need to get a message (a function call) from the background thread to the UI Thread.
- This is what various `ASyncTask` UI thread methods (such as `onProgressUpdate()`) do for us.
We can perform this communication using a [`Handler`](https://developer.android.com/reference/android/os/Handler.html), which is an object used to pass messages between Threads—it "handles" the messages!
- We instantiate a `new Handler()` object (e.g., in the Service's `onCreate()` 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 `post()` function, which takes a `Runnable()` method which will be executed _on the Main Thread_:
```java
//java
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(CountingService.this, "Count: " + count, Toast.LENGTH_SHORT).show();
}
});
```
```kotlin
//kotlin
mHandler.post {
Toast.makeText(this@CountingService, "Count: $count", Toast.LENGTH_SHORT).show()
Log.v(TAG, "" + count)
}
```
### The Service Lifecycle {-}
Having demonstrated the basic usage of a service, consider what is going on "under the hood"—starting with the [Service lifecycle](https://developer.android.com/guide/components/services.html#LifecycleCallbacks). There are actually two different "types" of Services, with different variations of the lifecycle. **Started Services** (or "unbound" Services) are those that are initiated via the `startService()` function, as in the above example. The other option, **Bound Services**, are Services that have "client" Activities bound to them to interact with; see below for details.
![Service lifecycle diagram, from Google^[https://developer.android.com/images/service_lifecycle.png]](img/services/service_lifecycle.png)
- Just like with Activities, Services have an `onCreate()` 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.
- 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.
- The most important callback for a _Started Service_ is called `onStartCommand()`. This method is called when the Service is **sent a command** by another component (via an Intent). Importantly, `onStartCommand()` 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 `startService()`.
- Note that when working with an _`IntentService`_ specifically, `onStartCommand()` will "queue" any incoming Intents. When it is the specific Intent's turn to be "run", that Intent is automatically passed to the `onHandleIntent()` method, which executes on a _background thread_ (similar to `AsyncTask#doInBackground()`). This callback is not part of the normal Service lifecycle, but is a special helper method used by IntentService—similar to how `onCreateDialog()` is a special method used by `DialogFragments`.
- The `onBind()` and `onUnbind()` callbacks are used for bound services, and are discussed below.
- IntentService does have a default `onBind()` implementation that returns `null`.
- Finally, Services have an `onDestroy()` callback, which is again equivalent to the Activity callback.
- In general, Services have to be manually told to **stop**. We stop a Service by using `stopService(Intent)` to send that Service a "stop" Intent. The Service can also stop itself by calling `stopSelf()`.
- _Important_: When told to stop, an `IntentService` 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 `stopSelf()`, thereby causing the `onDestroy()` callback to be executed.
___Practice:___ fill in the callback functions with Log or Toast messages to see how and when they are executed. For example:
```java
//java
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Intent received", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
```
As a last point to note about the Service lifecycle consider the `int` that is returned by `onStartCommand()`. This `int` is a flag that indicates how the Service should [behave](https://developer.android.com/guide/components/services.html#ExtendingService)^[https://developer.android.com/guide/components/services.html#ExtendingService] when it is "restarted" after having been destroyed:
- [`START_NOT_STICKY`](https://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY) 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.
- [`START_STICKY`](https://developer.android.com/reference/android/app/Service.html#START_STICKY) indicates that if the Service is destroyed by the system, it should be recreated when possible. At that point, `onStartCommand()` will be called by delivering a `null` 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).
- [`START_REDELIVER_INTENT`](https://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT) indicates that if the Service is destroyed by the system, it should be recreated when possible. At that point, `onStartCommand()` will be called with the _last_ 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.
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 `START_REDELIVER_INTENT`, but the Intent to play the music file might return `START_STICKY`.
<!-- TODO continue editing -->
## Example: A Music Service
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 [use a Service](http://developer.android.com/guide/topics/media/mediaplayer.html#mpandservices). Services have higher "priority" in the eyes of the Android system, and so don't get sacrificed for resources as readily as normal Activities.
### MediaPlayer {-}
In order to make a music service, we need to briefly explain how to play music with [`MediaPlayer`](https://developer.android.com/guide/topics/media/mediaplayer.html). This is the main API for playing sound and video (e.g., if you want to play `.mp3` files).
<p class="alert alert-info">Android actually has a total of three (3) audio APIs! The [`SoundPool`](https://developer.android.com/reference/android/media/SoundPool.html) 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 [`AudioTrack`](http://developer.android.com/reference/android/media/AudioTrack.html) 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>
`MediaPlayer` is very simple to use, particularly when playing a locally defined resource (e.g., something in `res/raw/`). You simply use a factory to make a new `MediaPlayer` object, and then call `.play()` on it:
```java
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.my_sound_file);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
```
We can also call `.pause()` to pause the music, `.seekTo()` to jump to a particular millisecond, and `.stop()` to stop the music.
- Note that when we `stop()`, we also need to release any resources used by the `MediaPlayer` (to free up memory):
```java
mediaPlayer.release();
mediaPlayer = null;
```
We can also implement and register a `MediaPlayer.OnCompletionListener` to do something when a song finishes playing.
Finally, it is possible to use `MediaPlayer` to play files from a `ContentProvider` or even off the Internet!
```java
//java
String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync(); //prepare media in the background (buffering, etc)
//.prepare() for synchronous buffering
mediaPlayer.setOnPreparedListener(this); //handle when file is buffered
mediaPlayer.start();
```
### Creating a Service {-}
In order to make our music service, we are going to subclass the `Service` class itself (_don't forget to include the Service in the `Manifest`_) and manually set up all the pieces. Specifically, we will fill in the lifecycle callbacks:
- `onCreate()` we can include, though it doesn't need to do anything.
- `onStartCommand()` should create and start our MediaPlayer. We can return `START_NOT_STICKY` so the music doesn't start up again randomly if the system needs to destroy the Service (since it won't get recreated).
_Important:_ 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 `create()` method). However, this may not be necessary for MediaPlayer when loading resources.
- `onDestroy()` can stop, release, and clean-up the MediaPlayer. We can implement this in a separate helper function for reuse.
- 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.
We can now have our Activity `startService()` and `stopService()` in order to play our music in the "background", even if we leave and return to the Activity!
## Foreground Services
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 _is_ 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).
To do this, we use what is called a [**Foreground Service**](https://developer.android.com/guide/components/services.html#Foreground). Foreground Services represent Services that are divorced from Activities (they _are_ Services after all), but the user is aware of them—and accordingly, have an even higher survival [priority](https://developer.android.com/guide/topics/processes/process-lifecycle.html) if the OS gets low on memory!
Foreground services require a **Notification** 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!
We create this Notification inside the Service's `onStartCommand()` method, then pass it to the `startForeground()` method in order to put our Service in the foreground:
```java
//java, pre-Oreo
String songName = "The Entertainer";
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentTitle("Music Player")
.setContentText("Now playing: "+songName)
.setContentIntent(pendingIntent)
.setOngoing(true) //cannot be dismissed by the user
.build();
startForeground(NOTIFICATION_ID, notification); //make this a foreground service!
```
```kotlin
//kotlin
val songName = "The Entertainer"
val pendingIntent = PendingIntent.getActivity(applicationContext, 0,
Intent(applicationContext, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Demo channel", NotificationManager.IMPORTANCE_LOW)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentTitle("Music Player")
.setContentText("Now playing: $songName")
.setContentIntent(pendingIntent)
.setOngoing(true) //cannot be dismissed by the user
.build()
startForeground(NOTIFICATION_ID, notification) //make this a foreground service!
```
Some details about this Notification:
- We build and set the icon, title, and text as in the previous lecture.
- We give the Notification a `PendingIntent` to run when selected. This PendingIntent can just open up our `MainActivity`, allowing us to control the Player. (Alternatively, we could use [Notification Actions](https://developer.android.com/guide/topics/ui/notifiers/notifications.html#controllingMedia) to control the music directly).
- We set the Notification to be _ongoing_, in order to enforce that it cannot be dismissed by the user.
_Importantly_, once we are done doing foreground work (e.g., playing music), we should call `stopForeground(true)` to get rid of the foreground service. This is a good thing to do in our `stopMusic()` helper (called from `onDestroy()`).
<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 [guide](https://developer.android.com/guide/topics/media/mediaplayer.html) for more details.</p>
## Bound Services
As mentioned above, there are two "types" of Services: **Started Services** (Services launched with `startService()`) and **Bound Services**. A [Bound Service](https://developer.android.com/guide/components/bound-services.html) is a Service that acts as the "server" in a client-server setup: it allows for client Activities to "connect" to it (___bind it___) and then exchange messages with it—primarily by calling methods on the Service. These messages can even be _across processes_, allowing for [interprocess communication](https://en.wikipedia.org/wiki/Inter-process_communication)! This is useful when you want interact with the Service from an Activity in some way (e.g., if we want to `pause()` our music), or if we want to make the service's capabilities available to other applications.
We make a Bound Service by having the Service implement and utilize the **`onBind()`** callback. This method returns an `IBinder` object (the `I` indicates that it's an _Interface_, following a Java convention common in enterprise software). When Activities connect to this Service (using the `bindService()` method), this `IBinder` 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 _object_ that represents that Service, so Activities can call methods on the Service without needing to send it Intents!
As an example, let's add the ability to "pause" the music being played as a bound service:
The first thing we need to do is have our Service implement the `onBind()` method. To do this, we will need an `IBinder` object to return (that is: an object of a class that implements the `IBinder` interface). For "local services" (e.g., Services that are run _in the same process_), the easiest way to get an `IBinder` is to extend the `Binder` class:
```java
//kotlin
public class MyBinder extends Binder { //implements IBinder
//binder class methods will go here!
}
private final IBinder mBinder = new MyBinder(); //singleton instance variable
```
```kotlin
//kotlin
class LocalBinder : Binder() {
//binder class methods will go here!
}
private val mLocalBinder = LocalBinder() //singleton instance variable
```
- Our local version starts "empty" for now; we'll add details below.
- We will just return this object from `onBind()`.
Because the Activity is given a copy of this `MyBinder` object, that class can be designed to support the Activity communicating with the Service in a couple of different ways:
1. The `IBinder` can provide `public` methods for the Activity to call. These methods can then access instance variables of the Service (since the `MyBinder` is a nested class). This causes the `IBinder` to literally act as the "public interface" for the Service!
```java
//in MyBinder
public String getSongName() {
return songName; //access Service instance variable
}
```
2. The `IBinder` can provide access to the Service itself (via a getter that returns the `Service` object). The Activity can then call any public methods provided by that `Service` class.
```java
//in MyBinder
public MusicService getService() {
// Return this instance of this Service so clients can call public methods on it!
return MusicService.this;
}
```
3. The `IBinder` can provide access to some other object "owned" by the Service, which the Activity can then call methods on (e.g., the `MediaPlayer`). This is somewhat like a compromise between the first two options: you don't need to implement a specific public interface on the `IBinder`, but you also don't have to provide full access to your Service object! This is good for only exposing part of the Service.
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)">`bindService(Intent, ServiceConnection, flag)`</a>. We can do this whenever we want the Service to be available (`onStart()` is a good option, so it is available when the Activity is active).
- The Intent parameter should be addressed to the Service we want to bind.
- The `ServiceConnection` parameter is a reference to an object that implements the `ServiceConnection` 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:
```java
//java
/** Defines callbacks for service binding, passed to bindService() */
/** From Android documentation */
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MyBinder binder = (MyBinder) service;
mService = binder.getService();
mBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
```
```kotlin
//kotlin
/** Defines callbacks for service binding, passed to bindService() */
/** From Android documentation */
private val mConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
val binder = service as LocalService.LocalBinder
mService = binder.getService()
mBound = true
}
override fun onServiceDisconnected(arg0: ComponentName) {
mBound = false
}
}
```
The `onServiceConnected()` callback handles the actual connection, and is where we get access to that `IBinder`. We can use that `IBinder` 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 `null` errors.
- Finally, the `flag` parameter indicates some options for how the Service should be bound (e.g., for specifying survival priority). `Conetxt.BIND_AUTO_CREATE` is a good default, specifying that the binding should create the Service object if needed.
Once a Service is bound, we can call methods on that Service (which must exist!)—allowing us to support the "pause" button.
We should also call `unbindService()` when the Activity stops, in order to free up resources:
```java
protected void onStop() {
if (mBound) {
unbindService(this);
}
super.onStop();
}
```
<p class="alert alert-info">Keep in mind that binding a Service **DOES NOT** call `onStartCommand()`, 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 `startService()`), we will need to remember to stop it later!</p>
This example is just for _local services_ (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 `Handler` and `Messenger` objects to pass messages between these processes (similar to the example we did for passing messages between threads); for more details, see [the example in the guide](https://developer.android.com/guide/components/bound-services.html#Messenger), as well as the complete sample classes [`MessengerService`](https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.java) and [`MessengerServiceActivities`](https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java).