Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PendingIntent scheduled using AlarmManager.RTC type is still invoked in the sleep mode

Here is the code that I used to set an alarm for my widget:

 private static void setAlarm(Context context) {
    Intent myIntent = new Intent(context, Widget.class);
    myIntent.setAction(AUTO_UPDATE);
    PendingIntent pendingIntent =
            PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 8);
    alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
            pendingIntent);
}  

but the problem is that even in the sleep mode, onReceive() is still triggered by the intent.

Although after using setInexactRepeating instead of setRepeating, the delays between calls get increased up to 1 minute in sleep mode, but that's still battery consuming.

like image 478
SAbbasizadeh Avatar asked Sep 19 '12 12:09

SAbbasizadeh


1 Answers

I believe you are setting the alarm to trigger 8 seconds after the Calendar's time, which you have set 8 seconds ahead of the current time .. so you are setting the alarm to trigger instantly.

I don't see any reason you need a Calendar here. The calendar is just used to track the time 8 seconds in the future here:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 8);

The alarm is created to trigger every 8 seconds here:

alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
        pendingIntent);

The alarm continues to trigger every eight seconds.

I would try changing:

alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 8000,
        pendingIntent);

To:

alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), 8000,
        pendingIntent);

If you continue having problems, then maybe the interval is the problem. Try changing setRepeating() to set() to see if that's the case.

like image 195
CodeShane Avatar answered Nov 09 '22 11:11

CodeShane