一旦服务不再处于前台,就可以取消来自前台服务的通知

Mic*_*elG 4 service notifications android foreground-service

我有一个音乐控制通知,允许用户开始/停止音乐。我想要与 Google Play 音乐应用程序通知完全相同的行为:播放音乐时,服务处于前台且通知不可取消,当音乐未播放时,服务不再处于前台且通知可以移除。它工作正常,但是当我取消我的服务的前台时,通知在重新出现之前很快被删除。

这是我的代码,首先是我如何构建通知:

NotificationCompat.Builder notifBuilder =
            new android.support.v7.app.NotificationCompat.Builder(getApplicationContext())
                    .setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
                            .setShowActionsInCompactView(1, 2, 3)
                            .setShowCancelButton(true)
                            .setCancelButtonIntent(deletePendingIntent)))
                    .setSmallIcon(R.drawable.notif_logo)
                    .setColor(ResourcesCompat.getColor(getResources(), R.color.blue, getTheme()))
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setShowWhen(false);

    notifBuilder.setContentIntent(pendingIntent);
    notifBuilder.setDeleteIntent(deletePendingIntent);
Run Code Online (Sandbox Code Playgroud)

这是我开始和更新通知的方式:

private void showNotification(NotificationCompat.Builder notifBuilder, boolean foreground) {
    if (foreground) {
        startForeground(NOTIFICATION_ID, notifBuilder.build());
    } else {
        stopForeground(false);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notifBuilder.build());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用 stopForeground(false),通知在运行后仍然不可取消。如果我使用 stopForeground(true),通知会被快速删除然后再次添加,这会产生奇怪的闪烁。

如何在服务退出前台后可以取消通知,而不必删除然后再次添加通知?

ian*_*ake 6

根据在前台服务文档中使用 MediaStyle 通知

在 Android 5.0(API 级别 21)及更高版本中,一旦服务不再在前台运行,您可以滑动通知以停止播放器。您不能在早期版本中执行此操作。在 Android 5.0(API 级别 21)之前,为了允许用户移除通知并停止播放,您可以通过调用setShowCancelButton(true)setCancelButtonIntent()在通知的右上角添加一个取消按钮。

你永远不需要调用setOngoing(false)/setOngoing(true)因为它是由你的服务当前是否在前台控制的。

根据媒体会话回调文档,您应该stopForeground(false)在音乐暂停时被调用- 这会删除前台优先级并允许用户在 API 21+ 设备上滑动通知。

  • @user888867 - 他们可能正在使用 [ServiceCompat.stopForeground](https://developer.android.com/reference/androidx/core/app/ServiceCompat.html#stopForeground(android.app.Service,%20int)) 和 [ STOP_FOREGROUND_DETACH](https://developer.android.com/reference/androidx/core/app/ServiceCompat.html#STOP_FOREGROUND_DETACH) 即使服务被销毁,通知也可以保留。 (2认同)