Foreground Service

1. What is a Foreground Service?

A Foreground Service is a service used for long-running work that the user should know about.

It must show a visible notification.

Simple Meaning

Foreground Service = Long running work + Visible notification

2. When Should We Use Foreground Service?

Use Foreground Service when work is:

Important + Running now + User visible

Common Examples

Use CaseWhy Foreground Service?
Music playerUser knows music is playing
NavigationUser knows location/navigation is active
Fitness trackingUser knows tracking is running
Ongoing callUser knows call is active
Screen recordingUser knows screen is being recorded
Large uploadUser can see upload progress


3. Foreground Service Flow

Activity starts Foreground Service
        ↓
Service.onCreate()
        ↓
Create Notification Channel
        ↓
Service.onStartCommand()
        ↓
Create Notification
        ↓
startForeground()
        ↓
Work starts
        ↓
User sees notification
        ↓
Work completed
        ↓
Stop service


4. How Foreground Service Works Internally

App requests service start
        ↓
Android starts Service
        ↓
Service creates notification
        ↓
Service calls startForeground()
        ↓
Android shows notification
        ↓
System understands user is aware of work
        ↓
Service continues with higher priority

Important:

Foreground Service must show notification.
Without notification, it is wrong.


5. Foreground Service Manifest

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<service
    android:name=".MusicService"
    android:exported="false"
    android:foregroundServiceType="mediaPlayback" />
For Android 14 and above, foreground service type is important.

Examples:

Foreground Service TypeUse Case
mediaPlaybackMusic player
locationLocation tracking
cameraCamera usage
microphoneAudio recording
dataSyncData sync
phoneCallOngoing call


6. Foreground Service Code Example

MusicService.kt

class MusicService : Service() {

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    override fun onStartCommand(
        intent: Intent?,
        flags: Int,
        startId: Int
    ): Int {

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Music Playing")
            .setContentText("Your song is playing")
            .setSmallIcon(R.drawable.ic_music)
            .setOngoing(true)
            .build()

        startForeground(1, notification)

        playMusic()

        return START_STICKY
    }

    private fun playMusic() {
        Log.d("MusicService", "Music started")

        // Start MediaPlayer here
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("MusicService", "Music stopped")

        // Stop MediaPlayer here
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val channel = NotificationChannel(
                CHANNEL_ID,
                "Music Service",
                NotificationManager.IMPORTANCE_LOW
            )

            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    companion object {
        const val CHANNEL_ID = "music_channel"
    }
}

Start Foreground Service from Activity

val intent = Intent(this, MusicService::class.java)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent)
} else {
    startService(intent)
}

Stop Foreground Service

val intent = Intent(this, MusicService::class.java)
stopService(intent)


7. Android 12+ Foreground Service Restriction

From Android 12/API 31+, apps generally cannot start a foreground service from the background unless they have a valid allowed reason.

Simple Meaning

If app is already in background,
do not randomly start Foreground Service.

Better option:

Use WorkManager for deferrable background work.
Use Foreground Service only for urgent user-visible work.


8. Benefits of Foreground Service

BenefitExplanation
Good for long-running workUseful for music, navigation, tracking
User is awareNotification shows active work
Higher priorityLess likely to be killed than normal background service
Good for progress updatesUpload/download progress can be shown


9. Drawbacks of Foreground Service

DrawbackExplanation
Notification requiredUser must always see notification
More restrictionsAndroid 12+ has strict background start rules
Permission handlingNeeds correct permissions
Foreground type requiredAndroid 14+ requires correct service type
Not for silent workShould not be used for hidden background tasks