我已经阅读了很多关于如何设置闹钟的教程。对于我的项目,我遵循Google提供的代码(下载样本按钮@ https://developer.android.com/training/scheduling/alarms.html),但每次设置时都会触发警报。 这是代码。
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to fire at approximately 6:00 p.m., according to the device's
// clock, and to repeat mon, wed, fri.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Set the alarm's trigger time to 2:49 p.m.
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 49);
calendar.set(Calendar.SECOND, 00);
calendar.set(Calendar.MILLISECOND, 00);
int day = 2;
while(day < 7){
//2 - monday, 4 - wednesday, 6 friday
calendar.set(Calendar.DAY_OF_WEEK,day);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
day += 2;
}
编辑1: 昨天我注意到这个警报在分钟49,例如14:49,15:59,16:49等每小时都在激活(除了我每次设置它)
答案 0 :(得分:0)
确定,
在与这个人挣扎之后,我不得不做一些黑客攻击:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
所有警报都将被视为不准确的警报,这会导致警报在一段随机时间后触发(不是您,程序员决定的)。然而这对我来说并不是什么大不了的事,因为在我设定它之后它会在20分钟后发射。
...所以,我只设置了一个(1)闹钟:
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
每天都会在接近我cal.set(...)
所设置的随机时间发出警报,但在我WakefulBroadcastReceiver.onRecieve(...)
上我检查今天是星期一,星期三还是星期五:
@Override
public void onReceive(Context context, Intent intent) {
//Check if it should do stuff
Calendar now = Calendar.getInstance();
now.setTimeInMillis(System.currentTimeMillis());
int day = now.get(Calendar.DAY_OF_WEEK);
if(day == Calendar.MONDAY || day == Calendar.WEDNESDAY || day == Calendar.FRIDAY){
//Do things!
}
else{
//Do nothing
}
}
有一个好的!