我有一个在前台启动的服务:
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:
前台服务是用户主动了解的服务,并且当内存不足时不是系统杀死的候选服务。前台服务必须为状态栏提供通知,该通知位于“正在进行”标题下。这意味着除非停止服务或从前台删除服务,否则无法解除通知。
并且,在文档中,没有设置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(参见here)。
然后,在您的通知实际发布到状态栏之前,NotificationManagerService
检查是否设置了FLAG_FOREGROUND_SERVICE
,如果是这样,它将添加标志FLAG_ONGOING_EVENT(请参阅here),这是当您手动使用setOngoing(true)
时将设置的相同标志(请参阅here) 。