Reputation: 2471
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?
Use AlarmManager.setAlarmClock
to schedule an exact alarm to trigger at time A. The alarm carries a pendingIntent
that targets a registered broadcast receiver.
Time A hits, the receiver gets the intent.
In the receiver OnCreate
method, we attempt to startForegroundService
which involves displaying a sticky notification and playing custom music with MediaPlayer
.
Upvotes: 4
Views: 959
Reputation: 4634
Yes, your described scenario should work and be compliant regarding the restrictions introduced with Android 12.
However, consider whether you can target the service directly with your pending intent instead of the broadcast receiver and starting the service from there. Jumping between the two is unnecessary and might even result in the service not being started - see this comment in Android's official alarm clock app (DeskClock):
// This intent is directed to AlarmService, though the actual handling of it occurs here
// in AlarmStateManager. The reason is that evidence exists showing the jump between the
// broadcast receiver (AlarmStateManager) and service (AlarmService) can be thwarted by
// the Out Of Memory killer. If clock is killed during that jump, firing an alarm can
// fail to occur. To be safer, the call begins in AlarmService, which has the power to
// display the firing alarm if needed, so no jump is needed.
val intent: Intent =
AlarmInstance.createIntent(context, AlarmService::class.java, instance.mId)
Upvotes: 0
Reputation: 2471
I have implemented and tested this and it appears to be working, so I assume this is a valid use case.
Upvotes: 4