Search code examples
androidalarmmanager

Alarm doesn't trigger notification after turning of device Android


In my app I need to set alarm, and show notification in status bar. I store scheduled events in data base, and remove event when notification shows up.

When I turn off device, and turn on again. The list in base exists, but alarm event never triggers. It seems like pending events are canceled when I turned off device.

How to prevent this? I need to show notification whenever the devices is on, and time for alarm comes up.

This is how I set alarm:

    Intent intent = new Intent(activity, TimeAlarm.class);
    intent.putExtra(SHOW_NAME, showName);
    intent.putExtra(SHOW_START_TIME, showStartTime);
    intent.putExtra(CHANNEL_NAME, channelName);
    intent.putExtra(VIBRATION_ENABLED, isVibrate);
    intent.putExtra(SOUND_ENABLED, isSound);

    int alarmId = (int) System.currentTimeMillis();

    intent.putExtra(ALARM_ID, alarmId);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(activity,
            alarmId, intent, PendingIntent.FLAG_ONE_SHOT);

    am.set(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + delayMilis, pendingIntent);

In Manifest file I have only this:

 <receiver
        android:name="com.moleandroid.tvprogramgui.alarm.TimeAlarm"
 /receiver>

TimeAlarm class is my receiver, and from there I show notification in status bar.

Any idea whats wrong?


Solution

  • Here what you need to do resolve this issue. usually when device is getting turned off it will cancel all the pendingIntent for the alarm and hence it will not trigger while device is turned on again. what alarm application do internally is while device is getting turned off/on it will start the service to register the events

    refer this link to implement the shutdown and power on intent in the code. so when device is powered on schedule all your events to AlarmManager and I am sure this will work

    Is there any way to receive a notification when the user powers off the device?