Foreground service launch restrictions-Android12
Published in
3 min readNov 4, 2021
- Applications that target Android 12 or higher can’t start foreground services while running in the background.
- If an application attempts to start a foreground service while running in the background, the 🛑
ForegroundServiceStartNotAllowedException
🛑exception occurs. - Android 12 or higher provides a smooth experience for short-running foreground services, the system waits 10 seconds before showing the
notification
associated with a foreground service. - Service can opt-out of this behavior change by passing
FOREGROUND_SERVICE_IMMEDIATE
intosetForegroundServiceBehavior()
when setting up the notification.
Special cases that are still considered valid
- Application transitions from a user-visible state, such as an activity.
- The application can start an activity from the background.
- The application receives a high-priority message using Firebase Cloud Messaging.
Check the full list here
Check whether the app performs background starts
- We can enable notifications 🔔 that appear each time the application attempts to
launch a foreground service while running in the background
. - Execute the following
ADB command
on the development machine connected to device or emulator 📱:
Warning 🔔 😬
Foreground Service
Custom Application class
- When the application moves to the ⏹
STOP STATE
then after waiting 5 seconds it will try to 🏁 start the ForegroundService.
Solutions
- WorkManager 2.7: Use it to schedule and start expedited work while the app runs in the background.
- AlarmManager: Start foreground services within an exact alarm ⏰ to complete time-sensitive actions that the user requests.