Как сделать не убиваемый intentService для показа view компонента поверх всех окон?

Кратко суть задачи: есть app и intentService. Сервис показывает view поверх всех окон и должен убиваться только при нажатии кнопки в app.

Подскажите пожалуйста, как сделать intentService не убиваемым? Android 8+. Убивается даже с startForeground. Если зайти в список недавних приложений и нажать кнопку "очистить всё", убивается напрочь (очищается оперативка). Я попробовал задействовать alarmManager, но криво он работает (или руки кривые), задаешь ему секунду для повторного вызова сервиса, а по итогу работает рандомно, может через 10 сек вызвать, может через 3 минуты.

Пример кода по работе с alarmManager:

    val restartIntent = Intent(this, javaClass)
    val am = getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val pi = PendingIntent.getService(this, 1, restartIntent, PendingIntent.FLAG_ONE_SHOT)
    restartIntent.putExtra("RESTART", "")
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), System.currentTimeMillis() + 5000, pi)

Пример кода по работе с startForeground:

private fun startForeground() {
    val channelId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel("FloatVolumeButtonService", "My Background Service Float_volume_button")
    } else {
        // If earlier version channel ID is not used
    }

    val notificationIntent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)
    val notificationBuilder = NotificationCompat.Builder(this, channelId)
    val notification = notificationBuilder.setOngoing(true)
        .setSmallIcon(R.drawable.ic_volume)
        .setPriority(NotificationCompat.PRIORITY_MIN)
        .setCategory(Notification.CATEGORY_SERVICE)
        .setContentIntent(pendingIntent)
        .build()
    startForeground(101, notification)
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String {
    val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
    chan.lightColor = Color.BLUE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

Ответы (0 шт):