Maedeh HM Maedeh HM - 3 days ago 5
Android Question

AlarmManager.setExact() does not work

I wrote an application which is able to set alarms based on some specif times. These specific times change day by day. For example, sunrise time changes every day. So, I defined a main activity which is responsible to call setExact() method every night at 11:55 p.m and then it has to set tomorrow's alarms based on the specific times for tomorrow. The issue is, it does not work! When I set the alarm, it just works for one time, and it is not going to be set for the second time. I really need help. Thank you :)

public class MainPage extends AppCompatActivity {

private Calendar calendar = new GregorianCalendar();

protected GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setMainAlarm();
}
private void setMainAlarm() {
AlarmManager alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(".mainAlarmReciever");
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Calendar alertCalendar = Calendar.getInstance();
alertCalendar.set(Calendar.HOUR,23);
alertCalendar.set(Calendar.MINUTE,54);
alertCalendar.set(Calendar.SECOND,59);

if (Build.VERSION.SDK_INT >= 23) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alertCalendar.getTimeInMillis(), alarmIntent);
}else{
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, alertCalendar.getTimeInMillis(), alarmIntent);
}

}


This is the related receiver class for that:

public class mainAlarmReciever extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmSetter.createOrUpdateAllAlarms(context);
this.completeWakefulIntent(intent);
}

Answer

The issue is you do not set the mainAlarm for tomorrow on your mainAlarmReciever.

Imagine that your mainAlarmReciever->onRecieve run at 11:54:59 P.M tonight. And it does whatever tasks you want to do. You should also set the mainAlarm for Tomorrow at 11:54:59 P.M in your onRecieve function.

Another option is using setRepeating (as CommonsWare mentioned it is not exact after API 19+).

Comments