我已尝试尽可能缩小代码范围以识别问题(尽管可能遗漏了一些部分),但基本上我遇到了 Android 11 或更高版本出现的问题,其中 MediaBrowserServiceCompat 不会被破坏使用相同的代码会在其他版本中破坏它。我已将其范围缩小为通知并设置 MediaSession 令牌。如果我设置它,它不会在调用时破坏,stopSelf()
如果我不设置它,它会清除。我还注意到它将绑定到服务(如果设置了 MediaSession 令牌),但我看不出有办法强制它解除绑定。下面提供的示例代码
class MediaPlayerService : MediaBrowserServiceCompat() {
private val mediaSession by lazy { MediaSessionCompat(this, "MusicService") }
private val mediaPlayerNotification by lazy { MediaPlayerNotification(this) }
override fun onCreate() {
super.onCreate()
sessionToken = mediaSession.sessionToken
}
//Not called on Android 11
override fun onDestroy() {
super.onDestroy()
}
playerStarted(){
mediaPlayerNotification.createNotification()
}
fun playerStopped() {
stopSelf()
}
}
const val mId = 101
class MediaPlayerNotification(service: MediaPlayerService) : BroadcastReceiver() {
private val notificationManager: NotificationManager = service.getSystemService(context.NOTIFICATION_SERVICE) as NotificationManager
private val notificationBuilder by lazy {
val filter = IntentFilter()
filter.addAction(NOTIFICATION_ACTION_SKIP)
service.registerReceiver(this, filter)
NotificationCompat.Builder(service, MEDIA_PLAYER_CHANNEL)
.setStyle(androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0)
.setMediaSession(service.sessionToken))// If I comment this line, the service will destory when `stopSelf()` is called
.setSmallIcon(R.drawable.img_logo_white)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) // Show controls on lock screen even when user hides sensitive content.
.addAction(skipAction)
}
private var notification = notificationBuilder.build()
fun createNotification() {
notification = notificationBuilder
.setContentTitle("title")
.setContentText("text")
.build()
notificationManager.notify(mId, notification)
}
}
我如何才能澄清 mediaSession 已结束的通知,以便它与服务解除绑定(我相信这是我需要走的路)。我似乎也找不到任何关于发生了什么变化以及为什么在 Android 10 上发生故障的 Android 文档