Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, onReceive in BroadCastReceiver is being called multiple times

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");
}
like image 481
user3423108 Avatar asked Mar 23 '14 16:03

user3423108


Video Answer


1 Answers

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.

like image 93
Bonatti Avatar answered Oct 18 '22 22:10

Bonatti