I've a question about the AlarmManager
and the BroadcastReceiver
!
I want to use the AlarmManager
to update some data every 15th minute (this is not the case in the code since I'm still trying to get the functionality to work) but something I don't really understand has occurred.
Every time the onReceive
method is being called by the timer, it gets called 3-5 fast times at once, the LogCat
message is being written 3-5 times. Is it something wrong with my code?
Code:
Method in the MainActivity
class:
private void setCloseByChecker() {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cal=Calendar.getInstance();
Intent intent = new Intent(this, CloseByReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis() + 15000, 15000, pendingIntent);
}
And the BroadcastReceiver
class:
@Override
public void onReceive(Context context, Intent intent) {
Log.i("hello","hello");
}
From the documentation.
If the stated trigger time is in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.
For testing purposes, change the public void setRepeating (int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)
set intervalMillis to 5 minutes or something, then repeat the operation. Should you still receive more than one Broadcast, its something else.
Also, from the documentation:
This alarm continues repeating until explicitly removed with cancel(PendingIntent).
Meaning that you should cancel the PendingIntent every time it completes what it needs to do, otherwise you may be using recursing to set an operation until you complete it. To check for this, run your code for a couple of minutes, then check if the BroadCast ammount has increased. If it did, you are starting a new alarm before the last one completed.
Then again, from the same documentation:
If your application wants to allow the delivery times to drift in order to guarantee that at least a certain time interval always elapses between alarms, then the approach to take is to use one-time alarms, scheduling the next one yourself when handling each alarm delivery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With