当我在每周不起作用的情况下设置警报时,我已经有很多联系,但没有一个是成功的。这里是我的代码。
public void forday(int week, int hour, int minuts, int position, int formate) {
Calendar calSet = Calendar.getInstance();
Calendar now=Calendar.getInstance();
calSet.set(Calendar.DAY_OF_WEEK,week);
calSet.set(Calendar.HOUR_OF_DAY, hour);
calSet.set(Calendar.MINUTE, minuts);
calSet.set(Calendar.AM_PM, formate);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND,0);
if (calSet.before(Calendar.getInstance())){
calSet.add(Calendar.DAY_OF_MONTH,7);
}
alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
int pos = position + week + 1028;
intent.putExtra("extra", "yes");
pendingIntent = PendingIntent.getBroadcast(context, pos, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
}
答案 0 :(得分:1)
替换代码行
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
使用
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), calSet.getTimeInMillis(), pendingIntent);
还有一种简单的方法可以使用AlarmManager.INTERVAL_DAY
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
下面添加了一些工作代码,以用于测试目的,在当前时间后2分钟设置警报。
Calendar next = Calendar.getInstance();
Calendar now = Calendar.getInstance();
int nowWeek = now.get(Calendar.DAY_OF_WEEK);
int nowMinute = now.get(Calendar.MINUTE);
int nowDay = now.get(Calendar.HOUR_OF_DAY);
int nowFormat = now.get(Calendar.AM_PM);
next.set(Calendar.DAY_OF_WEEK, nowWeek);
next.set(Calendar.HOUR_OF_DAY, nowDay);
next.set(Calendar.MINUTE, nowMinute + 2);
next.set(Calendar.AM_PM, nowFormat);
next.set(Calendar.SECOND, 0);
if (now.after(next)) {
// Added a day
next.add(Calendar.DATE, 1);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, next.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);