android - setOngoing(false) 后无法清除通知
问题描述
我有一个音乐播放器,它在播放音频时显示媒体通知。我希望用户能够在音乐暂停时关闭通知。
我必须使用 startForeground 以便该服务将继续运行并且它将保持连接到活动。我尝试使用通知通道,一旦我终止活动播放停止,这不是我想要的(代码仍在其中,已注释掉)。
当显示通知时,我调用 startForeground。setOngoing 设置为playbackState == STATE_PLAYING。当服务被销毁或当playbackState == null || 时我调用stopForeground 停止。
粘贴箱:https ://pastebin.com/FNTSSzjS
代码片段(因为您需要在 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
解决方案
Use stopForeground(false)
and rebuild notification. You don't have to use setOngoing
while using foreground service. For more information refer to this page
and search for Running a service in the foreground
.
推荐阅读
- amazon-web-services - AWS Data Pipeline 中 EC2 资源的 AWS IAM 设置
- git - 推入空的 git repo 时“无法推送引用”
- css - Razor 类库中的 Blazor 组件(CSS 隔离)
- c++ - 在表1 Sqlit下附上table2
- mongodb - 查找部署了我的 MongoDB 的服务器的 IP 地址
- flutter - 来回动画不能在颤动中工作
- asp.net - Bootstrap手风琴组需要在回发后保持折叠状态
- windows - 目录基础交换 (Cr3) 和 Windows 内核
- sql - 创建一个函数在 SQL 中生成随机密码
- express - 使用快速车把时如何修复“必需”属性?