我可以在没有 setOngoing(true) 的情况下启动前台服务吗?

Can I start a foreground service without setOngoing(true)?

我有一个在前台启动的服务:

val notification = NotificationCompat.Builder(context)
    .setSmallIcon(R.drawable.ic_stat_notify)
    .setContentTitle(title)
    .setTicker(message)
    .setStyle(NotificationCompat.BigTextStyle().bigText(message))
    .setContentText(message)
    .setContentIntent(pendingIntent)
    .build()
startForeground(Notifications.Id.RUNNING, notification)

注意我不是使用setOngoing(true)

我在 StackOveflow 上找到了一些示例和答案,有些人正在使用 setOngoing(true) 而有些人没有。示例:

此外,the Android documentation says

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the Ongoing heading. This means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

并且,在文档中,未设置 setOngoing(true)

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
        PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification =
          new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
    .setContentTitle(getText(R.string.notification_title))
    .setContentText(getText(R.string.notification_message))
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .setTicker(getText(R.string.ticker_text))
    .build();

startForeground(ONGOING_NOTIFICATION_ID, notification);

问题

省略 setOngoing(true) 有什么影响?

当您启动一个服务并 运行 它在前台使用 startForeground(int, Notification) 时,您传递的通知是标志 FLAG_FOREGROUND_SERVICE (see here)。

然后,在您的通知实际发布到状态栏之前,NotificationManagerService 检查是否设置了 FLAG_FOREGROUND_SERVICE,如果设置了,它将添加标志 FLAG_ONGOING_EVENT (see here) which is the same flag that will be set when you manually use setOngoing(true) (see here)。