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

时间:2013-10-11 18:39:14

标签: android android-alarms android-calendar

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

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小时格式获取它们;

EDIT2: 所以我改变了

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

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

并且基本上工作将添加它作为答案,如果它确实有效......

1 个答案:

答案 0 :(得分:0)

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

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

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

它有效!!

相关问题