Search code examples
androidandroid-servicealarmmanagerandroid-alarmsandroid-background

Can we startForegroundServie from an exact alarm's receiver in the background?


In one of the exemptions of the "cannot start foreground service from background" restriction, the doc mentions:

Your app invokes an exact alarm to complete an action that the user requests.

Does this mean that the usage scenario below can work?

  1. Use AlarmManager.setAlarmClock to schedule an exact alarm to trigger at time A. The alarm carries a pendingIntent that targets a registered broadcast receiver.

  2. Time A hits, the receiver gets the intent.

  3. In the receiver OnCreate method, we attempt to startForegroundServicewhich involves displaying a sticky notification and playing custom music with MediaPlayer.


Solution

  • I have implemented and tested this and it appears to be working, so I assume this is a valid use case.