Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my android alarm manager firing instantly?

I am following sample code for sending an update notification every 10'seconds. The code follows and it is in an UpdateService for an AppWidgetProvider. If I put a Thread.sleep(10*1000); I can see the expected behavior of my servicing loop. I obviously have something fundamentally wrong that is triggering immediately. It is supposed to be a PendingIntent of an alarm that will broadcast update to my listener.

long nextUpdate = 10*1000;
Log.d(TAG, "Requesting next update in " + nextUpdate + " msec." );

Intent updateIntent = new Intent(ACTION_UPDATE_ALL);
updateIntent.setClass(this, UpdateService.class);

PendingIntent pendingIntent = PendingIntent.getService(this, 0, updateIntent, 0);

// Schedule alarm, and force the device awake for this update
AlarmManager alarmManager = (AlarmManager)getBaseContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 
    nextUpdate, pendingIntent);
like image 320
mobibob Avatar asked Jul 29 '10 02:07

mobibob


People also ask

How do I turn off alarm manager?

You can cancel the alarm like this: Intent intent = new Intent(this, Mote. class); PendingIntent pendingIntent = PendingIntent. getBroadcast(getApplicationContext(), 1253, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.

What is Android alarm Manager?

AlarmManager is a bridge between application and Android system alarm service. It can send a broadcast to your app (which can be completely terminated by user) at a scheduled time and your app can then perform any task accordingly.

Does alarm Manager persist even after reboot?

Start an alarm when the device restarts This ensures that the AlarmManager will continue doing its task without the user needing to manually restart the alarm.


1 Answers

If you are creating PendingIntent of an alarm for past time it will be fired immediately. Example - Schedule alarm for today 8AM but executing code around 11AM will fire immediately.

Solution:

cal.add(Calendar.DATE, 1);

long delay = 24 * 60 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), delay,pendingIntent);` 

This will fire the event on next day at specified time (i.e 8AM);

like image 57
Shripad Bhat Avatar answered Oct 08 '22 04:10

Shripad Bhat