我試圖讓我的每日通知服務正常工作,但我遇到了問題。在應用程序啓動時觸發Android通知
我應該只在當天在未來特定時間收到通知,但我注意到,
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);
我已經取得的成果我需要。
謝謝你,祝你有美好的一天。
完美!我解決了這個問題!非常好的答案謝謝! – Claff