How to know the remaining time for the alarm to ring

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 AlarmManager to trigger PendingIntent.

For example, it is now 11:00 hours, and we set the AlarmManager to trigger PendingIntent 23:00 h, and by calculations, we know that PendingIntent will be called in 12 hours. But how to find out this remaining time?

Since now I thank you 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); 
}
Author: ramaral, 2014-06-24

2 answers

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

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

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

There are others, but everything but the Java native Date, since on Android there are some problems that you should still encounter (if you have not already found).

In joda-time, Just Do It:

Hours.hoursBetween(LocalDateTime.now(), new LocalDateTime("hora do alarme no formato YYYY-MM-dd HH:mm:ss"));
 1
Author: CĂ­cero Moura, 2014-06-28 02:03:00

One way to have 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 you set the alarm.

 0
Author: Felipe Bonezi, 2015-02-01 14:40:24