Search code examples
androidalarmmanagerandroid-4.4-kitkat

AlarmManager stops working in Android 4.4.2 (using SetExact())


I'm setting in my code an alarm to go off in specific time.
The alarm mechanism works great on SDK < 19, but on 19 the alarms aren't fired.
Here is the code where I set the alarm :

public void SetAlarm(Context context, Long executionTime)
{

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReciever.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    // Only one alarm can live, so cancel previous.
    am.cancel(pi);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        am.set(AlarmManager.RTC_WAKEUP, executionTime, pi);
    } else {
        setAlarmFromKitkat(am, executionTime, pi);
    }
}

Since I'm setting the alarm using a Service I use GetApplicationContext() as the context.

The onReceive() code :

@Override
public void onReceive(Context context, Intent intent) {
    for (SchedulerListener listener : listeners) {
        listener.fetchAndRebuildNotification();
    }
}

Here is the declaration of the BroadcastReceiver :

<receiver 
        android:name="com.SagiL.myAppName.BroadCastReceivers.AlarmReciever" />

The callback runs a method in a service (which is still alive when the alarm supposed to fire, notice it doesn't starts one).

This whole thing is a library which is used in my app, and there I declare the receiver the same way.

Sometimes the alarm do fires once, but mostly it doesn't fire at all.

Has anyone experienced such a thing ?
I can't believe it's common to SDK 19 since a lot of apps are using AlarmManager and they will break too if it is common.


Solution

  • I had a similar problem with my application. I found out that using 0 ad the id in getBroadcast(...); didn't work very well and caused numerous problems.

    Try changing the id from 0 to the alarm's real id.

    From:

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    

    To:

    PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);