Sobes.tech
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:

  1. Starts with startForegroundService().
  2. Within 5 seconds, call startForeground(notificationId, notification) to move the service to the foreground. Otherwise, the system may stop the service and throw ForegroundServiceDidNotStartInTimeException.
  3. Stops with stopSelf() or stopService() from another component, or forcibly by the user through the notification. When stopping, call stopForeground(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()
}