Android AlarmManager: how to find out the time rem

2019-07-17 04:04发布

问题:

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

For example, it is now 10:00 am, and set the AlarmManager to trigger the PendingIntent 23:00, and the calculations we know that the PendingIntent will be called here 13 hours. But how to find out this time remaining?

Sorry for my poor english. And I thank you for your attention

String schedule = "23:00"; //example

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); 
}

回答1:

You can calculate the difference between your alarm time (totalTime) and the current time like this:

long timeDiffInMillis = totalTime - System.currentTimeMillis();

This will give you the time remaining before your alarm will trigger (in milliseconds).