立即触发警报并立即调用广播接收器方法

alarm trigger immediately and broadcast receiver methods get called immediately

警报第一次根据我们设置的时间立即触发,但无论我们设置什么时间它都会立即触发

报警代码

 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);

    });

    

点击按钮时将调用以下代码

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.

下方接收者祝酒词立即显示

接收码

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    Globals.showToast(context, "Alarm Time");

}

}

我假设这是问题所在:

mCalendar.set(Calendar.MONTH, --mMonth);

这将在第一次起作用,但下一次 mMonth 的值将比应有的值少 1,因为您已经减小了 mMonth 的值。在这种情况下,触发时间已经过去,导致警报立即触发。

试试这个:

mCalendar.set(Calendar.MONTH, mMonth - 1);