Skip to content

Commit

Permalink
fix(app): pause with a delayed stop callback on becoming noisy
Browse files Browse the repository at this point in the history
resolves #426
  • Loading branch information
ashutoshgngwr committed Dec 4, 2020
1 parent b9686a3 commit 15acf89
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class MediaPlayerService : Service() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
Log.i(TAG, "Becoming noisy... Pause playback!")
playerManager.pause()
playerManager.pauseAndWaitBeforeStop()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,11 +245,12 @@ class PlayerManager(private val context: Context) :
notifyChanges()
}

private fun pauseAndWaitBeforeStop() {
fun pauseAndWaitBeforeStop() {
pause()
Log.d(TAG, "scheduling pauseAndWaitBeforeStop callback")
Log.d(TAG, "scheduling stop callback")
handler.removeCallbacksAndMessages(DELAYED_STOP_CALLBACK_TOKEN) // clear previous callbacks
HandlerCompat.postDelayed(
handler, this::stop, DELAYED_STOP_CALLBACK_TOKEN, TimeUnit.MINUTES.toMillis(1)
handler, this::stop, DELAYED_STOP_CALLBACK_TOKEN, TimeUnit.MINUTES.toMillis(5)
)
}

Expand Down Expand Up @@ -345,7 +346,6 @@ class PlayerManager(private val context: Context) :
PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN,
0f
)

}

mediaSession.setPlaybackState(playbackStateBuilder.build())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper

@RunWith(RobolectricTestRunner::class)
@Config(shadows = [ShadowMediaSession::class, ShadowMediaSessionCompat::class])
Expand Down Expand Up @@ -171,6 +172,21 @@ class PlayerManagerTest {
verify(exactly = 1) { players.getValue("test").pause() }
}

@Test
fun testPauseAndWaitBeforeStop() {
playerManager.pauseAndWaitBeforeStop()

assertEquals(PlayerManager.State.PAUSED, playerManager.state)
assertEquals(PlaybackStateCompat.STATE_PAUSED, ShadowMediaSessionCompat.getLastPlaybackState())
assertEquals(1, playerManager.players.size)
verify(exactly = 1) { players.getValue("test").pause() }

ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
assertEquals(PlayerManager.State.STOPPED, playerManager.state)
assertEquals(PlaybackStateCompat.STATE_STOPPED, ShadowMediaSessionCompat.getLastPlaybackState())
assertEquals(0, playerManager.players.size)
}

@Test
fun testResumePlayback_whenAudioFocusRequestFails() {
mockkStatic(AudioManagerCompat::class)
Expand Down

0 comments on commit 15acf89

Please sign in to comment.