RGS
RGS

Reputation: 4253

Alarm is firing every second?

I have a function to repeat alarm every 15 minutes.

The problem is it is firing every second.

I have this in my main activity:

 AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intentn = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intentn, 0);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());

        if(android.os.Build.VERSION.SDK_INT>=23) {
            alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,1000*900, pendingIntent);
        }
        else{
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP, 1000*900, pendingIntent);
        }

and I repeated the same thing above in my AlarmReceiver onReceive() to set it again after it fires.

any ideas what is wrong and what can I do to make it repeat correctly?

Upvotes: 0

Views: 48

Answers (2)

Ramindu Weeraman
Ramindu Weeraman

Reputation: 354

Try to use android worker manager since it is working with doze mode as well. https://developer.android.com/reference/androidx/work/PeriodicWorkRequest#min_periodic_interval_millis

Upvotes: 0

michael
michael

Reputation: 462

First of all, you are setting the alarm without adding the current time. See below:

...
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 1000*900, pendingIntent);
...
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, 1000*900, pendingIntent);
...

should instead be

...
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time + 1000*900, pendingIntent);
...
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, time + 1000*900, pendingIntent);
...

Second of all, there exists a function to do exactly what I believe you're trying to accomplish here (set a repeating alarm). See setRepeating().

Upvotes: 1

Related Questions