【问题标题】:Notification cannot be cleared after setOngoing(false)setOngoing(false) 后无法清除通知
【发布时间】: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


    【解决方案1】:

    使用stopForeground(false) 并重建通知。使用前台服务时不必使用setOngoing。更多信息请参考page

    然后搜索Running a service in the foreground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 2019-03-05
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多