Apps that target Android 12 (API level 31) or higher can’t start foreground services while running in the background, except for a few special cases. If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException.
Exemptions from background start restrictions
In the following situations, your app can start foreground services even while your app is running in the background:
- Your app transitions from a user-visible state, such as an activity.
- Your app can start an activity from the background, except for the
case where the app has an activity in the back stack of an existing
task. - Your app receives a high-priority message using Firebase Cloud
Messaging. - The user performs an action on a UI element related to your app. For
example, they might interact with a bubble, notification, widget, or
activity. - Your app invokes an exact alarm to complete an action that the user
requests. - Your app is the device’s current input method.
- Your app receives an event that’s related to geofencing or activity
recognition transition. - After the device reboots and receives the ACTION_BOOT_COMPLETED,
ACTION_LOCKED_BOOT_COMPLETED, or ACTION_MY_PACKAGE_REPLACED intent
action in a broadcast receiver.
For more info please check link1 link2