phpdroid phpdroid - 10 months ago 81
Java Question

Alarm set more frequently than time provided

Whenever user enters MainActivity I am setting alarm on an interval of 43200000 miliseconds using code below and also remove previous alarms.

int interval =43200000;
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

Problem is am getting a notification or alarm is fired after every 2 mins i open the app

Answer Source

I would suggest to use this: manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pendingIntent); second parameter:

triggerAtMillis long: time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).


or better:

am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);

that is re-fired each time on broadcastreceiver is started and each startup (launch device) event .

43200000 is 12 hours;) do not forget Futhermore , use long type for each milliseconds variable: long interval = 43200000L; in order to prevent some bugs.