calculate Next Timing - Android android.app

Android examples for android.app:AlarmManager

Description

calculate Next Timing

Demo Code

import java.util.ArrayList;
import java.util.Calendar;

public class Main {

  public static Calendar calculateNextTiming(int alarmHour, int alarmMinute, ArrayList<Integer> daysOfWeek) {

    Calendar now = Calendar.getInstance();
    now.setTimeInMillis(System.currentTimeMillis());

    Calendar base = Calendar.getInstance();
    base.setTimeInMillis(System.currentTimeMillis());
    base.set(Calendar.HOUR_OF_DAY, alarmHour);
    base.set(Calendar.MINUTE, alarmMinute);
    base.set(Calendar.SECOND, 0);
    base.set(Calendar.MILLISECOND, 0);

    if (null == daysOfWeek || 0 == daysOfWeek.size()) {
      if (base.after(now)) {
        return base;
      } else {/*from  w w  w . ja v  a 2s .  c  o m*/
        base.add(Calendar.DAY_OF_YEAR, 1);
        return base;
      }
    }

    Calendar c;
    for (Integer i : daysOfWeek) {
      c = Calendar.getInstance();
      c.setTime(base.getTime());
      c.set(Calendar.DAY_OF_WEEK, i.intValue());
      if (c.after(now)) {
        return c;
      }
    }
    c = Calendar.getInstance();
    c.setTime(base.getTime());
    c.add(Calendar.WEEK_OF_YEAR, 1);
    c.set(Calendar.DAY_OF_WEEK, daysOfWeek.get(0).intValue());
    return c;
  }

}

Related Tutorials