Search code examples
javaandroidsqlitealarmmanageralarm

Set 3 different alarms android


I know that are many questions about this topic but none of them help me with what I'm trying to do, so I hope you can help me. I want to set 3 alarms that trigger at different hours of the day, let's suposse 9AM, 1PM, 6PM.The information about the hours is saved in a sqlite database.

I read row by row my database and set the alarm for each hour. For the id I'm using just a number.

This is the code that I'm using. It only works when I set one alarm, but if I try to set more, none of them is set.

private void setAlarm() throws ParseException {
      DBHelper helper = new DBHelper(Main3Activity.this);
      Cursor cursor = helper.getQueryDB();
      cursor.moveToPosition(-1);
      int i = 1;

      AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);

      while (cursor.moveToNext()) {
            final String name = cursor.getString(1);
            final String time = cursor.getString(2);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), i, intent, 0);

            Calendar t = parseTime(time);

            alarmManager.set(AlarmManager.RTC_WAKEUP, t.getTimeInMillis(), pendingIntent);


            i++;
      }
}
public Calendar parseTime (String t) throws ParseException {
       SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy");
       Calendar cal = Calendar.getInstance();
       cal.setTime(sdf.parse(t));
       return cal;
}

Solution

  • The code was fine, I forgot to put the receiver on the android manifest. My bad!