Reputation: 506
I am having trouble with using Alarm Manager to fire a pending intent in the future. I have been at it for hours, and do not understand what I am doing wrong. Any help would be greatly appreciated.
This works, sending a broadcast immedietely:
_context.startService(notificationIntent);
This works, sending a broadcast in ~30 seconds:
if (mgr != null)
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 30000, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);
This works, sending a broadcast in ~30 seconds:
if (mgr != null)
mgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);
But for some unknown reason, doing this fails. The broadcast is never triggered. When I take System.currentTimeMillis(), and subtract it from my trigger...it shows that the trigger is indeed in the future:
if (mgr != null)
mgr.setExact(AlarmManager.RTC_WAKEUP, trigger, pendingNotificationIntent);
I am printing my variable 'trigger' (type long) to console, and it is definitely a valid time (according to epochconverter.com). The value it is printing currently (just for reference) is 1521144300000, which elapsed a few minutes ago..never having fired my alarm;
Here is most of the setup:
Intent notificationIntent = new Intent(_context, com.example.example.NotificationReceiver.class)
.setAction(ACTION_SHOW_NOTIFICATION)
.putExtra(EXTRA_NOTIFICATION_TITLE, _title)
.putExtra(EXTRA_NOTIFICATION_BODY, newBody)
.putExtra(EXTRA_NOTIFICATION_TRIGGER_TIME, trigger);
AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(_context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG, "trigger time: " + trigger);
if (mgr != null) mgr.setExact(AlarmManager.RTC_WAKEUP, trigger, pendingNotificationIntent);
I receive the trigger time from the back-end, which appears correct in every response.
This also never fires:
if (mgr != null) mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, trigger, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);
Upvotes: 0
Views: 2096
Reputation: 306
There are some considerations depending in the Android version in which you are testing the alarm, but if you are testing for Android 6 or later then try the next code:
// Init the Alarm Manager.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Setting the PendingIntent to be fired when alarm triggers.
Intent serviceIntent = new Intent(context.getApplicationContext(), YourService.class);
PendingIntent pendingServiceIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
// Set the alarm for the next seconds.
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000, pendingServiceIntent);
Upvotes: 1