-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
MediaNotificationManager.java
418 lines (368 loc) · 17.9 KB
/
MediaNotificationManager.java
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
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.app.NotificationCompat.MediaStyle;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import com.example.android.uamp.ui.MusicPlayerActivity;
import com.example.android.uamp.utils.LogHelper;
import com.example.android.uamp.utils.ResourceHelper;
/**
* Keeps track of a notification and updates it automatically for a given
* MediaSession. Maintaining a visible notification (usually) guarantees that the music service
* won't be killed during playback.
*/
public class MediaNotificationManager extends BroadcastReceiver {
private static final String TAG = LogHelper.makeLogTag(MediaNotificationManager.class);
private static final String CHANNEL_ID = "com.example.android.uamp.MUSIC_CHANNEL_ID";
private static final int NOTIFICATION_ID = 412;
private static final int REQUEST_CODE = 100;
public static final String ACTION_PAUSE = "com.example.android.uamp.pause";
public static final String ACTION_PLAY = "com.example.android.uamp.play";
public static final String ACTION_PREV = "com.example.android.uamp.prev";
public static final String ACTION_NEXT = "com.example.android.uamp.next";
public static final String ACTION_STOP = "com.example.android.uamp.stop";
public static final String ACTION_STOP_CASTING = "com.example.android.uamp.stop_cast";
private final MusicService mService;
private MediaSessionCompat.Token mSessionToken;
private MediaControllerCompat mController;
private MediaControllerCompat.TransportControls mTransportControls;
private PlaybackStateCompat mPlaybackState;
private MediaMetadataCompat mMetadata;
private final NotificationManager mNotificationManager;
private final PendingIntent mPlayIntent;
private final PendingIntent mPauseIntent;
private final PendingIntent mPreviousIntent;
private final PendingIntent mNextIntent;
private final PendingIntent mStopIntent;
private final PendingIntent mStopCastIntent;
private final int mNotificationColor;
private boolean mStarted = false;
public MediaNotificationManager(MusicService service) throws RemoteException {
mService = service;
updateSessionToken();
mNotificationColor = ResourceHelper.getThemeColor(mService, R.attr.colorPrimary,
Color.DKGRAY);
mNotificationManager = (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
String pkg = mService.getPackageName();
mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mStopIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_STOP).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mStopCastIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_STOP_CASTING).setPackage(pkg),
PendingIntent.FLAG_CANCEL_CURRENT);
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
/**
* Posts the notification and starts tracking the session to keep it
* updated. The notification will automatically be removed if the session is
* destroyed before {@link #stopNotification} is called.
*/
public void startNotification() {
if (!mStarted) {
mMetadata = mController.getMetadata();
mPlaybackState = mController.getPlaybackState();
// The notification must be updated after setting started to true
Notification notification = createNotification();
if (notification != null) {
mController.registerCallback(mCb);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_NEXT);
filter.addAction(ACTION_PAUSE);
filter.addAction(ACTION_PLAY);
filter.addAction(ACTION_PREV);
filter.addAction(ACTION_STOP_CASTING);
mService.registerReceiver(this, filter);
mService.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
}
}
}
/**
* Removes the notification and stops tracking the session. If the session
* was destroyed this has no effect.
*/
public void stopNotification() {
if (mStarted) {
mStarted = false;
mController.unregisterCallback(mCb);
try {
mNotificationManager.cancel(NOTIFICATION_ID);
mService.unregisterReceiver(this);
} catch (IllegalArgumentException ex) {
// ignore if the receiver is not registered.
}
mService.stopForeground(true);
}
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
LogHelper.d(TAG, "Received intent with action " + action);
switch (action) {
case ACTION_PAUSE:
mTransportControls.pause();
break;
case ACTION_PLAY:
mTransportControls.play();
break;
case ACTION_NEXT:
mTransportControls.skipToNext();
break;
case ACTION_PREV:
mTransportControls.skipToPrevious();
break;
case ACTION_STOP_CASTING:
Intent i = new Intent(context, MusicService.class);
i.setAction(MusicService.ACTION_CMD);
i.putExtra(MusicService.CMD_NAME, MusicService.CMD_STOP_CASTING);
mService.startService(i);
break;
default:
LogHelper.w(TAG, "Unknown intent ignored. Action=", action);
}
}
/**
* Update the state based on a change on the session token. Called either when
* we are running for the first time or when the media session owner has destroyed the session
* (see {@link android.media.session.MediaController.Callback#onSessionDestroyed()})
*/
private void updateSessionToken() throws RemoteException {
MediaSessionCompat.Token freshToken = mService.getSessionToken();
if (mSessionToken == null && freshToken != null ||
mSessionToken != null && !mSessionToken.equals(freshToken)) {
if (mController != null) {
mController.unregisterCallback(mCb);
}
mSessionToken = freshToken;
if (mSessionToken != null) {
mController = new MediaControllerCompat(mService, mSessionToken);
mTransportControls = mController.getTransportControls();
if (mStarted) {
mController.registerCallback(mCb);
}
}
}
}
private PendingIntent createContentIntent(MediaDescriptionCompat description) {
Intent openUI = new Intent(mService, MusicPlayerActivity.class);
openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
openUI.putExtra(MusicPlayerActivity.EXTRA_START_FULLSCREEN, true);
if (description != null) {
openUI.putExtra(MusicPlayerActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, description);
}
return PendingIntent.getActivity(mService, REQUEST_CODE, openUI,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private final MediaControllerCompat.Callback mCb = new MediaControllerCompat.Callback() {
@Override
public void onPlaybackStateChanged(@NonNull PlaybackStateCompat state) {
mPlaybackState = state;
LogHelper.d(TAG, "Received new playback state", state);
if (state.getState() == PlaybackStateCompat.STATE_STOPPED ||
state.getState() == PlaybackStateCompat.STATE_NONE) {
stopNotification();
} else {
Notification notification = createNotification();
if (notification != null) {
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
}
@Override
public void onMetadataChanged(MediaMetadataCompat metadata) {
mMetadata = metadata;
LogHelper.d(TAG, "Received new metadata ", metadata);
Notification notification = createNotification();
if (notification != null) {
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
@Override
public void onSessionDestroyed() {
super.onSessionDestroyed();
LogHelper.d(TAG, "Session was destroyed, resetting to the new session token");
try {
updateSessionToken();
} catch (RemoteException e) {
LogHelper.e(TAG, e, "could not connect media controller");
}
}
};
private Notification createNotification() {
LogHelper.d(TAG, "updateNotificationMetadata. mMetadata=" + mMetadata);
if (mMetadata == null || mPlaybackState == null) {
return null;
}
MediaDescriptionCompat description = mMetadata.getDescription();
String fetchArtUrl = null;
Bitmap art = null;
if (description.getIconUri() != null) {
// This sample assumes the iconUri will be a valid URL formatted String, but
// it can actually be any valid Android Uri formatted String.
// async fetch the album art icon
String artUrl = description.getIconUri().toString();
art = AlbumArtCache.getInstance().getBigImage(artUrl);
if (art == null) {
fetchArtUrl = artUrl;
// use a placeholder art while the remote art is being downloaded
art = BitmapFactory.decodeResource(mService.getResources(),
R.drawable.ic_default_art);
}
}
// Notification channels are only supported on Android O+.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel();
}
final NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(mService, CHANNEL_ID);
final int playPauseButtonPosition = addActions(notificationBuilder);
notificationBuilder
.setStyle(new MediaStyle()
// show only play/pause in compact view
.setShowActionsInCompactView(playPauseButtonPosition)
.setShowCancelButton(true)
.setCancelButtonIntent(mStopIntent)
.setMediaSession(mSessionToken))
.setDeleteIntent(mStopIntent)
.setColor(mNotificationColor)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setContentIntent(createContentIntent(description))
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setLargeIcon(art);
if (mController != null && mController.getExtras() != null) {
String castName = mController.getExtras().getString(MusicService.EXTRA_CONNECTED_CAST);
if (castName != null) {
String castInfo = mService.getResources()
.getString(R.string.casting_to_device, castName);
notificationBuilder.setSubText(castInfo);
notificationBuilder.addAction(R.drawable.ic_close_black_24dp,
mService.getString(R.string.stop_casting), mStopCastIntent);
}
}
setNotificationPlaybackState(notificationBuilder);
if (fetchArtUrl != null) {
fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
}
return notificationBuilder.build();
}
private int addActions(final NotificationCompat.Builder notificationBuilder) {
LogHelper.d(TAG, "updatePlayPauseAction");
int playPauseButtonPosition = 0;
// If skip to previous action is enabled
if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0) {
notificationBuilder.addAction(R.drawable.ic_skip_previous_white_24dp,
mService.getString(R.string.label_previous), mPreviousIntent);
// If there is a "skip to previous" button, the play/pause button will
// be the second one. We need to keep track of it, because the MediaStyle notification
// requires to specify the index of the buttons (actions) that should be visible
// when in compact view.
playPauseButtonPosition = 1;
}
// Play or pause button, depending on the current state.
final String label;
final int icon;
final PendingIntent intent;
if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
label = mService.getString(R.string.label_pause);
icon = R.drawable.uamp_ic_pause_white_24dp;
intent = mPauseIntent;
} else {
label = mService.getString(R.string.label_play);
icon = R.drawable.uamp_ic_play_arrow_white_24dp;
intent = mPlayIntent;
}
notificationBuilder.addAction(new NotificationCompat.Action(icon, label, intent));
// If skip to next action is enabled
if ((mPlaybackState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0) {
notificationBuilder.addAction(R.drawable.ic_skip_next_white_24dp,
mService.getString(R.string.label_next), mNextIntent);
}
return playPauseButtonPosition;
}
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
LogHelper.d(TAG, "updateNotificationPlaybackState. mPlaybackState=" + mPlaybackState);
if (mPlaybackState == null || !mStarted) {
LogHelper.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
mService.stopForeground(true);
return;
}
// Make sure that the notification can be dismissed by the user when we are not playing:
builder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
private void fetchBitmapFromURLAsync(final String bitmapUrl,
final NotificationCompat.Builder builder) {
AlbumArtCache.getInstance().fetch(bitmapUrl, new AlbumArtCache.FetchListener() {
@Override
public void onFetched(String artUrl, Bitmap bitmap, Bitmap icon) {
if (mMetadata != null && mMetadata.getDescription().getIconUri() != null &&
mMetadata.getDescription().getIconUri().toString().equals(artUrl)) {
// If the media is still the same, update the notification:
LogHelper.d(TAG, "fetchBitmapFromURLAsync: set bitmap to ", artUrl);
builder.setLargeIcon(bitmap);
addActions(builder);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
});
}
/**
* Creates Notification Channel. This is required in Android O+ to display notifications.
*/
@RequiresApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel notificationChannel =
new NotificationChannel(CHANNEL_ID,
mService.getString(R.string.notification_channel),
NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription(
mService.getString(R.string.notification_channel_description));
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
}