Search code examples
androidservicebroadcastreceiveralarmmanager

Android AlarmManager defaulting to 5 minutes when phone screen is off


So I am having an issue with AlarmManager. I am trying to run some code every 2 minutes, which works okay while the phone is awake, but not when the device goes to sleep - during sleep, the intervals are perfectly 5 minutes apart.

Since my desired interval is 2 minutes, this is roughly 250% off my target interval, which for my specific application is not acceptable.

I am aware of the changes in API 19, and have followed suggestions to re-schedule the alarm using setExact() within my BroadcastReceiver. Code is below:

The code used to trigger BroadcastReceiver:

    Intent intent = new Intent(this, AlarmReceiver.class);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(this,  0, intent, 0);

    mAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3000, pendingIntent);

And this code is in my BroadcastReceiver which re-schedules the alarm:

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "AlarmService Triggered.", Toast.LENGTH_SHORT).show();
    Log.d(this.getClass().getSimpleName(), "Service triggered");

    Intent newIntent = new Intent(context, this.getClass());
    mPendingIntent = PendingIntent.getBroadcast(context, 0, newIntent, 0);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120000, mPendingIntent);
}

Does anyone have suggestions as to how I could fix this? It is very frustrating that AlarmManager is totally ignoring my wish to have an alarm fire at an exact time. Is there any alternative that will allow me to schedule code at 2 minute intervals like I want?

DEVICE: Samsung Galaxy S6, OS 5.1.1


Solution

  • As @Francesc suggested, it ended up being the Samsung device. Tried it on another phone, now it works flawlessly.

    Let this be a lesson to you - don't buy Samsung, they do weird stuff, lol.