How to know the remaining time for the alarm to ring

1

I'm developing an alarm clock. Below I have a function to set the alarm. But I want to know how to find the remaining time for the AlarmManager to trigger the PendingIntent.

For example, it is now 11:00 AM, and we set AlarmManager to trigger PendingIntent at 11:00 PM, and by the calculations, we know PendingIntent will be called in 12 hours. But how to discover this remaining time?

Thanks in advance for your attention

String schedule = "23:00"; //exemplo
Calendar cal = Calendar.getInstance();
cal.set(cal.HOUR_OF_DAY, getTime(schedule));
cal.set(cal.MINUTE, getMinute(schedule));
cal.set(cal.SECOND, 0);
cal.set(cal.MILLISECOND, 0);

DateFormat dfH = new SimpleDateFormat("HH");
DateFormat dfM = new SimpleDateFormat("mm");
int currentTime = Integer.parseInt(dfH.format(new Date()));
int currentMinute = Integer.parseInt(dfM.format(new Date()));

Intent i = new Intent(context, RecebAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context.getApplicationContext(), id, i, 0);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long totalTime = cal.getTimeInMillis();

if (currentTime > getTime(schedule) || (currentTime == getTime(schedule) && currentMinute >= getMinute(schedule))) {
    alarms.set(AlarmManager.RTC_WAKEUP, totalTime + AlarmManager.INTERVAL_DAY, pi);
} else {
    alarms.set(AlarmManager.RTC_WAKEUP, totalTime, pi); 
}
    
asked by anonymous 24.06.2014 / 16:26

2 answers

1

Well, in the simplest case of all, you can save the time set for the wake-up alarm in a file of preferences.

So, you having this time, just subtract it from the current time to find out the time remaining.

One tip I give you is to work with the library joda-time

There are others, but everything but the native Date of Java, because in Android there are some problems that you must still find (if you have not already found it).

In joda-time, just do this:

Hours.hoursBetween(LocalDateTime.now(), new LocalDateTime("hora do alarme no formato YYYY-MM-dd HH:mm:ss"));
    
28.06.2014 / 04:03
0

One way to get a function that returns the hour, minute and second is as follows:

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * (60 * 1000)) % 60;

String toLeave;
if (diffHours > 0) {
    toLeave = String.format("%dh %dm %ds", diffHours, diffMinutes, diffSeconds);
} else if (diffMinutes > 0) {
    toLeave = String.format("%dm %ds", diffMinutes, diffSeconds);
} else if (diffSeconds > 0) {
    toLeave = String.format("%ds", diffSeconds);
} else {
    return;
}

Where diff is the difference, in milliseconds, between the current time and the time that you set the alarm.

    
01.02.2015 / 15:40