我的闹钟管理器日历比较没有得到预期的结果



我在两个日历之间做了比较:年、月和日是当前的年、月和日:但如果第一个日历的时间在当前时间之后,则结果与预期不符,日历会等到该时间并开始响铃,但如果在当前时间之前,日历将直接开始响铃,因此它始终访问第二个条件:

public void scheduleAlarm()
{
//to initialize the time variable not a real value:
Long time=Long.parseLong("0");
 int hour=calendar.get(Calendar.HOUR);
 int minute=calendar.get(Calendar.MINUTE);
 Calendar cal_now = new GregorianCalendar(Year,Month,Day, hour, minute,Calendar.SECOND);
 Calendar cal_alarm_first=new GregorianCalendar(Year,Month,Day,21,14,0);

 //if the first calendar is in the past increment its day by one:
  if(cal_alarm_first.before(cal_now)){
  Notif_Body=getResources().getString(R.string.remembrance_body_first);     
  //here if the first alarm is already gone I should add a day and it should ring after a day from now with the specified hour and minute...           
  cal_alarm_first.add(Calendar.DATE, 1);                 
  time=cal_alarm_first.getTimeInMillis();
    }                                  

    else if(cal_alarm_first.after(cal_now)){
    //the problem is here it always access this condition even if the first calendar time is before the current time for example same date but the first calendar is 9:14 and current time is 9:17 it always access this condition and the alarm starts ringing...       
     Notif_Body=getResources().getString(R.string.remembrance_body_first);
     time=cal_alarm_first.getTimeInMillis();
       }

     //to send this alarm to be retrieved by the broadcast receiver class:
     Intent intentAlarm = new Intent(this, TimeAlarm.class);
     //add the notification body to the intent:
     intentAlarm.putExtra("Notif_body", Notif_Body);
     // create the object
     AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
     //set the alarm for particular time
     alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
                            }

我真的不知道问题是什么!! 谢谢。

编辑:所以这个意外结果的原因是因为 24 小时格式,我以 24 小时格式添加第一个日历的时间,并且当前时间将其时间设置为 12 小时格式,因此需要以 24 小时格式获取它们;

编辑2:所以我改变了

int hour=calendar.get(Calendar.HOUR);//12 hours

int hour=calendar.get(Calendar.HOUROFDAY);//24 hours
基本上有效,

如果它真的有效,会将其添加为答案......

这个

意外结果的原因是因为 24 小时格式,我以 24 小时格式添加第一个日历的时间,并且当前时间将其时间设置为 12 小时格式,因此需要以 24 小时格式获取它们;所以我改变了:

int hour=calendar.get(Calendar.HOUR);//12 hours

int hour=calendar.get(Calendar.HOUROFDAY);//24 hours

它奏效了!!

最新更新