I have an app that should update/get data from a server every six hours. To do so I made an AlarmManager the following way:
public class Repository {
public static AlarmManager alarmManager;
public static void initAlarmManager(Context context){
//start the update alarm manager
Intent resultIntent = new Intent(context,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 60 * 60 * 1000, pendingIntent);
}
My AlarmReceiver now has to look for updates and if there is new data of a specific condition it has to notify the user via a notification. This is a part of my AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Repository.ddfDb == null){
Repository.initDdfDb(context);
}
if(Repository.alarmManager == null){
Repository.initAlarmManager(context);
}
for(Episode episode : Repository.ddfDb.getListOfNextEpisodes()){
Notification.showNotification(context,episode);
}
}
}
Since my AlarmManager should run all the time I let him start also when boot is completed. To do so I added the following to my manifest file:
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
I run the function initAlarmManager() in my onCreate() of the mainActivity. So if the app is started, the AlarmManager starts too and everything works fine. Even if I close my app via the home button or change to another app via the "change between recent apps" button, my AlarmManager still fires and I get the notifications although my app is in the background.
I also run the function initAlarmManager() in my AlarmReceiver. So if I reboot my phone, the receiver gets called, sees that my AlarmManager is null and inits it afterwards. So everything works fine here too.
But here is my problem: If I press the "change between recent apps" button and close my app with a swipe my AlarmManager stops and I won't get any further notifications. This is weird, since after a reboot my app also doesn't appear in the recent apps menu but there it works.
I googled a lot and some people say it is impossible, since if the user really wants to close the app, he has to be able to do so. I understand this, since it provides security against virus apps. But also I see apps like WhattsApp being able to always notify the user.
So is there really no way to accomplish my always running AlarmManager or if there is a way, how do I implement this?
Thank you in advance!