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