Search code examples
androidalarmmanagerandroid-alarms

Android Alarms too early


I'm using android studio to develop an application that would retrieve the time information from the database and would set an alarm to prompt the user that it's time to drink the medicine, my problem is that the alarm goes on too early

for example the retrieved time is 12:50 AM and the current time is 12:40 AM even though there's a 10 minutes difference the alarm goes off right away

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
         Calendar Cnow = Calendar.getInstance();
         long now=Cnow.getTimeInMillis();
         Calendar time=Calendar.getInstance();
         time.setTimeInMillis(0);
         Date dTime=sdf.parse(strAlarmDate + " " + strTime1);
//example strAlarmDate="2015-09-27" and strTime1="12:50 AM" and now="12:40 AM" in millis
//dTime="...... 2015-09-27 00:50"
         time.setTime(dTime);
         //Date dNow=now.getTime();
         //time.setTime(date);
         //long trigger=time.getTimeInMillis()-now.getTimeInMillis();
         long trigger=time.getTimeInMillis()-now;
         if(trigger>0) {
             ctr++;
             Intent i = new Intent(Login.this, AlarmReceiver.class);
             i.putExtra("message", strMedname);
             i.putExtra("line", strLine);
             final int _id = (int) System.currentTimeMillis();
             PendingIntent pi = PendingIntent.getActivity(Login.this, _id, i, 0);
             AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//           am.set(AlarmManager.RTC_WAKEUP, trigger, pi);
//           am.setExact(AlarmManager.RTC_WAKEUP, trigger, pi);
             am.set(AlarmManager.RTC_WAKEUP, trigger, pi);
         }
     }catch(ParseException ex)
     {
          ex.printStackTrace();
     }

Solution

  • The problem is that you set the alarm to go off at time trigger which is the time minus the current time.

    You should pass time.getTimeInMillis() instead.

    So replace the line with

    am.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
         }