我想制作一个应用程序,这会让我想起每天同一时间的活动。对于这个purpouse我使用AlarmManager。
这是我注册活动的方式:
Intent alarmIntent = new Intent(getApplicationContext(), ReminderAlarm.class);
alarmIntent.putExtra("id_bundle", cursor.getInt(0));
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), cursor.getInt(0), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
这是我取消注册活动的方式:
Intent alarmIntent = new Intent(getApplicationContext(), ReminderAlarm.class);
alarmIntent.putExtra("id_bundle", id);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
这是我编辑活动的方式:
Intent alarmIntent = new Intent(getApplicationContext(), ReminderAlarm.class);
alarmIntent.putExtra("id_bundle", id);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
Intent alarmIntentNew = new Intent(getApplicationContext(), ReminderAlarm.class);
alarmIntentNew.putExtra("id_bundle", id);
PendingIntent pendingIntentNew = PendingIntent.getActivity(getApplicationContext(), id, alarmIntentNew, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntentNew);
我尝试使用setRepeating,间隔为24 * 3600 * 1000,但这似乎不起作用,所以我决定在触发并重新注册时取消注册该事件。我在ReminderAlarm活动中执行此操作,该活动在警报触发后启动。
此外,每当我启动应用程序时,我都会使用我发布的代码块再次注册所有事件来注册事件。我从数据库中提取有关哪些事件和注册时间的数据。
我的问题是,这个doesent工作。当我将事件添加到时间T + 1分钟时,它会正确触发。但第二天,它就会出现。
可能是因为我给日历实例提供了错误的数据吗?我有一个很长的函数,它在事件触发后和我将此日历实例发送到AlarmManager实例之前设置日历实例。在这个函数中,我为新月,新年等事情做了准备,并设置了日历字段(年,月,日_月,小时_天,分钟)。这甚至是必要的吗? calendar.getTimeInMillis()会考虑所有这些字段还是只考虑hour_of_day和minute?你看到可能出错了吗?谢谢!
答案 0 :(得分:1)
为什么不这样做才能得到时间。
Calendar cal = Calendar.getInstance();
int now = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, 1);
int tomorrow = cal.getTimeInMillis();
我认为压延机可能正在做什么。
PS。我是在上一篇文章中提出警报的人:P看起来你做得很好。
那个有用的代码:
//Create a calendar.
Calendar cal = Calendar.getInstance();
//Get the time in miilis since Jan 1st 1970 I think?
cal.getTimeInMillis();
//Set the calendar
cal.set(year, month, day, hour, minute, second);
//set a certain aspect of the calendar
cal.set(Calendar.<What you want to set>, <amount>);
//for example
cal.set(Calendar.DAY_OF_MONTH, 1);
//Add to the calendar, Calendar.DAY_OF_MONTH what ever you are using specifies the amount of milliseconds to add, for example a day is 100*60*60*24 milliseconds where a second is 1000 milliseconds.
cal.add(Calendar.<Day or month or what ever>, <amount>);
//for example
cal.add(Calendar.MONTH, 1);
//Take of the calendar
cal.add(Calendar.MONTH, -1);
//Get that value
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
希望你喜欢:)