Sunday, 11 October 2020

MediaBrowserServiceCompat: Context.startForegroundService() did not then call Service.startForeground()

I have a music player app and recently I switched to MediaBrowserServiceCompat from a regular service. The service is created automatically by the framework (onCreate method is called at app startup), and I start it as foreground only on play action.

The ANR is encountered on a few devices, especially Samsung, but also seen on Sony, Nokia, AllView etc.

class MusicService: MediaBrowserServiceCompat() {

  override fun onCreate() {
    super.onCreate()
    .....
 }

 override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)
    stopSelf()
 }

  fun moveServiceToStartedState(){
     if (!mServiceInStartedState) {
          ContextCompat.startForegroundService(
                  this@MusicService,
                  Intent(this@MusicService, MusicService::class.java))
          mServiceInStartedState = true
      }

      startForeground(PlayerNotificationManager.NOTIFICATION_ID, notification)
  }

  fun  moveServiceOutOfStartedState() {
     if(mServiceInStartedState) {
       stopForeground(true)
       stopSelf()
       mServiceInStartedState = false
     }
  }

  fun updateNotificationForPause(state: PlaybackStateCompat) {
      stopForeground(false)
      ................
  }

private inner class MediaPlayerListener: PlaybackInfoListener() {

   private val mServiceManager: ServiceManager = ServiceManager()

   override fun onPlaybackStateChange(state: PlaybackStateCompat) {

      // Manage the started state of this service.
      when (state.state) {
         PlaybackStateCompat.STATE_PLAYING -> mServiceManager.moveServiceToStartedState(state)
         PlaybackStateCompat.STATE_PAUSED -> mServiceManager.updateNotificationForPause(state)
         PlaybackStateCompat.STATE_ERROR -> {
            mServiceManager.updateNotificationForPause(state)
            Toast.makeText(this@MusicService, R.string.error, Toast.LENGTH_SHORT).show()
         }
         PlaybackStateCompat.STATE_STOPPED -> mServiceManager.moveServiceOutOfStartedState()
      }
   }

}

I ALWAYS call startForeground after ContextCompat.startForegroundService...

Is there any way to debug/reproduce/fix this issue?



from MediaBrowserServiceCompat: Context.startForegroundService() did not then call Service.startForeground()

No comments:

Post a Comment