使用AlarmManager设置多个闹钟,一切正常但没有闹钟
我正在尝试根据用户输入的分钟列表设置一堆警报。如果他们在下午 4:00 按下开始时钟按钮并设置了 5 分钟、10 分钟和 15 分钟的闹钟,那么我需要设置 4:05、4:10 和 4:15 的闹钟。我认为代码是正确的,Toast 会为列表中的每个项目向我发送一条“设置闹钟”消息,但我的手机上没有响起闹钟:
setAlarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] spAlarms = allAlarms.split(";");
for(int i = 0; i < spAlarms.length; i++) {
try {
if(!spAlarms.equals("")) {
int time = Integer.valueOf(spAlarms[i]);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, time);
Intent intent = new Intent(Hop_Timer.this, Alarm_Receiver.class);
intent.putExtra("alarm_message", "Time for your " + spAlarms[i] + " min addition!");
PendingIntent sender = PendingIntent.getBroadcast(Hop_Timer.this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
Toast.makeText(getApplicationContext(), "Set alarm", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
I'm trying to set a bunch of alarms based on a list of minutes entered by the user. If they hit the start clock button at 4:00pm and had 5 min, 10 min and 15 min alarms set then I need alarms set for 4:05, 4:10 and 4:15. The code I have seeeems right and the Toast sends me a "Set alarm" message for each item I have in the list, but no alarms are going off on my phone:
setAlarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] spAlarms = allAlarms.split(";");
for(int i = 0; i < spAlarms.length; i++) {
try {
if(!spAlarms.equals("")) {
int time = Integer.valueOf(spAlarms[i]);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, time);
Intent intent = new Intent(Hop_Timer.this, Alarm_Receiver.class);
intent.putExtra("alarm_message", "Time for your " + spAlarms[i] + " min addition!");
PendingIntent sender = PendingIntent.getBroadcast(Hop_Timer.this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
Toast.makeText(getApplicationContext(), "Set alarm", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,你不能在 OnClickListener 中执行此操作,但更好的解决方案是在
OnResume()
中执行此操作,并且 Ekta Parikh 是正确的,你必须使用
cal.set(Calender .MINUTE, 时间);
确实能够设置闹钟As far as I know you can't do this in OnClickListener, but a better solution is to do this in
OnResume()
and Ekta Parikh is right that you must use
cal.set(Calender.MINUTE, time);
do be able to set the alarm使用 cal.set(Calendar.MINUTE, time);而不是添加方法。
Use cal.set(Calendar.MINUTE, time); instead of add method.