I am running this code to set a Alarm Manager in my MainActivity on create method
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);
}
}
So this should set the alarm daily at 10:00 AM, The alarm is working fine until it's fired once. Once the alarm is done at 10:00 AM it keeps going off each time i open the app.
Can some please explain if i need to make any code changes?
EDIT :
I am using sharedPreferences to set the time of the Calendar Instance
Preferences:
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();
}
... and I set the Preferences in my app Settings using TimePicker Dialog
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
Preferences.setMorningHour(getApplicationContext(), hourOfDay);
Preferences.setMorningMinute(getApplicationContext(), minute);
}