我正在创建一个使用TimePicker的应用程序,用户可以设置他们希望将SMS发送到指定号码的时间。他们还可以选择单击“重复”,以便每天在同一指定时间继续发送SMS。
我的问题是它在我设置计时器而不是等待之后立即关闭。我试图多次混淆间隔,但从逻辑上讲它似乎应该按原样工作,但事实并非如此。
以下是从时间选择器和设置AlarmManger获取时间的代码:
Button setSchedule = (Button) setTimer.findViewById(R.id.setSchedule);
setSchedule.setText("Set");
setSchedule.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
hours = timePicker.getCurrentHour();
minutes = timePicker.getCurrentMinute();
minutesConv += hours * 60;
minutes += minutesConv;
seconds = minutes * 60;
time = seconds * 1000;
long currentTime = System.currentTimeMillis();
CheckBox repeat = (CheckBox) setTimer.findViewById(R.id.repeat);
Intent intentAlarm = new Intent(MainMenu.this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MainMenu.this, 0, intentAlarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (repeat.isChecked())
{
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time - currentTime, AlarmManager.INTERVAL_DAY, pi);
}//end if
else
{
alarmManager.set(AlarmManager.RTC_WAKEUP, time - currentTime, PendingIntent.getBroadcast(MainMenu.this, 1, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT));
}//end else
Toast.makeText(MainMenu.this, "Your message has been scheduled to be repeated at " +
hours + ":" + minutes, Toast.LENGTH_SHORT).show();
setTimer.dismiss();
}//end onClick
});
编辑:
Calendar cal = Calendar.getInstance();
Calendar current = Calendar.getInstance();
cal.set(0, 0, 0, timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 00);
Toast.makeText(MainMenu.this, "time: " + cal.getTimeInMillis(), Toast.LENGTH_SHORT).show();
CheckBox repeat = (CheckBox) setTimer.findViewById(R.id.repeat);
Intent intentAlarm = new Intent(MainMenu.this, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MainMenu.this, 0, intentAlarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (repeat.isChecked())
{
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
}//end if
else
{
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), PendingIntent.getBroadcast(MainMenu.this, 1, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT));
}//end else
答案 0 :(得分:1)
如果我正确读取documentation,则triggerAtMillis
参数是绝对值,而不是相对时间。传递time + currentTime
代替time - currentTime
应该没问题。
答案 1 :(得分:1)
因此,问题与正确设置警报有关。实质上,警报管理器设置为您希望触发警报时的绝对时间(以毫秒为单位)。您有几个选项来计算它。
尝试使用此日历设置单个闹钟:
hours = timePicker.getCurrentHour();
minutes = timePicker.getCurrentMinute();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, hours);
cal.set(Calendar.MINUTE, minutes);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), PendingIntent.getBroadcast(MainMenu.this, 1, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT));
setTimeInMillis()将日历对象更新为当前日期(这一年,所有其他内容都正确设置)。然后,将日历设置为同一天的未来时间并将其传递给警报管理器。