Foreground Service
Also known as: foreground service android, long running service, android foreground service
An Android foreground service is a long-running service the user is actively aware of, shown with a persistent status-bar notification. It keeps work like a storage scan alive after the user leaves the app, with a far lower chance of being killed than a background service.
- Requires a persistent, user-visible notification via startForeground() or the system kills the app.
- Android 14 (API 34)+ requires a typed foregroundServiceType (e.g. dataSync) and matching permission.
- For deferrable cleanup work, WorkManager's expedited/long-running workers are the recommended wrapper.
What it is and why it exists
A foreground service performs work that is noticeable to the user and must keep running even when the app is not in the foreground. Because Android aggressively kills background work to save battery and memory, a foreground service is the supported way to keep a task alive across screen-off and app-switch events.
The defining requirement is a user-visible persistent notification. The system enforces this: a foreground service must call startForeground() with a notification shortly after it starts, or Android raises an exception and may stop the app. This is the trade Android makes for granting the elevated process priority.
How you start one (modern API levels)
On Android 8.0 (API 26)+ you launch it with startForegroundService(), then the service has a short window to call startForeground() with a notification ID and a `Notification`. On Android 9 (API 28)+ you must also declare the FOREGROUND_SERVICE permission, and on Android 14 (API 34)+ you must declare a specific typed permission such as FOREGROUND_SERVICE_DATA_SYNC plus a `foregroundServiceType` in the manifest.
Android 12 (API 31) blocked starting a foreground service while the app is in the background, except for allow-listed cases. For deferrable work, WorkManager with an expedited or long-running worker is usually preferable, since it handles constraints, retries, and the foreground-service plumbing for you.
Where it fits in a cleaner app
A storage-cleanup scan can take a while when it hashes thousands of photos to find duplicates or walks the entire MediaStore. Wrapping that scan in a foreground service (or an expedited WorkManager job that promotes itself to the foreground) lets Cleanor keep scanning while you switch apps or lock the screen, with a notification showing progress so the work is transparent and not silently draining the battery.