I cannot believe I'm asking this, but I want to schedule notifications in my Android app (repeating or not).
I managed to do this easily following the Android training article, using WakefulBroadcastReceiver and Services. But now, since I have to target the last Android APIs for my future updates, I have to make some changes to my code.
I believe that WakefulBroadcastReceiver has been deprecated, so I'm using a simple BroadcastReceiver instead.
Current implementation
Whenever I want to schedule an alarm, I'm sending an Intent to my BroadcastReceiver, and in the onReceive method, instead of the old call to startWakefulService(context, service);, I did a context.startService(service);. But with the background limitations, I cannot start a service when my app is in the background...
I have an error: java.lang.IllegalStateException: Not allowed to start service: app is in background
How can I change my code effectively to handle this problem? The service I call is the one that sends the notifications to the user.
Code
Set the alarm
Intent broadcastIntent = new Intent(context, AlarmReceiver.class); // put the extras for the notification details // ... alarmIntent = PendingIntent.getBroadcast(context, idNotif, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, millis, interval, alarmIntent);The
Intentis received in theAlarmReceiverclass// onReceive method context.startService(service); // The ERROR is raised here when my app is in bg
EDIT
I cannot use JobScheduler as it will not guarantee me that the notifications will be sent in time.
I cannot start a foreground service too to send my notifications.