问题描述: 在 Android 的 MediaPlayer 中,当使用 API 33 中的 notification 支持时,有时会出现无法正确工作的情况,导致无法正常显示通知信息。
以下是使用 MediaPlayer 的示例代码,可以正常使用通知功能:
Notification notification = new Notification.Builder(this, "channel_id")
.setContentTitle("正在播放音乐")
.setContentText("MediaPlayer 正在播放...")
.setSmallIcon(R.drawable.ic_music_note)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(new Notification.Action(
R.drawable.ic_pause,
getString(R.string.pause),
PendingIntent.getService(this, 0, new Intent(this, MusicService.class)
.setAction(ACTION_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT)))
.addAction(new Notification.Action(
R.drawable.ic_stop,
getString(R.string.stop),
PendingIntent.getService(this, 0, new Intent(this, MusicService.class)
.setAction(ACTION_STOP), PendingIntent.FLAG_UPDATE_CURRENT)))
.build();
注意:上述代码中使用的 Notification.Builder 类并不是 API 33 中的类,如果需要兼容 API 33,可以使用以下代码:
Notification notification = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle("正在播放音乐")
.setContentText("MediaPlayer 正在播放...")
.setSmallIcon(R.drawable.ic_music_note)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(new NotificationCompat.Action(
R.drawable.ic_pause,
getString(R.string.pause),
PendingIntent.getService(this, 0, new Intent(this, MusicService.class)
.setAction(ACTION_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT)))
.addAction(new NotificationCompat.Action(
R.drawable.ic_stop,
getString(R.string.stop),
PendingIntent.getService(this, 0, new Intent(this, MusicService.class)
.setAction(ACTION_STOP), PendingIntent.FLAG_UPDATE_CURRENT)))
.build();