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.
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.
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