alarm trigger immediately first time working according to time we set but then whatever the time we set it trigger immediately
alarm code
mCalendar = Calendar.getInstance();
mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
mMinute = mCalendar.get(Calendar.MINUTE);
mYear = mCalendar.get(Calendar.YEAR);
mMonth = mCalendar.get(Calendar.MONTH) + 1;
mDay = mCalendar.get(Calendar.DATE);
timePicker.setOnTimeChangedListener((view, hourOfDay, minute) -> {
mHour = hourOfDay;
mMinute = minute;
//Globals.showToast(getActivity(), hourOfDay + ":" + minute);
});
below code will be called on a button click
int rcode = new Random().nextInt();
alarmManager = (AlarmManager) Objects.requireNonNull(getActivity()).getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(
this.getActivity(), rcode, intent, PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA);
mCalendar.set(Calendar.MONTH, --mMonth);
mCalendar.set(Calendar.YEAR, mYear);
mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
mCalendar.set(Calendar.MINUTE, mMinute);
mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mCalendar.set(Calendar.SECOND, 0);
/* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyy hh:mm:a", Locale.ENGLISH);
Globals.showToast(getActivity(), simpleDateFormat.format(mCalendar.getTimeInMillis()));*/
// Calculate notification time
Calendar c = Calendar.getInstance();
long currentTime = c.getTimeInMillis();
long diffTime = mCalendar.getTimeInMillis() - currentTime;
// Start alarm using notification time
alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime,
pendingIntent);
using above code i m setting alarm but it works perfect only for first time alarm setting. then after using whatever i m setting alarm it triggers immediately.
below receiver toast show immediately
receiver code
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Globals.showToast(context, "Alarm Time");
}
}
I'm assuming this is the problem:
mCalendar.set(Calendar.MONTH, --mMonth);
This will work the first time, but the next time the value of mMonth
will be 1 less than it should be, because you have decreased the value of mMonth
. In this case, the trigger time will have already passed, causing the alarm to trigger immediately.
Try this instead:
mCalendar.set(Calendar.MONTH, mMonth - 1);