Ответ
Создание Foreground Service в Android требует нескольких шагов:
- Объявить сервис в манифесте:
<service android:name=".MyForegroundService" />
- Создать сервис:
class MyForegroundService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, "channel_id")
.setContentTitle("Foreground Service")
.setContentText("Running...")
.setSmallIcon(R.drawable.ic_notification)
.build()
startForeground(1, notification)
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
}
- Запустить сервис из Activity:
val serviceIntent = Intent(this, MyForegroundService::class.java)
ContextCompat.startForegroundService(this, serviceIntent)
Ключевые моменты:
- Необходимо создать Notification канал для Android 8+
- Требуется иконка для уведомления
- startForeground() должен быть вызван в течение 5 секунд после startForegroundService()
- Для Android 9+ нужно разрешение FOREGROUND_SERVICE в манифесте