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

查看:103
本文介绍了如果一天中的警报时间已过,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
                {
                }

什么如果 setTimestamp currentTimestamp 之前,我应该使用 alarmManager 吗? ?

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

推荐答案

您不需要创建时间戳。您可以使用日历

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天全站免登陆