Middle
What is a background service (foreground service) in Android?
sobes.tech AI
Answer from AI
Foreground service — is a type of service in Android that has a higher priority and is visible to the user. It performs tasks that are noticeable to the user and should not be interrupted when conserving battery or memory.
Key characteristics:
- Displays a persistent notification in the notification area. The user should be able to see that the service is running and potentially interact with it.
- The system is less likely to kill a foreground service compared to a regular background service or thread due to its high priority.
- Requires a special permission
FOREGROUND_SERVICE. - Used for tasks like music playback, location tracking, real-time data synchronization.
Lifecycle:
- Starts with
startForegroundService(). - Within 5 seconds, call
startForeground(notificationId, notification)to move the service to the foreground. Otherwise, the system may stop the service and throwForegroundServiceDidNotStartInTimeException. - Stops with
stopSelf()orstopService()from another component, or forcibly by the user through the notification. When stopping, callstopForeground(bool removeNotification)to remove the notification.
Example of starting:
// Request permission
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.FOREGROUND_SERVICE),
REQUEST_CODE_FOREGROUND_SERVICE
)
// In callback after permission is granted or if already granted
val serviceIntent = Intent(this, MyForegroundService::class.java)
ContextCompat.startForegroundService(this, serviceIntent)
Inside the service:
// MyForegroundService.kt
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification: Notification = createNotification() // Method to create notification
startForeground(NOTIFICATION_ID, notification)
// Service task execution begins here
return START_STICKY // Or another suitable flag
}
override fun onDestroy() {
stopForeground(true) // Remove notification on stop
// Resource cleanup
super.onDestroy()
}