1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| public static Calendar cacluteNextAlarm(int hour, int minute, int dayOfweek){ Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(System.currentTimeMillis()); mCalendar.set(Calendar.HOUR_OF_DAY,hour); mCalendar.set(Calendar.MINUTE, minute); int differDays = getNextAlarmDifferDays(dayOfweek,mCalendar.get(Calendar.DAY_OF_WEEK), mCalendar.getTimeInMillis()); int nextYear = getNextAlarmYear(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.DAY_OF_YEAR), mCalendar.getActualMaximum(Calendar.DAY_OF_YEAR), differDays); int nextMonth = getNextAlarmMonth(mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), mCalendar.getActualMaximum(Calendar.DATE), differDays); int nextDay = getNextAlarmDay(mCalendar.get(Calendar.DAY_OF_MONTH), mCalendar.getActualMaximum(Calendar.DATE), differDays); mCalendar.set(Calendar.YEAR,nextYear); mCalendar.set(Calendar.MONTH, nextMonth % 12);//月份从0开始 mCalendar.set(Calendar.DAY_OF_MONTH, nextDay); mCalendar.set(Calendar.SECOND, 0); mCalendar.set(Calendar.MILLISECOND, 0); return mCalendar; }
//获取下次闹钟相差的天数 private static int getNextAlarmDifferDays(int data, int currentDayOfWeek,long timeInMills){ int nextDayOfWeek = getNextDayOfWeek(data, currentDayOfWeek,timeInMills); return currentDayOfWeek<=nextDayOfWeek?(nextDayOfWeek-currentDayOfWeek):(7 - currentDayOfWeek + nextDayOfWeek); }
//考虑年进位的情况 private static int getNextAlarmYear(int year,int dayOfYears, int actualMaximum, int differDays) { int temp = actualMaximum-dayOfYears-differDays; return temp >= 0?year:year+1; }
//考虑月进位的情况 private static int getNextAlarmMonth(int month,int dayOfMonth,int actualMaximum, int differDays) { int temp = actualMaximum-dayOfMonth-differDays; return temp >= 0?month:month+1; }
//获取下次闹钟的day private static int getNextAlarmDay(int thisDayOfMonth, int actualMaximum, int differDays) { int temp = actualMaximum - thisDayOfMonth-differDays; if (temp<0){ return thisDayOfMonth + differDays - actualMaximum; } return thisDayOfMonth + differDays; }
//获取下次显示是星期几 private static int getNextDayOfWeek(int data, int cWeek,long timeInMillis) { int tempBack = data >> cWeek - 1; int tempFront = data ;
if(tempBack%2==1){ if(System.currentTimeMillis()<timeInMillis) return cWeek; } tempBack = tempBack>>1; int m=1,n=0; while (tempBack != 0) { if (tempBack % 2 == 1 ) return cWeek + m; tempBack = tempBack / 2; m++; } while(n<cWeek){ if (tempFront % 2 == 1) return n+1; tempFront =tempFront/2; n++; } return 0; }
|