0

I have set alarm to get trigger after 60 seconds. but the alarm is getting triggered after 80/90 seconds (But not exactly after 60 seconds). How can i set alarm to get trigger exact at specified time?

 //calling method to set alarm after 60 seconds
    startAlarm(context, 1, System.currentTimeMillis()+60000);

    //method defination
    public static void startAlarm(Context context, int timerType, long nextScheduledTime) {
            EABLog.d(TAG, " ~~~INSIDE START ALARM~~~~~ "+timerType);
            Intent intent = new Intent(context, AlarmReceiver.class);
            intent.putExtra(Constants.KEY_TIMER_TYPE, timerType);
            intent.setAction(""+timerType);
            PendingIntent pollPendingIntent = PendingIntent.getBroadcast(context,
                    timerType, intent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmManager = (AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextScheduledTime,
                    pollPendingIntent);
            EABLog.d(TAG, System.currentTimeMillis()+" ALARM IS SET AT "+nextScheduledTime+" TYPE :"+timerType);
        }


//permission added in Android Manifest
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243

1 Answers1

0

As docs say about setExact - The alarm will be delivered as nearly as possible to the requested trigger time. So it is not as exact as you think :)

Look at public void setWindow (int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation) methods 3rd parameter - windowLengthMillis The length of the requested delivery window, in milliseconds. The alarm will be delivered no later than this many milliseconds after windowStartMillis. This might do the trick :)

Dmitrijs
  • 1,333
  • 1
  • 14
  • 20
  • Can you please provide an example of how it's used? Has it also changed on newer Android versions? – android developer Feb 05 '20 at 15:18
  • Now you have to use AlarmManagerCompat.setExactAndAllowWhileIdle + many things like removing an app from battery optimization list etc. – Dmitrijs Feb 05 '20 at 15:20
  • Android Clock app has a system permission, it is an exception for all optimizations, but on Android 10 few phones like Huawei or Xiaomi might block even the system Clock app. – Dmitrijs Feb 05 '20 at 15:42
  • But it says "setExactAndAllowWhileIdle " is restricted to number of times it can trigger in short time, yet for some reason Clock app of Google can wake up with 2 alarms set, one minute after another, and that's even though it's not on the battery optimization list in the "not optimized" section. How come? Anyway, I've made this question: https://stackoverflow.com/q/60079472/878126 – android developer Feb 05 '20 at 15:52