在代码中添加必要的配置并将通知频道和通知媒体处理合并
Android 12的一个新问题是媒体通知会在通知中心中消失,这可能影响用户对正在播放的媒体的可见性和控制。为了解决这个问题,需要在代码中添加以下配置:
这将允许您的应用程序更好地跟踪媒体通知并对其进行处理。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, necessary for ALL notifications on Android 8.0 and above.
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_LOW
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = descriptionText
val notificationCompatBuilder = NotificationCompat.Builder(requireContext(), CHANNEL_ID).apply {
setSmallIcon(R.drawable.ic_notification)
setContentTitle(getString(R.string.notification_title))
setContentText(getString(R.string.notification_text_playing, mediaTitle))
setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
setPriority(NotificationCompat.PRIORITY_HIGH)
setAutoCancel(true)
setStyle(androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.sessionToken)
.setShowCancelButton(true)
.setShowActionsInCompactView(0, 1, 2)
.setCancelButtonIntent(stopPendingIntent)
.setMediaSession(mediaSession.sessionToken)
)
addAction(
NotificationCompat.Action(
R.drawable.ic_notification_previous,