I want to schedule simple local notifications in my Android app.
This was working fine when I was targeting API 24, but since I have to move to the last API in order to be able to update my app, I have to change some things in my code.
Currently, I use a WakefulBroadcastReceiver
and a simple Service
to send the notification.
Every time I want to send a notification, I send an Intent
to my WakefulBroadcastReceiver
with all the info, and in the onReceive
method I create a service and call startWakefulService(context, service);
.
The WakefulBroadcastReceiver
ensures that the process is not killed and the service does the heavy job in the background before firing the notification.
But now with the new background limitations of the last Android versions, I cannot simply start a service when my app is in the background, so every attempt to send a notification crashes my app: java.lang.IllegalStateException: Not allowed to start service: app is in background.
I also noticed that WakefulBroadcastReceiver
is now deprecated.
When the alarm is set:
Intent broadcastIntent = new Intent(context, NotifBroadcastReceiver.class);
// ...
alarmIntent = PendingIntent.getBroadcast(context, idNotification, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
millis, interval, alarmIntent);
When the alarm is received: (in the NotifBroadcastReceiver class)
// onReceive method
startWakefulService(context, service);
// the service then does the heavy job and fires the notification...
My Questions:
BroadcastReceiver
(instead of a WakefulBroadcastReceiver
) to send the notification by ensuring that CPU stays awake the whole process?I've read about the JobScheduler
, but it seems that it cannot be used in this case, since it cannot garantee me that it will run in the exact time.
The notifications are a very important part of my app, so if they're not fired anymore the app is practically useless...
I ended up using IntentJobService
as it's the same as Service
for Pre-O and uses Jobs
for Android O.