forked from doublesymmetry/react-native-track-player
-
Notifications
You must be signed in to change notification settings - Fork 16
/
NotificationManager.kt
872 lines (790 loc) · 34.5 KB
/
NotificationManager.kt
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
package com.doublesymmetry.kotlinaudio.notification
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.RatingCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationCompat
import coil.imageLoader
import coil.request.Disposable
import coil.request.ImageRequest
import jp.wasabeef.transformers.coil.CropSquareTransformation
import com.doublesymmetry.kotlinaudio.event.NotificationEventHolder
import com.doublesymmetry.kotlinaudio.event.PlayerEventHolder
import com.doublesymmetry.kotlinaudio.models.AudioItem
import com.doublesymmetry.kotlinaudio.models.MediaSessionCallback
import com.doublesymmetry.kotlinaudio.models.NotificationButton
import com.doublesymmetry.kotlinaudio.models.NotificationConfig
import com.doublesymmetry.kotlinaudio.models.NotificationState
import com.doublesymmetry.kotlinaudio.players.components.getAudioItemHolder
import com.doublesymmetry.kotlinaudio.utils.saveMediaCoverToPng
import com.doublesymmetry.trackplayer.R
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.ui.PlayerNotificationManager.CustomActionReceiver
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.Headers
import okhttp3.Headers.Companion.toHeaders
class NotificationManager internal constructor(
private val context: Context,
private val player: Player,
private val mediaSession: MediaSessionCompat,
private val mediaSessionConnector: MediaSessionConnector,
val event: NotificationEventHolder,
val playerEventHolder: PlayerEventHolder
) : PlayerNotificationManager.NotificationListener {
private var pendingIntent: PendingIntent? = null
private val descriptionAdapter = object : PlayerNotificationManager.MediaDescriptionAdapter {
override fun getCurrentContentTitle(player: Player): CharSequence {
return getTitle() ?: ""
}
override fun createCurrentContentIntent(player: Player): PendingIntent? {
return pendingIntent
}
override fun getCurrentContentText(player: Player): CharSequence? {
return getArtist() ?: ""
}
override fun getCurrentSubText(player: Player): CharSequence? {
return player.mediaMetadata.displayTitle
}
override fun getCurrentLargeIcon(
player: Player,
callback: PlayerNotificationManager.BitmapCallback,
): Bitmap? {
val bitmap = getCachedArtworkBitmap()
if (bitmap != null) {
return bitmap
}
val artwork = getMediaItemArtworkUrl()
val headers = getNetworkHeaders()
val holder = player.currentMediaItem?.getAudioItemHolder()
if (artwork != null && holder?.artworkBitmap == null) {
var imgrequest = ImageRequest.Builder(context)
.data(artwork)
if (Build.MANUFACTURER == "samsung") {
imgrequest = imgrequest.transformations(CropSquareTransformation())
}
context.imageLoader.enqueue(
imgrequest
.headers(headers)
.target { result ->
val resultBitmap = (result as BitmapDrawable).bitmap
holder?.artworkBitmap = resultBitmap
invalidate()
}
.build()
)
}
return iconPlaceholder
}
}
private var internalNotificationManager: PlayerNotificationManager? = null
private val scope = MainScope()
private val buttons = mutableSetOf<NotificationButton?>()
private var invalidateThrottleCount = 0
private var iconPlaceholder = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888)
private var notificationMetadataBitmap: Bitmap? = null
private var notificationMetadataArtworkDisposable: Disposable? = null
/**
* The item that should be used for the notification
* This is used when the user manually sets the notification item
*
* _Note: If [BaseAudioPlayer.automaticallyUpdateNotificationMetadata] is true, this will
* get override on a track change_
*/
internal var overrideAudioItem: AudioItem? = null
set(value) {
notificationMetadataBitmap = null
val headers = getNetworkHeaders()
if (field != value) {
if (value?.artwork != null) {
notificationMetadataArtworkDisposable?.dispose()
notificationMetadataArtworkDisposable = context.imageLoader.enqueue(
ImageRequest.Builder(context)
.data(value.artwork)
.headers(headers)
.target { result ->
notificationMetadataBitmap = (result as BitmapDrawable).bitmap
invalidate()
}
.build()
)
}
}
field = value
invalidate()
}
private fun getTitle(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
val audioItem = mediaItem?.getAudioItemHolder()?.audioItem
return overrideAudioItem?.title
?:mediaItem?.mediaMetadata?.title?.toString()
?: audioItem?.title
}
private fun getArtist(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
val audioItem = mediaItem?.getAudioItemHolder()?.audioItem
return overrideAudioItem?.artist
?: mediaItem?.mediaMetadata?.artist?.toString()
?: mediaItem?.mediaMetadata?.albumArtist?.toString()
?: audioItem?.artist
}
private fun getGenre(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
return mediaItem?.mediaMetadata?.genre?.toString()
}
private fun getAlbumTitle(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
return mediaItem?.mediaMetadata?.albumTitle?.toString()
?: mediaItem?.getAudioItemHolder()?.audioItem?.albumTitle
}
private fun getMediaId(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
return mediaItem?.getAudioItemHolder()?.audioItem?.mediaId
}
private fun getArtworkUrl(index: Int? = null): String? {
return getMediaItemArtworkUrl(index)
}
private fun getMediaItemArtworkUrl(index: Int? = null): String? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
return overrideAudioItem?.artwork
?: mediaItem?.mediaMetadata?.artworkUri?.toString()
?: mediaItem?.getAudioItemHolder()?.audioItem?.artwork
}
private fun getNetworkHeaders(): Headers {
return player.currentMediaItem?.getAudioItemHolder()?.audioItem?.options?.headers?.toHeaders() ?: Headers.Builder().build()
}
/**
* Returns the cached artwork bitmap for the current media item.
* Bitmap might be cached if the media item has extracted one from the media file
* or if a user is setting custom data for the notification.
*/
private fun getCachedArtworkBitmap(index: Int? = null): Bitmap? {
val mediaItem = if (index == null) player.currentMediaItem else player.getMediaItemAt(index)
val isCurrent = index == null || index == player.currentMediaItemIndex
val artworkData = player.mediaMetadata.artworkData
return if (isCurrent && overrideAudioItem != null) {
notificationMetadataBitmap
} else if (isCurrent && artworkData != null) {
BitmapFactory.decodeByteArray(artworkData, 0, artworkData.size)
} else {
mediaItem?.getAudioItemHolder()?.artworkBitmap
}
}
private fun getDuration(index: Int? = null): Long? {
val mediaItem = if (index == null) player.currentMediaItem
else player.getMediaItemAt(index)
return if (player.isCurrentMediaItemDynamic || player.duration == C.TIME_UNSET) {
overrideAudioItem?.duration ?: mediaItem?.getAudioItemHolder()?.audioItem?.duration ?: -1
} else {
overrideAudioItem?.duration ?: player.duration
}
}
private fun getUserRating(index: Int? = null): RatingCompat? {
val mediaItem = if (index == null) player.currentMediaItem
else player.getMediaItemAt(index)
return RatingCompat.fromRating(mediaItem?.mediaMetadata?.userRating)
}
var showPlayPauseButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUsePlayPauseActions(value)
}
}
var showStopButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseStopAction(value)
}
}
var showForwardButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseFastForwardAction(value)
}
}
/**
* Controls whether or not this button should appear when the notification is compact (collapsed).
*/
var showForwardButtonCompact = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseFastForwardActionInCompactView(value)
}
}
var showRewindButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseRewindAction(value)
}
}
/**
* Controls whether or not this button should appear when the notification is compact (collapsed).
*/
var showRewindButtonCompact = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseRewindActionInCompactView(value)
}
}
var showNextButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseNextAction(value)
}
}
/**
* Controls whether or not this button should appear when the notification is compact (collapsed).
*/
var showNextButtonCompact = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUseNextActionInCompactView(value)
}
}
var showPreviousButton = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUsePreviousAction(value)
}
}
/**
* Controls whether or not this button should appear when the notification is compact (collapsed).
*/
var showPreviousButtonCompact = false
set(value) {
scope.launch {
field = value
internalNotificationManager?.setUsePreviousActionInCompactView(value)
}
}
var stopIcon: Int? = null
var forwardIcon: Int? = null
var rewindIcon: Int? = null
var customIcons: MutableMap<String, Int?> = mutableMapOf()
init {
mediaSessionConnector.setQueueNavigator(
object : TimelineQueueNavigator(mediaSession) {
override fun getSupportedQueueNavigatorActions(player: Player): Long {
return buttons.fold(0) { acc, button ->
acc or when (button) {
is NotificationButton.NEXT -> {
PlaybackStateCompat.ACTION_SKIP_TO_NEXT
}
is NotificationButton.PREVIOUS -> {
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
}
else -> {
0
}
}
}
}
override fun getMediaDescription(
player: Player,
windowIndex: Int
): MediaDescriptionCompat {
val title = getTitle(windowIndex)
val artist = getArtist(windowIndex)
val mediaItem = if (windowIndex == null) player.currentMediaItem else player.getMediaItemAt(windowIndex)
val audioItemHolder = mediaItem?.getAudioItemHolder()
return MediaDescriptionCompat.Builder().apply {
setTitle(title)
setSubtitle(artist)
setExtras(Bundle().apply {
title?.let {
putString(MediaMetadataCompat.METADATA_KEY_TITLE, it)
}
artist?.let {
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, it)
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, it)
}
})
setIconUri(mediaItem?.mediaMetadata?.artworkUri ?: Uri.parse(audioItemHolder?.audioItem?.artwork
?: ""))
setIconBitmap(audioItemHolder?.artworkBitmap)
setMediaId(audioItemHolder?.audioItem?.mediaId)
}.build()
}
}
)
mediaSessionConnector.setMetadataDeduplicationEnabled(true)
}
/**
* Overrides the notification metadata with the given [AudioItem].
*
* _Note: If [BaseAudioPlayer.automaticallyUpdateNotificationMetadata] is true, this will
* get override on a track change._
*/
public fun overrideMetadata(item: AudioItem) {
overrideAudioItem = item
}
public fun getMediaMetadataCompat(): MediaMetadataCompat {
val currentItemMetadata = player.currentMediaItem?.mediaMetadata
return MediaMetadataCompat.Builder().apply {
getMediaId()?.let {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, it)
}
getArtist()?.let {
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, it)
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, it)
}
getTitle()?.let {
putString(MediaMetadataCompat.METADATA_KEY_TITLE, it)
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, it)
}
currentItemMetadata?.subtitle?.let {
putString(
MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, it.toString()
)
}
currentItemMetadata?.description?.let {
putString(
MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, it.toString()
)
}
getAlbumTitle()?.let {
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, it)
}
getMediaId()?.let {
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, it)
}
getGenre()?.let {
putString(MediaMetadataCompat.METADATA_KEY_GENRE, it)
}
getDuration()?.let {
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, it)
}
getArtworkUrl()?.let {
val cachedArtworkBitmap = getCachedArtworkBitmap()
if (it != "null") {
putString(MediaMetadataCompat.METADATA_KEY_ART_URI, it)
// HACK: fix blurry thumbnail (why?)
putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, cachedArtworkBitmap)
putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, cachedArtworkBitmap)
} else {
val cachedBitmapURI = saveMediaCoverToPng(
player.currentMediaItem?.getAudioItemHolder()?.audioItem?.audioUrl,
contentResolver = context.contentResolver,
// HACK: this method is called 2/4 times
// HACK: mediaId is null; currentMetadata doesnt change; what to use?
cacheKey = "${player.currentMediaItemIndex}-${getTitle()}"
)
if (cachedBitmapURI != null) {
putString(MediaMetadataCompat.METADATA_KEY_ART_URI, cachedBitmapURI)
} else {
putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, cachedArtworkBitmap)
putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, cachedArtworkBitmap)
}
}
}
getUserRating()?.let {
putRating(MediaMetadataCompat.METADATA_KEY_RATING, it)
}
}.build()
}
private fun createNotificationAction(
drawable: Int,
action: String,
instanceId: Int
): NotificationCompat.Action {
val intent: Intent = Intent(action).setPackage(context.packageName)
val pendingIntent = PendingIntent.getBroadcast(
context,
instanceId,
intent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
)
return NotificationCompat.Action.Builder(drawable, action, pendingIntent).build()
}
private fun handlePlayerAction(action: String) {
when (action) {
REWIND -> {
playerEventHolder.updateOnPlayerActionTriggeredExternally(MediaSessionCallback.REWIND)
}
FORWARD -> {
playerEventHolder.updateOnPlayerActionTriggeredExternally(MediaSessionCallback.FORWARD)
}
STOP -> {
playerEventHolder.updateOnPlayerActionTriggeredExternally(MediaSessionCallback.STOP)
}
else -> {
playerEventHolder.updateOnPlayerActionTriggeredExternally(MediaSessionCallback.CUSTOMACTION(action))
}
}
}
private val customActionReceiver = object : CustomActionReceiver {
override fun createCustomActions(
context: Context,
instanceId: Int
): MutableMap<String, NotificationCompat.Action> {
if (!needsCustomActionsToAddMissingButtons) return mutableMapOf()
val actionMap = mutableMapOf(
REWIND to createNotificationAction(
rewindIcon ?: DEFAULT_REWIND_ICON,
REWIND,
instanceId
),
FORWARD to createNotificationAction(
forwardIcon ?: DEFAULT_FORWARD_ICON,
FORWARD,
instanceId
),
STOP to createNotificationAction(
stopIcon ?: DEFAULT_STOP_ICON,
STOP,
instanceId
)
)
customIcons.forEach { (key, value) ->
actionMap[key] = createNotificationAction(value?: DEFAULT_STOP_ICON, key, instanceId)
}
return actionMap
}
override fun getCustomActions(player: Player): List<String> {
if (!needsCustomActionsToAddMissingButtons) return emptyList()
return buttons.mapNotNull {
when (it) {
is NotificationButton.BACKWARD -> {
REWIND
}
is NotificationButton.FORWARD -> {
FORWARD
}
is NotificationButton.STOP -> {
STOP
}
is NotificationButton.CUSTOM_ACTION -> {
it.customAction
}
else -> {
null
}
}
}
}
override fun onCustomAction(player: Player, action: String, intent: Intent) {
handlePlayerAction(action)
}
}
fun invalidate() {
if (invalidateThrottleCount++ == 0) {
scope.launch {
internalNotificationManager?.invalidate()
mediaSessionConnector.invalidateMediaSessionQueue()
mediaSessionConnector.invalidateMediaSessionMetadata()
delay(300)
val wasThrottled = invalidateThrottleCount > 1
invalidateThrottleCount = 0
if (wasThrottled) {
invalidate()
}
}
}
}
/**
* Create a media player notification that automatically updates. Call this
* method again with a different configuration to update the notification.
*/
fun createNotification(config: NotificationConfig) = scope.launch {
if (isNotificationButtonsChanged(config.buttons)) {
// hideNotification()
}
buttons.apply {
clear()
addAll(config.buttons)
}
stopIcon = null
forwardIcon = null
rewindIcon = null
updateMediaSessionPlaybackActions()
pendingIntent = config.pendingIntent
showPlayPauseButton = false
showForwardButton = false
showRewindButton = false
showNextButton = false
showPreviousButton = false
showStopButton = false
if (internalNotificationManager == null) {
internalNotificationManager =
PlayerNotificationManager.Builder(context, NOTIFICATION_ID, CHANNEL_ID)
.apply {
setChannelNameResourceId(R.string.playback_channel_name)
setMediaDescriptionAdapter(descriptionAdapter)
setCustomActionReceiver(customActionReceiver)
setNotificationListener(this@NotificationManager)
for (button in buttons) {
if (button == null) continue
when (button) {
is NotificationButton.PLAY_PAUSE -> {
button.playIcon?.let { setPlayActionIconResourceId(it) }
button.pauseIcon?.let { setPauseActionIconResourceId(it) }
}
is NotificationButton.STOP -> button.icon?.let {
setStopActionIconResourceId(
it
)
}
is NotificationButton.FORWARD -> button.icon?.let {
setFastForwardActionIconResourceId(
it
)
}
is NotificationButton.BACKWARD -> button.icon?.let {
setRewindActionIconResourceId(
it
)
}
is NotificationButton.NEXT -> button.icon?.let {
setNextActionIconResourceId(
it
)
}
is NotificationButton.PREVIOUS -> button.icon?.let {
setPreviousActionIconResourceId(
it
)
}
else -> {}
}
}
}.build().apply {
setMediaSessionToken(mediaSession.sessionToken)
setPlayer(player)
}
}
setupInternalNotificationManager(config)
}
private fun isNotificationButtonsChanged(newButtons: List<NotificationButton>): Boolean {
val currentNotificationButtonsMapByType = buttons.filterNotNull().associateBy { it::class }
return newButtons.any { newButton ->
when (newButton) {
is NotificationButton.PLAY_PAUSE -> {
(currentNotificationButtonsMapByType[NotificationButton.PLAY_PAUSE::class] as? NotificationButton.PLAY_PAUSE).let { currentButton ->
newButton.pauseIcon != currentButton?.pauseIcon || newButton.playIcon != currentButton?.playIcon
}
}
is NotificationButton.STOP -> {
(currentNotificationButtonsMapByType[NotificationButton.STOP::class] as? NotificationButton.STOP).let { currentButton ->
newButton.icon != currentButton?.icon
}
}
is NotificationButton.FORWARD -> {
(currentNotificationButtonsMapByType[NotificationButton.FORWARD::class] as? NotificationButton.FORWARD).let { currentButton ->
newButton.icon != currentButton?.icon
}
}
is NotificationButton.BACKWARD -> {
(currentNotificationButtonsMapByType[NotificationButton.BACKWARD::class] as? NotificationButton.BACKWARD).let { currentButton ->
newButton.icon != currentButton?.icon
}
}
is NotificationButton.NEXT -> {
(currentNotificationButtonsMapByType[NotificationButton.NEXT::class] as? NotificationButton.NEXT).let { currentButton ->
newButton.icon != currentButton?.icon
}
}
is NotificationButton.PREVIOUS -> {
(currentNotificationButtonsMapByType[NotificationButton.PREVIOUS::class] as? NotificationButton.PREVIOUS).let { currentButton ->
newButton.icon != currentButton?.icon
}
}
else -> false
}
}
}
private fun updateMediaSessionPlaybackActions() {
mediaSessionConnector.setEnabledPlaybackActions(
buttons.fold(
PlaybackStateCompat.ACTION_SET_REPEAT_MODE
or PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE
or PlaybackStateCompat.ACTION_SET_PLAYBACK_SPEED
) { acc, button ->
acc or when (button) {
is NotificationButton.PLAY_PAUSE -> {
PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE
}
is NotificationButton.BACKWARD -> {
rewindIcon = button.icon ?: rewindIcon
PlaybackStateCompat.ACTION_REWIND
}
is NotificationButton.FORWARD -> {
forwardIcon = button.icon ?: forwardIcon
PlaybackStateCompat.ACTION_FAST_FORWARD
}
is NotificationButton.SEEK_TO -> {
PlaybackStateCompat.ACTION_SEEK_TO
}
is NotificationButton.STOP -> {
stopIcon = button.icon ?: stopIcon
PlaybackStateCompat.ACTION_STOP
}
is NotificationButton.CUSTOM_ACTION -> {
stopIcon = button.icon ?: stopIcon
customIcons[button.customAction ?: "DEFAULT_CUSTOM"] = button.icon ?: stopIcon
PlaybackStateCompat.ACTION_SET_RATING
}
else -> {
0
}
}
}
)
if (needsCustomActionsToAddMissingButtons) {
val customActionProviders = buttons
.sortedBy {
when (it) {
is NotificationButton.BACKWARD -> 1
is NotificationButton.FORWARD -> 2
is NotificationButton.STOP -> 3
else -> 4
}
}
.mapNotNull {
when (it) {
is NotificationButton.BACKWARD -> {
createMediaSessionAction(rewindIcon ?: DEFAULT_REWIND_ICON, REWIND)
}
is NotificationButton.FORWARD -> {
createMediaSessionAction(forwardIcon ?: DEFAULT_FORWARD_ICON, FORWARD)
}
is NotificationButton.STOP -> {
createMediaSessionAction(stopIcon ?: DEFAULT_STOP_ICON, STOP)
}
is NotificationButton.CUSTOM_ACTION -> {
createMediaSessionAction(customIcons[it.customAction] ?: DEFAULT_CUSTOM_ICON, it.customAction ?: "NO_ACTION_CODE_PROVIDED")
}
else -> {
null
}
}
}
mediaSessionConnector.setCustomActionProviders(*customActionProviders.toTypedArray())
}
}
private fun setupInternalNotificationManager(config: NotificationConfig) {
internalNotificationManager?.run {
setColor(config.accentColor ?: Color.TRANSPARENT)
config.smallIcon?.let { setSmallIcon(it) }
for (button in buttons) {
if (button == null) continue
when (button) {
is NotificationButton.PLAY_PAUSE -> {
showPlayPauseButton = true
}
is NotificationButton.STOP -> {
showStopButton = true
}
is NotificationButton.FORWARD -> {
showForwardButton = true
showForwardButtonCompact = button.isCompact
}
is NotificationButton.BACKWARD -> {
showRewindButton = true
showRewindButtonCompact = button.isCompact
}
is NotificationButton.NEXT -> {
showNextButton = true
showNextButtonCompact = button.isCompact
}
is NotificationButton.PREVIOUS -> {
showPreviousButton = true
showPreviousButtonCompact = button.isCompact
}
else -> {}
}
}
}
}
fun hideNotification() {
internalNotificationManager?.setPlayer(null)
internalNotificationManager = null
invalidate()
}
override fun onNotificationPosted(
notificationId: Int,
notification: Notification,
ongoing: Boolean
) {
scope.launch {
event.updateNotificationState(
NotificationState.POSTED(
notificationId,
notification,
ongoing
)
)
}
}
override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
scope.launch {
event.updateNotificationState(NotificationState.CANCELLED(notificationId))
}
}
internal fun destroy() = scope.launch {
internalNotificationManager?.setPlayer(null)
}
private fun createMediaSessionAction(
@DrawableRes drawableRes: Int,
actionName: String
): MediaSessionConnector.CustomActionProvider {
return object : MediaSessionConnector.CustomActionProvider {
override fun getCustomAction(player: Player): PlaybackStateCompat.CustomAction? {
return PlaybackStateCompat.CustomAction.Builder(actionName, actionName, drawableRes)
.build()
}
override fun onCustomAction(player: Player, action: String, extras: Bundle?) {
handlePlayerAction(action)
}
}
}
companion object {
// Due to the removal of rewind, forward, and stop buttons from the standard notification
// controls in Android 13, custom actions are implemented to support them
// https://developer.android.com/about/versions/13/behavior-changes-13#playback-controls
private val needsCustomActionsToAddMissingButtons = Build.VERSION.SDK_INT >= 33
public const val REWIND = "rewind"
public const val FORWARD = "forward"
public const val STOP = "stop"
private const val NOTIFICATION_ID = 1
private const val CHANNEL_ID = "kotlin_audio_player"
private val DEFAULT_STOP_ICON =
com.google.android.exoplayer2.ui.R.drawable.exo_notification_stop
private val DEFAULT_REWIND_ICON =
com.google.android.exoplayer2.ui.R.drawable.exo_notification_rewind
private val DEFAULT_FORWARD_ICON =
com.google.android.exoplayer2.ui.R.drawable.exo_notification_fastforward
private val DEFAULT_CUSTOM_ICON =
com.google.android.exoplayer2.ui.R.drawable.exo_edit_mode_logo
}
}