我开始扩展 MediaBrowserServiceCompat 类的前台服务。 当服务在前台运行但服务仅显示播放/暂停按钮时,我创建了一个通知。它不显示上一个或下一个按钮。 我调用或不调用 setAction 函数通知仍然只在通知上显示播放/暂停按钮。
private fun getNotification(isPlaying: Boolean = false): Notification? {
val controller = mediaSession.controller
Log.d(LOG_TAG, "currentMediaItemIndex ${player.currentMediaItemIndex}")
val audioData = listData?.get(player.currentMediaItemIndex) ?: return null
val icon = getBitmapFromPath(audioData.path) ?: BitmapFactory.decodeResource(
mContext.resources,
R.drawable.music
)
val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
setContentTitle(audioData.name)
setContentText(audioData.author)
setSubText(audioData.artist)
setLargeIcon(icon)
setSilent(true)
setContentIntent(controller?.sessionActivity)
setDeleteIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(
this@MediaPlaybackService,
PlaybackStateCompat.ACTION_STOP
)
)
setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
setSmallIcon(R.drawable.music)
color = ContextCompat.getColor(
this@MediaPlaybackService,
androidx.appcompat.R.color.material_blue_grey_800
)
setStyle(
androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(sessionToken)
.setShowActionsInCompactView(0, 1, 2)
.setShowCancelButton(true)
.setCancelButtonIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(
this@MediaPlaybackService,
PlaybackStateCompat.ACTION_STOP
)
)
)
//setAction(this@apply, isPlaying)
}
return builder.build()
}
private fun setAction(builder: NotificationCompat.Builder, isPlaying: Boolean) {
builder.apply {
val iconPlayPause = if (isPlaying)
com.google.android.exoplayer2.ui.R.drawable.exo_notification_pause else
com.google.android.exoplayer2.ui.R.drawable.exo_notification_play
val actionPlayPause = NotificationCompat.Action(
iconPlayPause, "Pause", MediaButtonReceiver.buildMediaButtonPendingIntent(
this@MediaPlaybackService,
PlaybackStateCompat.ACTION_PLAY_PAUSE
)
)
val actionPrevious = NotificationCompat.Action(
com.google.android.exoplayer2.ui.R.drawable.exo_icon_previous,
"Previous",
MediaButtonReceiver.buildMediaButtonPendingIntent(
this@MediaPlaybackService,
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
)
)
val actionNext = NotificationCompat.Action(
com.google.android.exoplayer2.ui.R.drawable.exo_icon_next,
"Previous",
MediaButtonReceiver.buildMediaButtonPendingIntent(
this@MediaPlaybackService,
PlaybackStateCompat.ACTION_SKIP_TO_NEXT
)
)
addAction(actionPrevious)
addAction(actionPlayPause)
addAction(actionNext)
}
}