Search code examples
javaandroidalarmmanager

AlarmManager at two specific times


i have two AlarmManager at 9:00 and 21:00, but only run the second alarm.

    ////////9:00am/////////
    Intent aviso = new Intent(FijarAlerta.this,Servicio.class);
    PendingIntent pi = PendingIntent.getService(FijarAlerta.this, 0, aviso, PendingIntent.FLAG_UPDATE_CURRENT);
           //set the hour
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 9);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pi);

The second alarm

////////21:00pm//////////
    Intent avisopm = new Intent(FijarAlerta.this,Servicio.class);
    PendingIntent pipm = PendingIntent.getService(FijarAlerta.this, 0, avisopm, PendingIntent.FLAG_UPDATE_CURRENT);
                 //set the hour
    Calendar calpm = Calendar.getInstance();
    calpm.set(Calendar.HOUR_OF_DAY, 21);
    calpm.set(Calendar.MINUTE, 0);
    calpm.set(Calendar.SECOND, 0);
    AlarmManager ampm = (AlarmManager)getSystemService(ALARM_SERVICE);
    ampm.setRepeating(AlarmManager.RTC_WAKEUP,calpm.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pipm);

Solution

  • The second parameter of your call to PendingIntent.getService() should be a different number in each case. For example:

    PendingIntent pi = PendingIntent.getService(FijarAlerta.this, 111, aviso,       PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pipm = PendingIntent.getService(FijarAlerta.this, 222, avisopm, PendingIntent.FLAG_UPDATE_CURRENT);
    

    At the moment the second pendingIntent just overwrites the first