Search code examples
androidservicealarmmanagerkillrepeatingalarm

Why repeating tasks with alarm manager are not accurate on android?


I'm developing an app which you can schedule your time and It reminds you on time just like google calendar. I use AlarmManager class and set a Repeating task to check Database every one minute and see if there is any alarm on that time or not.

@Override
public void onReceive(Context context, Intent intent) {

    Calendar now = Calendar.getInstance();

    doRepeatingWorks(now.getTimeInMillis()); // Like Checking if one day passed to do some tasks

    checkDbIfThereIsSomeSchedule(now);
}

And I call this to start alarm manager:

    public void setAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), G.ALARM_CHECK_INTERVAL_MILIS, pendingIntent);
}

But it's inaccurate and sometimes I figure out that the task killer apps kill my alarm and make it totally worthless.

Although using a foregroundService is battery consuming and it goes on user's nerve with the notification.

Is there any solutions or alternatives for this problem?


Solution

  • I use AlarmManager class and set a Repeating task to check Database every one minute and see if there is any alarm on that time or not

    That is a truly awful approach. This sort of behavior is precisely why Doze mode and app standby were added in Android 6.0.

    Is there any solutions or alternatives for this problem?"

    Schedule an alarm event for first event. When you get control, notify the user about the event, then schedule an alarm event for the next event in sequence. If the user adds a new event that is sooner than your first event, cancel the previous alarm and schedule one for the new first event.