我這段代碼運行在我的MainActivity設置報警管理器上創建方法AlarmManager會關閉每次我打開
public void notificationCheck() {
calendar.set(Calendar.HOUR_OF_DAY, Preferences.getMorningHour(getApplicationContext()));
calendar.set(Calendar.MINUTE, Preferences.getMorningMinute(getApplicationContext()));
calendar.set(Calendar.SECOND, 0);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), 0);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setAndAllowWhileIdle(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
因此它應該在10:00 AM每天設置鬧鐘應用程序,該警報工作正常,直到它被解僱一次。一旦警報在上午10點完成,每次打開應用程序時它都會繼續。
有些人可以解釋一下,如果我需要做任何代碼更改?
編輯:
我使用sharedPreferences設置Calendar的實例
首時間:
public static int getMorningHour(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(MORNING_HOUR, 9);
}
public static void setMorningHour(Context context, Integer morningHour) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(MORNING_HOUR, morningHour).apply();
}
public static int getMorningMinute(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(MORNING_MINUTE, 0);
}
public static void setMorningMinute(Context context, Integer morningMinute) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(MORNING_MINUTE, morningMinute).apply();
}
...我使用TimePicker對話框中設置的首選項在我的應用程序設置
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
Preferences.setMorningHour(getApplicationContext(), hourOfDay);
Preferences.setMorningMinute(getApplicationContext(), minute);
}
請參閱下面的鏈接。它爲我工作。 [重複報警](http://stackoverflow.com/a/40311030/3782085) –
代碼是相同的,我每天重複一次報警。我要求在活動 –
開始時AlarmManager出現故障,您是否嘗試過使用廣播接收器? – Radhey