使用startCommand处理服务的意图。
stopForeground(true)
这个调用将会使服务退出前台状态,如果需要更多的内存,服务可以被杀掉。这并不会停止服务的运行。如果想要停止服务,需要调用stopSelf()或相关方法。
传递值true或false表示是否要删除通知。
val ACTION_STOP_SERVICE = "stop_service"
val NOTIFICATION_ID_SERVICE = 1
...
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
if (ACTION_STOP_SERVICE == intent.action) {
stopForeground(true)
stopSelf()
} else {
sendServiceNotification(this)
}
return Service.START_NOT_STICKY
}
当通过 stopSelf() 调用时,处理您的任务。
override fun onDestroy() {
super.onDestroy()
}
创建一个通知,以使服务在前台运行。
fun sendServiceNotification(myService: Service) {
val notificationTitle = "Service running"
val notificationContent = "<My app> is using <service name> "
val actionButtonText = "Stop"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
}
val notificationBuilder = NotificationCompat.Builder(applicationContext, CHANNEL_ID_SERVICE)
notificationBuilder.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_location)
.setContentTitle(notificationTitle)
.setContentText(notificationContent)
.setVibrate(null)
val pStopSelf = createStopButtonIntent(myService)
notificationBuilder.addAction(R.drawable.ic_location, actionButtonText, pStopSelf)
val notificationManagerCompact = NotificationManagerCompat.from(applicationContext)
notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notificationBuilder.build())
val notification = notificationBuilder.build()
myService.startForeground(NOTIFICATION_ID_SERVICE, notification)
notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notification)
}
在通知中添加一个停止按钮,以便用户需要时停止服务。
private fun createStopButtonIntent(myService: Service): PendingIntent? {
val stopSelf = Intent(applicationContext, MyService::class.java)
stopSelf.action = ACTION_STOP_SERVICE
return PendingIntent.getService(myService, 0,
stopSelf, PendingIntent.FLAG_CANCEL_CURRENT)
}