java - Android 警报管理器不适用于特定日期和时间
问题描述
所以我一直在开发药物摄入应用程序,我需要在本地提醒用户(不需要互联网/推送通知)服用他们的药物。我正在为此使用 Android 警报管理器。以下是代码注意我正在尝试将警报安排在特定日期:“2018 年 7 月 13 日下午 3 点 30 分”。我安排并等待,但提醒没有触发(所以没有广播)但是如果我使用具有定义的毫秒量的AlarmManager.ELAPSED_REALTIME_WAKEUP它会触发(但 AlarmManager.RTC_WAKEUP只是不起作用)`
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
long reminderDateTimeInMilliseconds = 000;
myIntent = new Intent(this,MedicationScheduleBroadCastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//TODO : Reminder the user to take medication on the 13th July 2018 at 15:30
Calendar calendarToSchedule = Calendar.getInstance();
calendarToSchedule.set(Calendar.YEAR, 2018);
calendarToSchedule.set(Calendar.MONTH, 07);
calendarToSchedule.set(Calendar.DAY_OF_MONTH, 13);
calendarToSchedule.set(Calendar.HOUR_OF_DAY, 15);
calendarToSchedule.set(Calendar.MINUTE, 30);
reminderDateTimeInMilliseconds = calendarToSchedule.getTimeInMillis();
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}
else{
manager.set(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}
`
解决方案
所以我发现了这个问题,主要问题是 Java 中的日历月实际上是基于 0 索引的所以(Jan:0 - Dec:11)所以下面是更新的代码。
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
long reminderDateTimeInMilliseconds = 000;
myIntent = new Intent(this,MedicationScheduleBroadCastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//TODO : Reminder the user to take medication on the 13th July 2018 at 15:30
// Note: For the month of July the int value will actuall be 6 instead of 7
Calendar calendarToSchedule = Calendar.getInstance();
calendarToSchedule.setTimeInMillis(System.currentTimeMillis());
calendarToSchedule.clear();
//.Set(Year, Month, Day, Hour, Minutes, Seconds);
calendarToSchedule.set(2018, 06, 13, 15, 30, 0);
reminderDateTimeInMilliseconds = calendarToSchedule.getTimeInMillis();
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}
else{
manager.set(AlarmManager.RTC_WAKEUP, reminderDateTimeInMilliseconds, pendingIntent);
}
推荐阅读
- css - 我可以将 CSS 选择器作为道具传递给外部组件中的样式类吗?
- java - 如何在读取 .txt 文件 java 时包含空格和其他字符
- asp.net-mvc-5 - 当前上下文中不存在名称“配置”
- html - 仅当它包含特定类时如何更改css中的特定标签
- html - 如何使用 sendmail 在 HTML 中显示嵌入的图像?
- python - 如何映射或排序两个不同数据框的值?
- java - heapsort 的一部分发生了变化并且不起作用
- reactjs - 将 getStaticProps 与 next-redux-wrapper 一起使用
- asp.net - 如何修复 robots.txt 文件错误
- reactjs - 如何找到状态索引并做拼接数据的过程