【发布时间】:2023-03-15 19:06:01
【问题描述】:
我有一个音乐播放器,它在播放音频时显示媒体通知。我希望用户能够在音乐暂停时关闭通知。
我必须使用 startForeground 以便服务继续运行并且它会保持连接到活动。我尝试过使用通知通道,一旦我终止了活动,播放也会停止,这不是我想要的(代码仍在其中,已注释掉)。
当显示通知时,我调用 startForeground。 setOngoing 设置为playbackState == STATE_PLAYING。当服务被销毁或当playbackState == null || 时我调用stopForeground停止。
Pastebin:https://pastebin.com/FNTSSzjS
代码sn-p(因为你需要用pastebin包含代码)
private void addPlayPauseAction(NotificationCompat.Builder builder) {
String label;
int icon;
PendingIntent intent;
if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
label = service.getString(R.string.play_pause);
icon = android.R.drawable.ic_media_pause;
intent = intentPause;
builder.setOngoing(true);
} else {
label = service.getString(R.string.play_pause);
icon = android.R.drawable.ic_media_play;
intent = intentPlay;
builder.setOngoing(false);
}
builder.addAction(new NotificationCompat.Action(icon, label, intent));
}
PasteBin 中的相关方法有startNotification、stopNotification、createNotification、addPlayPauseAction、setNotificationPlaybackState
【问题讨论】:
标签: android service notifications audio-player android-music-player