AlarmManager 未设置,每次打开活动时都会发出警报

发布于 2024-12-02 02:19:03 字数 601 浏览 2 评论 0原文

我正在尝试用它来设置每天都会响的闹钟。

String alarm = Context.ALARM_SERVICE;
                Calendar calendar = Calendar.getInstance();
                AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);

                    Intent intent = new Intent("NEW_ITEM");
                    PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
                     calendar.setTimeInMillis(System.currentTimeMillis());
                     am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1*AlarmManager.INTERVAL_DAY, sender);

I am trying to use this to set an alarm that goes off everyday.

String alarm = Context.ALARM_SERVICE;
                Calendar calendar = Calendar.getInstance();
                AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);

                    Intent intent = new Intent("NEW_ITEM");
                    PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
                     calendar.setTimeInMillis(System.currentTimeMillis());
                     am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1*AlarmManager.INTERVAL_DAY, sender);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱的故事 2024-12-09 02:19:03

如果不运行它,代码对我来说看起来不错...显然,如果您每次启动活动时都设置此闹钟,则闹钟将立即响起,因为: am.setRepeating(AlarmManager.RTC_WAKEUP, **calendar. getTimeInMillis()**, 1*AlarmManager.INTERVAL_DAY, sender); 告诉警报管理器立即发出警报(第二个参数)并在一天内重复(第三个参数,假设你的常数是正确的)。

如果您希望警报仅在 24 小时内启动,只需将该行更改为:

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, sender);

Without running it, the code looks good to me... Obviously, if you set this alarm every time you start the activity, the alarm will go off immediately since: am.setRepeating(AlarmManager.RTC_WAKEUP, **calendar.getTimeInMillis()**, 1*AlarmManager.INTERVAL_DAY, sender); Tells the alarm manager to alert right now (2nd param) and to repeat in a day (3rd param, assuming your constant is correct).

If you want the alert to start only in 24 hours, simply change the line to:

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, sender);
北陌 2024-12-09 02:19:03

代码看起来不错,但您必须注意一件事。如果用户决定再次设置闹钟(例如,通过点击“设置闹钟”按钮),旧的闹钟将被替换。如果您想避免这种情况,请查看此主题:使用 Alarmmanager在特定时间启动服务

Code looks good, but you have to be aware of one thing. If the user decides to set the alarm again (for example, by hitting the 'set the alarm' button) the old one will be replaced. If you want to avoid this, check out this topic: Using Alarmmanager to start a service at specific time

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文