警报管理器触发的待定意图似乎立即触发

编程入门 行业动态 更新时间:2024-10-23 19:20:20
本文介绍了警报管理器触发的待定意图似乎立即触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经设置了一个警报管理器,该警报管理器应该在一天中的某个特定时间触发待处理的意图.

I have set up an Alarm Manager that is supposed to trigger a Pending Intent at a certain time of day.

我将代码放在Main Activity的onCreate()方法中,因为我认为这是放置代码的最佳位置?

I placed the code in the onCreate() method of my Main Activity, as I believed this was the best place to put it?

下面是代码:

Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 4); // trigger at 4am in the morning calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); final Intent updateIntent = new Intent(Intent.ACTION_MAIN, null); updateIntent.addCategory(Intent.CATEGORY_HOME); final ComponentName cn = new ComponentName( "com.example.myotherapp", "com.example.myotherapp.MainActivity"); updateIntent.setComponent(cn); updateIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, updateIntent, 0); AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent); // launch at 4am, then every day (24 hours)

警报管理器"正常工作,我可以看到它在指定的时间触发,但是似乎该基本应用程序启动后,也会立即触发待处理的意图".

The Alarm Manager works, I can see it fire at the specified time, but it also seems that the Pending Intent is fired as soon as this base app starts.

什么原因导致Intent立即触发?而我该如何阻止它呢?

What is causing the Intent to fire right away? And how can I stop it from doing so?

推荐答案

您的问题在这里:

Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 4); // trigger at 4am in the morning calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0);

calendar.getTimeInMillis()将返回当前时间戳(System.currentTimeMillis())之前的时间戳,这就是Alarm立即触发的原因.

calendar.getTimeInMillis() will return the timestamp that BEFORE current timestamp (System.currentTimeMillis()) so that is why Alarm fire right away.

要解决您的问题,

long triggerTime = calendar.getTimeInMillis(); if (triggerTime <= System.currentTimeMillis() + 3000) { // 3 Second distance calendar.add(Calendar.DATE, 1); // Add 1 day --> Trigger 1 day later from now }

如果您始终想在1天后的凌晨4点开始闹钟.您可以删除条件并执行以下操作:

IF you always want to start your alarm at 4am 1 day later. You can remove condition and doing like this:

calendar.add(Calendar.DATE, 1); // Add 1 day --> Calendar time will be tomorrow 4am

AND

alarm.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent);

更多推荐

警报管理器触发的待定意图似乎立即触发

本文发布于:2023-11-27 03:37:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管理器   警报   意图   待定

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!