Foreground Services let your app perform important tasks that users are aware of, with persistent notifications. This is essential for tracking, timers, and location services.
Creating a Foreground Service
Declare the service in AndroidManifest.xml:
<service
android:name=".LocationTrackingService"
android:foregroundServiceType="location" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
Service Implementation with Notification
class LocationTrackingService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Location Tracking")
.setContentText("Your location is being tracked")
.setSmallIcon(R.drawable.ic_location)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
startForeground(NOTIFICATION_ID, notification)
lifecycleScope.launchWhenStarted {
trackLocation()
}
return START_STICKY
}
private suspend fun trackLocation() {
// Your location tracking logic
}
}
Starting a Foreground Service from Compose
@Composable
fun TimerScreen() {
Button(
onClick = {
val intent = Intent(context, TimerService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
) {
Text("Start Timer")
}
}
Updating Notification from Service
Keep users informed with dynamic notification updates:
private fun updateNotification(timeRemaining: Long) {
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Timer")
.setContentText("$timeRemaining seconds remaining")
.setProgress(100, progress, false)
.build()
notificationManager.notify(NOTIFICATION_ID, notification)
}
Foreground Services are crucial for building reliable, user-aware background operations.
8 Android app templates available on Gumroad
Top comments (0)