bre*_*ite 6 android kotlin exoplayer
我在 Android 12 上遇到了一些奇怪的行为。特别是对于MediaBrowserService. 该应用程序将在后台长时间播放声音。我在 Android 12 上遇到了两种不同但不受欢迎的行为。
在 Pixel 5a 上 - 通知会出现,但会在一小时左右后在后台消失。音乐仍然可以正常播放,如果打开应用程序可以暂停。
在 Samsung s21 上 - 播放声音时会出现通知。但如果它被停止,并且另一个启动,通知将不会在启动服务时再次出现,直到手机本身重新启动。
在运行 Android 10 的 s9 和运行 Android 11 的 OnePlus 8 上,没有任何问题。
创建通知似乎非常简单:
companion object {
const val ACTION_STOP = "action_stop"
const val CHANNEL_ID = "app_notification_channel"
const val NOTIFICATION_CHANNEL_TAG = "Playing Controls"
const val ONGOING_NOTIFICATION_ID = 2222
}
private fun refreshNotification(stopCalled: Boolean = false) {
val sounds = playingSounds
if (sounds.isEmpty() || stopCalled) {
// if we lost audio focus we will expect to restart momentarily. Don't stop the service
if (!audioFocusTakenBackground) {
Timber.e("Stopping Foreground")
stopForeground(true)
}
return
}
val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
color = this@SoundPlayerService.getColor(R.color.magenta_0FF)
val nowPlaying = getString(R.string.action_now_playing)
setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
setContentTitle(nowPlaying)
setContentText(name)
setSmallIcon(R.drawable.ic_icon_small)
setContentIntent(relaunchPendingIntent())
setSilent(true)
setCategory(NotificationCompat.CATEGORY_SERVICE)
priority = NotificationCompat.PRIORITY_HIGH
addAction(NotificationCompat.Action(R.drawable.ic_playbar_stop, getString(R.string.action_stop), stopIntent))
setStyle(
androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0)
.setMediaSession(mediaSession.sessionToken)
.setShowCancelButton(true)
.setCancelButtonIntent(stopIntent)
)
}
// If we lost audio focus in the background, we don't stop the service.
// Ensure that its not called in the background aka failure android 12
if (!audioFocusTakenBackground && Application.instance.isAppInForeground) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(
ONGOING_NOTIFICATION_ID,
builder.build(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
)
} else {
startForeground(
ONGOING_NOTIFICATION_ID,
builder.build()
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
媒体会话是先前创建的:
// Create a MediaSession
mediaSession = MediaSessionCompat(this, this.javaClass.name).apply {
setSessionActivity(sessionActivityPendingActivity)
isActive = true
}
sessionToken = mediaSession.sessionToken
Run Code Online (Sandbox Code Playgroud)
然后,媒体会话通过以下方式连接到 ExoPlayer 实例:MediaSessionConnector
if (mediaSession != null) {
MediaSessionConnector(mediaSession).also { mediaSessionConnector ->
mediaSessionConnector.setPlayer(mCurrentPlayer)
}
}
Run Code Online (Sandbox Code Playgroud)
再说一次,直到 12 点这才成为问题。
如果有人看到过这个或者可以指出我尝试和调试的方法,我将非常感激。
谢谢!
| 归档时间: |
|
| 查看次数: |
801 次 |
| 最近记录: |