Android examples for android.app:AlarmManager
get Next Delay In Millis For Next Alarm
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main{ private static final String TAG = "AlarmUtil"; public static long getNextDelayInMillisForNextAlarm(Context context, int hour, int minute, String alarmDaysOfWeek) { ArrayList<Integer> dayOfWeekList = getDayOfWeekList(context, alarmDaysOfWeek);//from w w w .jav a 2s . c om Calendar nextAlarm = calculateNextTiming(hour, minute, dayOfWeekList); final int year = nextAlarm.get(Calendar.YEAR); final int month = nextAlarm.get(Calendar.MONTH); final int day = nextAlarm.get(Calendar.DAY_OF_MONTH); final int hour_r = nextAlarm.get(Calendar.HOUR_OF_DAY); final int minute_r = nextAlarm.get(Calendar.MINUTE); final int dayOfWeek_r = nextAlarm.get(Calendar.DAY_OF_WEEK); long nextDelayInMillis = nextAlarm.getTimeInMillis() - System.currentTimeMillis(); return nextDelayInMillis; } 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 { 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; } public static ArrayList<Integer> getDayOfWeekList(Context context, String weeks) { String[] weeklist = weeks.split(","); String[] displayList = context.getResources().getStringArray( R.array.array_day_of_weeks); HashMap<String, Integer> map = new HashMap<String, Integer>(); int value = Calendar.SUNDAY; for (int i = 0; i < displayList.length; i++) { map.put(displayList[i], value); value++; } ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < weeklist.length; i++) { if (map.containsKey(weeklist[i])) { list.add(map.get(weeklist[i])); } } return list; } }