我试图让我的每日通知服务正常工作,但我遇到了问题。
我应该只在当天的某个特定时间收到通知,但我注意到了
if (time_that_i_set_for_notification < current_time_of_the_day) notification triggers at the boot of my app
这是错误的,因为在这种情况下,通知应该仅在第二天触发 ,而不是在我启动应用的瞬间。
我试图让事情发挥作用:
我在我的MainActivity,onCreate()方法中调用它:
private void scheduleNotification(int hour, int minute){
Intent notificationIntent = new Intent(this, NotificationReceiver.class);
notificationIntent.putExtra("notifId", notifId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, notifId, notificationIntent, 0);
// Set the alarm to start at approximately at a time
DatePicker datePicker = new DatePicker(this);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
if(calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 12);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
我认为添加if(calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.DAY_OF_MONTH, 1);
我会获得我需要的结果。
谢谢你,祝你有愉快的一天。
答案 0 :(得分:0)
在致电setInexactRepeating
之前,请添加此项检查:
if (calendar.getTimeInMillis() < System.currentTimeMillis())
calendar.setTimeInMillis(calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY);
希望这有帮助。
答案 1 :(得分:0)
好的,那里检查错了,如果你改了它,你应该能够解决你的问题。
我们走了:
Intent notificationIntent = new Intent(this, NotificationReceiver.class);
notificationIntent.putExtra("notifId", notifId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, notifId, notificationIntent, 0);
// Set the alarm to start at approximately at a time
DatePicker datePicker = new DatePicker(this);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
//if(calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 50);
if (calendar.getTimeInMillis() < System.currentTimeMillis()) calendar.setTimeInMillis(calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
我评论//if(calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.DAY_OF_MONTH, 1);
,因为它应该是不必要的。
让我知道它是否有效。
更新:您应该完全检查处理日常通知的服务是否消耗很高。高耗电电池应用会让您的用户感到烦恼。