Search code examples
androidandroid-fragmentstimeralarmmanager

Why isn't my AlarmManager working?


I am trying to make an alarm that triggers an event some number of seconds from now, one time, from within a DialogFragment.

Here is the relevant code, I put in onCreate():

broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent i) {
        Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
    }
};
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(ALARM_MANAGER_TAG) );
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ALARM_MANAGER_TAG), 0 );
alarmManager = (AlarmManager)(getActivity().getSystemService( Context.ALARM_SERVICE ));

And then when I press the start button:

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timestampEnd, pendingIntent);

In this case timestampEnd = System.currentTimeMillis() + 10 * 1000;, 10 seconds.

And then I have overridden destroy:

@Override
public void onDestroy() {
    alarmManager.cancel(pendingIntent);
    getActivity().unregisterReceiver(broadcastReceiver);
    super.onDestroy();
}

And yet, nothing happens for some reason.


Solution

  • You're passing AlarmManager.ELAPSED_REALTIME_WAKEUP, which means the AlarmManager is going to use SystemClock.elapsedRealtime() when checking timestamps. Since you're passing something calculated off of System.currentTimeMillis(), you are going to have to wait about 47 years before the alarm fires.

    Either change your first argument to AlarmManager.RTC_WAKEUP or change your timestamp to be calculated off of SystemClock.elapsedRealtime().