moritzbruder
moritzbruder

Reputation: 83

Android AlarmManager firing at random times

I'm developing an application which has to show some Notifications and that has to download some data two times a day, so i created a Service for launching my Notifications and a BroadcastReceiver which should (depending on the time) run my NotificationService and later also my DownloadService. My problem is now, that the AlarmManager-alarm i created should call fire every hour (not important if 1 or 2 minutes less or more), and it does that for about 3 to 4 hours but then it runs randomly and also multiple times in between for example 7 and 8 o'clock.

I have no idea where the problem could be so here is my code:

Activity:

Intent myIntent = new Intent(OverviewActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(OverviewActivity.this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notifCal.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);

Receiver:

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Intent notificationService = new Intent(context, NotificationService.class);
        context.startService(notificationService);<br/>
    }

}

Thanks in advance, momob114

Upvotes: 0

Views: 847

Answers (1)

Tleilaxus
Tleilaxus

Reputation: 61

Each time your Activity is fired your app is cancelling and recreating the Alarm which could be the cause of the seemingly random calls (which could actually correspond to the time you opened the app, or one hour later).

Note in case you still want to do that, instead of cancelling the previous alarm you can just call :

PendingIntent pendingIntent = PendingIntent.getBroadcast(OverviewActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Keep also in mind that a reboot of the device will clear any alarms that you might have set. So you'll probably want to create a BroadcastReceiver listening for the android.intent.action.BOOT_COMPLETED action in order to set your repeating alarm then.

Upvotes: 1

Related Questions