Android AlarmManager:如何找出触发PendingIntent的剩余时间 [英] Android AlarmManager: how to find out the time remaining to trigger the PendingIntent

查看:166
本文介绍了Android AlarmManager:如何找出触发PendingIntent的剩余时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个闹钟应用程序。下面我有一个设置闹钟的功能。但是我想知道如何找到AlarmManager触发PendingIntent的剩余时间。

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.

例如,现在是上午10:00,并将AlarmManager设置为触发PendingIntent 23:00,通过计算我们知道PendingIntent将在这里13小时被调用。但是如何找出这个剩余时间呢?

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


推荐答案

您可以计算出您的闹钟时间( totalTime )和当前时间是这样的:

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).

这篇关于Android AlarmManager:如何找出触发PendingIntent的剩余时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆