서비스의 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 {
//Start your task
//Send forground notification that a service will run in background.
sendServiceNotification(this)
}
return Service.START_NOT_STICKY
}
파괴시 stopSelf ()에 의해 호출되면 작업을 처리하십시오 .
override fun onDestroy() {
super.onDestroy()
//Stop whatever you started
}
서비스가 포 그라운드에서 계속 실행되도록 알림을 작성하십시오.
//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)
}
사용자가 필요할 때 서비스를 중지하려면 알림에 중지 버튼을 제공합니다.
/**
* 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)
}