Junior — Middle
Can you give an example of using services that run in the foreground in Android?
sobes.tech AI
Answer from AI
Foreground services in Android are used for tasks that need to continue running even when the app is in the background, and must display a notification to inform the user.
Examples:
- Music player — playing music in the background with controls in the notification.
- Navigation apps — providing directions in the background.
- File downloaders — long downloads with progress display.
Example of creating a foreground service with a notification:
class MyForegroundService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Service is running")
.setContentText("Performing important task")
.setSmallIcon(R.drawable.ic_service_icon)
.build()
startForeground(1, notification)
// Service logic
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
}
It is important that a foreground service must show a notification, so the user is aware of its operation.