Manejar la intención en el inicio Comando de servicio mediante.
stopForeground(true)
Esta llamada eliminará el servicio del estado de primer plano , lo que permitirá que se elimine si se necesita más memoria. Esto no detiene la ejecución del servicio . Para eso, debe llamar a stopSelf () o métodos relacionados.
El valor de paso verdadero o falso se indica si desea eliminar la notificación o no.
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 {
//Start your task
//Send forground notification that a service will run in background.
sendServiceNotification(this)
}
return Service.START_NOT_STICKY
}
Manejar su tarea cuando se destruye se llama por stopSelf () .
override fun onDestroy() {
super.onDestroy()
//Stop whatever you started
}
Cree una notificación para mantener el servicio ejecutándose en primer plano.
//This is from Util class so as not to cloud your service
fun sendServiceNotification(myService: Service) {
val notificationTitle = "Service running"
val notificationContent = "<My app> is using <service name> "
val actionButtonText = "Stop"
//Check android version and create channel for Android O and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//You can do this on your own
//createNotificationChannel(CHANNEL_ID_SERVICE)
}
//Build notification
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)
//Add stop button on notification
val pStopSelf = createStopButtonIntent(myService)
notificationBuilder.addAction(R.drawable.ic_location, actionButtonText, pStopSelf)
//Build notification
val notificationManagerCompact = NotificationManagerCompat.from(applicationContext)
notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notificationBuilder.build())
val notification = notificationBuilder.build()
//Start notification in foreground to let user know which service is running.
myService.startForeground(NOTIFICATION_ID_SERVICE, notification)
//Send notification
notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notification)
}
Dé un botón de detención en la notificación para detener el servicio cuando el usuario lo necesite.
/**
* Function to create stop button intent to stop the service.
*/
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)
}