即使在底层服务停止后仍保留前台服务的通知

Keep the notification of a foreground service even after the underlying service is stopped

我查阅了很多文档来了解如何在服务停止后保持前台服务的通知。

我已按照此处接受的答案建议的步骤进行操作:

我的代码如下:

 public void onDestroy() {
  
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        stopForeground(Service.STOP_FOREGROUND_DETACH);
    } else {
        stopForeground(false);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = gpsServiceNotificationSingleton.getNotificationBuilder().build();
        mNotificationManager.notify(MYMConstants.FOREGROUND_ID_FOR_NOTIFICATION, notification);
    }
}

这里的问题是,即使在将 STOP_FOREGROUND_DETACH 标志传递给 stopForeground 之后,我也无法保留通知,因为通知已被清除。我在这里遗漏了什么吗?

经过多次尝试和错误,我发现将stopForeground(Service.STOP_FOREGROUND_DETACH)添加到onDestroy()的范围内将清除生成的通知no不管怎样

为了在相应的前台服务被杀死后仍保持通知,必须在 onDestroy() 之外调用 stopForeground(Service.STOP_FOREGROUND_DETACH) 。这方面的一个例子是:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    if(intent.getAction().equals("STOP_SERVICE_ACTION")) {
        // your code
    } else if(intent.getAction().equals("START_SERVICE_ACTION")) {
       // your code 
    }
    return START_STICKY;
}