React to changes in the player notification

This commit is contained in:
Bnyro 2023-01-13 18:44:41 +01:00
parent 186925dfa1
commit b09b9ad3bf
2 changed files with 23 additions and 0 deletions

View File

@ -93,6 +93,11 @@ class BackgroundMode : Service() {
*/ */
private val binder = LocalBinder() private val binder = LocalBinder()
/**
* Listener for passing playback state changes to the AudioPlayerFragment
*/
var onIsPlayingChanged: ((isPlaying: Boolean) -> Unit)? = null
/** /**
* Setting the required [Notification] for running as a foreground service * Setting the required [Notification] for running as a foreground service
*/ */
@ -257,6 +262,11 @@ class BackgroundMode : Service() {
* Plays the next video when the current one ended * Plays the next video when the current one ended
*/ */
player?.addListener(object : Player.Listener { player?.addListener(object : Player.Listener {
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
onIsPlayingChanged?.invoke(isPlaying)
}
override fun onPlaybackStateChanged(state: Int) { override fun onPlaybackStateChanged(state: Int) {
when (state) { when (state) {
Player.STATE_ENDED -> { Player.STATE_ENDED -> {
@ -398,6 +408,8 @@ class BackgroundMode : Service() {
fun getCurrentPosition() = player?.currentPosition fun getCurrentPosition() = player?.currentPosition
fun getDuration() = player?.duration
fun seekToPosition(position: Long) = player?.seekTo(position) fun seekToPosition(position: Long) = player?.seekTo(position)
fun pause() { fun pause() {

View File

@ -35,6 +35,7 @@ class AudioPlayerFragment : BaseFragment() {
// We've bound to LocalService, cast the IBinder and get LocalService instance // We've bound to LocalService, cast the IBinder and get LocalService instance
val binder = service as BackgroundMode.LocalBinder val binder = service as BackgroundMode.LocalBinder
playerService = binder.getService() playerService = binder.getService()
handleServiceConnection()
mBound = true mBound = true
} }
@ -97,9 +98,19 @@ class AudioPlayerFragment : BaseFragment() {
ImageHelper.loadImage(current.thumbnail, binding.thumbnail) ImageHelper.loadImage(current.thumbnail, binding.thumbnail)
} }
private fun handleServiceConnection() {
playerService.onIsPlayingChanged = { isPlaying ->
binding.playPause.setIconResource(
if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
)
isPaused = !isPlaying
}
}
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
playerService.onIsPlayingChanged = null
activity?.unbindService(connection) activity?.unbindService(connection)
// unregister the listener // unregister the listener
PlayingQueue.removeOnTrackChangedListener(onTrackChangeListener) PlayingQueue.removeOnTrackChangedListener(onTrackChangeListener)