API 24 级的前台服务 - Android 7.0 Nougat
Foreground service in API Level 24 - Android 7.0 Nougat
我的问题特定于 API 级别 24 - Android 7.0 牛轧糖。
我正在尝试找到最合适且面向未来的方式来启动粘性前台服务。
总结:
- 按下按钮后需要从 activity 开始服务
- 将创建一个(粘性 - 这将由通知标志处理)通知
在API 26级,我们可以调用startForegroundService(service, notification)
,服务会自动关联到通知。
然而在API级别24中,服务是用[=13=]启动的,通知是通过调用NotificationManagerCompat的notify
方法来显示的。
怎么才能让OS知道这个通知是和服务相关的,所以这个服务就认为是前台服务,OS永远不会自己杀掉。
注意:我想要这个实现的原因是要面向未来。此服务需要位置更新,并且从 API 级别 26 开始,只有前台服务(带有粘性通知)能够接收实时更新 (https://developer.android.com/about/versions/oreo/background-location-limits)。
How can we let the OS know that the notification is related to the service, so the service is considered a foreground service
在服务中调用 startForeground()
,提供 Notification
。您也需要在 Android 8.0+ 上执行此操作。
that the OS will never kill by itself
从来没有这样。它只是降低了 Android 终止您的进程的可能性。
我的问题特定于 API 级别 24 - Android 7.0 牛轧糖。 我正在尝试找到最合适且面向未来的方式来启动粘性前台服务。 总结: - 按下按钮后需要从 activity 开始服务 - 将创建一个(粘性 - 这将由通知标志处理)通知
在API 26级,我们可以调用startForegroundService(service, notification)
,服务会自动关联到通知。
然而在API级别24中,服务是用[=13=]启动的,通知是通过调用NotificationManagerCompat的notify
方法来显示的。
怎么才能让OS知道这个通知是和服务相关的,所以这个服务就认为是前台服务,OS永远不会自己杀掉。
注意:我想要这个实现的原因是要面向未来。此服务需要位置更新,并且从 API 级别 26 开始,只有前台服务(带有粘性通知)能够接收实时更新 (https://developer.android.com/about/versions/oreo/background-location-limits)。
How can we let the OS know that the notification is related to the service, so the service is considered a foreground service
在服务中调用 startForeground()
,提供 Notification
。您也需要在 Android 8.0+ 上执行此操作。
that the OS will never kill by itself
从来没有这样。它只是降低了 Android 终止您的进程的可能性。