Для создания сервиса, который не будет убит системой необходимо, чтобы этот сервис постоянно поддерживал уведомление.
Пример такого сервиса:
class MyForegraundService : Service(){
companion object {
const val channelId = "--your channel id--"
const val notifyId = 395 // some number
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("Your service started")
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
sendStartNotification()
doWhatYouNeed()// your code
}
}
Где sendStartNotification:
private fun sendStartNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel()
val notification = buildNotification()
this.startForeground(notifyId, notification)
}
private fun buildNotification(): Notification {
val builder = notificationBuilder
builder.setSmallIcon(R.drawable.ic_menu_6)
.setContentTitle(this.resources.getString(R.string.app_name))
.setContentText(this.resources.getString("describe process"))
.setShowWhen(true)
.setOngoing(true)
.setProgress(100, 0, true)
.priority = NotificationCompat.PRIORITY_MAX
return builder.build()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val name = getString("notification_channel_name")// for user
val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH)
channel.description = getString("notification_channel_description") //for user
manager.createNotificationChannel(channel)
}
Пример где можно почитать: https://www.dev2qa.com/android-foreground-service-example/
Гуглится по запросу ForegroundService.
Если простыми словами, то такой сервис будет жить до тех пор, пока висит уведомление, а уведомление создается несмахиваемым. Очевидно, перезагрузка устройства сервис убьет. Так же бывает, что система убивает даже такой сервис, но это случается нечасто (на практике пока ни разу встретилось), а пользователь имеет возможность увидеть, что сервис убит. При остановке сервиса нужно убрать/заменить уведомление.