Skip to content

Commit

Permalink
Fix GitHub issue #250
Browse files Browse the repository at this point in the history
MusicService wasn't getting started, leading to a situation where the
service would be killed and the ExoPlayer playback thread would continue
to play queued songs until it was also killed or it completed the queue.

This change ensures the service is started when playback begins so that
the client may unbind without service being killed immediately.

Change-Id: Ib4a846c2e60d3f0644b0b5843d1815dbd3caef68
  • Loading branch information
nic0lette committed Sep 20, 2018
1 parent 5222b05 commit d56268a
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions media/src/main/java/com/example/android/uamp/media/MusicService.kt
Expand Up @@ -164,9 +164,22 @@ class MusicService : MediaBrowserServiceCompat() {
packageValidator = PackageValidator(this, R.xml.allowed_media_browser_callers)
}

/**
* This is the code that causes UAMP to stop playing when swiping it away from recents.
* The choice to do this is app specific. Some apps stop playback, while others allow playback
* to continue and allow uses to stop it with the notification.
*/
override fun onTaskRemoved(rootIntent: Intent) {
super.onTaskRemoved(rootIntent)
stopSelf()

/**
* By stopping playback, the player will transition to [Player.STATE_IDLE]. This will
* cause a state change in the MediaSession, and (most importantly) call
* [MediaControllerCallback.onPlaybackStateChanged]. Because the playback state will
* be reported as [PlaybackStateCompat.STATE_NONE], the service will first remove
* itself as a foreground service, and will then call [stopSelf].
*/
exoPlayer.stop(true)
}

override fun onDestroy() {
Expand Down Expand Up @@ -288,21 +301,36 @@ class MusicService : MediaBrowserServiceCompat() {
PlaybackStateCompat.STATE_PLAYING -> {
becomingNoisyReceiver.register()

startForeground(NOW_PLAYING_NOTIFICATION, notification)
isForegroundService = true
/**
* This may look strange, but the documentation for [Service.startForeground]
* notes that "calling this method does *not* put the service in the started
* state itself, even though the name sounds like it."
*/
if (!isForegroundService) {
startService(Intent(applicationContext, this@MusicService.javaClass))
startForeground(NOW_PLAYING_NOTIFICATION, notification)
isForegroundService = true
} else if (notification != null) {
notificationManager.notify(NOW_PLAYING_NOTIFICATION, notification)
}
}
else -> {
becomingNoisyReceiver.unregister()

if (isForegroundService) {
stopForeground(false)
isForegroundService = false

// If playback has ended, also stop the service.
if (updatedState == PlaybackStateCompat.STATE_NONE) {
stopSelf()
}

if (notification != null) {
notificationManager.notify(NOW_PLAYING_NOTIFICATION, notification)
} else {
removeNowPlayingNotification()
}
isForegroundService = false
}
}
}
Expand Down

0 comments on commit d56268a

Please sign in to comment.