2

我有一个音乐播放器应用程序,最近我从常规服务切换到 MediaBrowserServiceCompat。该服务由框架自动创建(在应用程序启动时调用 onCreate 方法),我仅在播放操作时将其作为前台启动。

ANR 出现在少数设备上,尤其是三星,但也出现在索尼、诺基亚、AllView 等设备上。

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()
      }
   }

}

我总是在 ContextCompat.startForegroundService 之后调用 startForeground ...

有没有办法调试/重现/修复这个问题?

4

0 回答 0