首页 > 解决方案 > 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

标签: androidservicenotificationsaudio-playerandroid-music-player

解决方案


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.


推荐阅读