设置多个警报/通知错误/错误?
我正在尝试制作一个应用程序,允许用户为每个任务设置任务和警报或通知。我在下面创建了一个“setAlarm”方法。但是,我有一个错误,每当我设置带有警报的多个任务时,不知何故,所有先前的任务都会被取消,并且只有最近设置的警报才会响起。你知道问题出在哪里吗?我的猜测是,每次我调用“setAlarm”时,“日历”实例都会重置。我该如何解决这个问题?
public void setAlarm() {
Intent intent1 = new Intent(NewGoal.this, SingleAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(NewGoal.this,
0, intent1, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (alarm_time == 10) {
calendar.add(Calendar.SECOND, alarm_time);
} else if (alarm_time == 30 {
calendar.add(Calendar.SECOND, alarm_time)
}
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Log.i(TEST, "In setAlarm method");
Log.i(TEST, "calendar=" + calendar.MILLISECOND);
}
I'm trying to make an app that allows the user to set tasks and alarms or notifications for each task. I have created a 'setAlarm' method below. However, I have an error that whenever I set multiple tasks with alarms, somehow all the previous ones get cancelled and only the most recently set alarm will go off. Do you know whats the problem? My guess is that the 'calendar' instance gets reset every time I call 'setAlarm'. How could I get around this?
public void setAlarm() {
Intent intent1 = new Intent(NewGoal.this, SingleAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(NewGoal.this,
0, intent1, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (alarm_time == 10) {
calendar.add(Calendar.SECOND, alarm_time);
} else if (alarm_time == 30 {
calendar.add(Calendar.SECOND, alarm_time)
}
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Log.i(TEST, "In setAlarm method");
Log.i(TEST, "calendar=" + calendar.MILLISECOND);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 文档:
From the documentation:
可能是因为您正在使用毫秒粒度,而在 Java 中这些不能保证准确。以下内容来自 JavaDoc。也许你应该使用 System.nanoTime() ,但这仅从 Java 5 开始可用。请阅读以下线程: System.currentTimeMillis 与 System.nanoTime
另外,您的代码中的以下语句是多余的
May be because you are working with milli second granularity and in Java these is not guaranteed to be accurate. Below is from the JavaDoc. May be you should use System.nanoTime() but this is available only since Java 5. Read this thread on SO: System.currentTimeMillis vs System.nanoTime
Also, the below statement from your code is redundant
@dave.c 谢谢,我也在文档中找到了这一点。这是我解决这个问题的方法。
如果有多个同名意图,则最新的意图会取消前一个意图。为了解决这个问题,请使用当前时间来使每个意图不同。
谢谢你们。
@dave.c Thanks, I found this in the documentation too. Here is how I got around it.
If there is more than one intent with the same name, the most recent one cancels the previous one. To get around this, use the current time to make each intent different.
Thanks guys.