Search code examples
javadatealarmmanagerandroid-alarms

Putting an expiry on an alarm


So I have alarms set in a database which my application takes from, however I want to be able to put an expiry date on these alarms (there for medication). How would I do this?

Here is my code for the alarms:

private void calMeds(int medication1, String time1) {

    String string = time1; 
    String[] parts = string.split(":");
    String part1 = parts[0]; 
    String part2 = parts[1]; 
    Log.e("DATABASE", "Hours: " + part1);
    Log.e("DATABASE", "Minutes: " + part2);

    hourCorrect = Integer.parseInt(part1);
    minuteCorrect = Integer.parseInt(part2);

    Date date = new Date();
    Calendar cal_Alarm = Calendar.getInstance();
    Calendar cal_Now = Calendar.getInstance();
    cal_Now.setTime(date);

    cal_Alarm.setTime(date);
    cal_Alarm.set(Calendar.HOUR_OF_DAY, hourCorrect);
    cal_Alarm.set(Calendar.MINUTE, minuteCorrect);
    cal_Alarm.set(Calendar.SECOND, 3);

    if (cal_Alarm.before(cal_Now)) { 
        cal_Alarm.add(Calendar.DATE, 1);

    }

    alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    String ALARM_ACTION;

If I have an alarm going off everyday at 9:00 and its expiry date is the 21st of March, how do I stop it from alarming after this date? The times are entered in a database, and each have a different expiry date.


Solution

  • Based on your revision:

    Calendar now = Calendar.getInstance();
        Calendar then = Calendar.getInstance();
        then.set(Calendar.MONTH, month);
        then.set(Calendar.DAY_OF_MONTH, day);
        then.set(Calendar.HOUR, hour);
        then.set(Calendar.MINUTE, minute);
    
        long dif = then.getTimeInMillis() - now.getTimeInMillis();
    
        ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(!alarm.isStopped())
                alarm.stop();
        }
        };
    
        Timer timer = new Timer((int)dif, action);
        timer.start();