如果当天的闹钟时间已过,android会阻止立即触发闹钟服务 [英] android prevent immediate trigger of alarm service if alarm time has passed for the day

查看:28
本文介绍了如果当天的闹钟时间已过,android会阻止立即触发闹钟服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警报管理器的参考说

如果规定的触发时间在过去,则会触发警报立即.

If the stated trigger time is in the past, the alarm will be triggered immediately.

我在我的应用程序中遇到了这个问题.这是我的警报管理器代码:

I am facing this problem in my application. Here is my alarm manager code :

Intent myIntent = new Intent(getActivity(), DinnerAlarmReceiver.class);
                pendingDinnerIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);

                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingDinnerIntent);

是否有解决此问题的方法?

Is there any workaround to this problem?

-----编辑------

我写了一些代码来估计闹钟的设置时间是否在当前时间之前.这是上面有相应变化的部分:

I have written some code to estimate if the set time for the alarm is before the current time . Here is the above portion with corresponding changes :

Calendar calendar = Calendar.getInstance();
                long currentTime = calendar.getTimeInMillis();
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                long setTime = calendar.getTimeInMillis();
                Timestamp setTimestamp = new Timestamp(setTime);
                Timestamp currentTimestamp = new Timestamp(currentTime);
                if (setTimestamp.after(currentTimestamp))
                {
                    alarmManager.set(AlarmManager.RTC_WAKEUP,
                            calendar.getTimeInMillis(), pendingDinnerIntent);
                }
                else
                {
                }

如果 setTimestampcurrentTimestamp 之前,我应该如何使用 alarmManager ?

What should I the alarmManager to in case setTimestamp is before currentTimestamp ?

推荐答案

您不需要创建 Timestamps.你可以用你的 Calendar 做到这一点.

You don't need to create Timestamps. You can do it with your Calendar.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);

if(calendar.before(Calendar.getInstance())) {
    calendar.add(Calendar.DATE, 1);
}

alarmManager.set(AlarmManager.RTC_WAKEUP,
    calendar.getTimeInMillis(), pendingDinnerIntent);

我还要提一下,从 KitKat 开始,如果您的 targetSdkVersion 是 19 或更高版本,则 AlarmManager#set() 方法不准确.如果您希望闹钟在准确的时间触发,则需要使用 setExact*() 方法.

I would also mention that as of KitKat, if your targetSdkVersion is 19 or above, the AlarmManager#set() method is not exact. If you want your alarm to fire at an exact time, you'll need to use a setExact*() method.

这篇关于如果当天的闹钟时间已过,android会阻止立即触发闹钟服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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