可以使用系统通知来启动服务,而无需广播或活动调用其startService()。
实现代码如下:
在服务中添加以下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT)
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
val notification = Notification.Builder(this, "channel_id")
.setOngoing(true)
.build()
startForeground(1, notification)
} else {
startService(Intent(this, YourService::class.java))
}
此代码会检查Android版本是否大于等于O(API级别26)。如果是,我们需要创建一个通知渠道并使用startForeground()方法将服务启动为前台服务。如果未达到O或更高版本,则使用startService()方法。