使用警报管理器启动服务

发布于 2024-10-18 11:39:33 字数 866 浏览 5 评论 0原文

我有一些代码想在每天凌晨 3:00 执行。我已经阅读了服务类文档,看来我可以使用AlarmManager 触发一个意图(我认为是活动还是服务?),然后在该意图中创建消息并在 Android 通知区域中发布消息。

Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );

它运行代码没有任何问题,但没有迹象表明警报已设置,并且活动未启动。我正在使用一项我知道有效的活动。我尝试将其包装在 try/catch 中,但 logcat 中没有任何内容...

I have some code I want to execute at 3:00am every day. I've read the Service Class Documentation and it seems I can use AlarmManager to fire an intent(Activity or Service, I think?), and then, in that intent create and post a message in the Android Notification area.

Calendar threeAM = Calendar.getInstance();
threeAM.set(Calendar.HOUR_OF_DAY,2);
threeAM.set(Calendar.MINUTE,0);
threeAM.set(Calendar.SECOND,0);
threeAM.set(Calendar.MILLISECOND,0);
AlarmManager alarmManager =
         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, myNotifier.class);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, threeAM.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, PendingIntent.getService(context, 1, i , 0));
Log.i("Service TEST", "Alarm set?" );

It runs through the code with no problems, but there is no indication that the alarm is set, and the activity doesn't start. I'm using an activity that I know works. I tried wrapping it in a try/catch, nothing in logcat...

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

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

发布评论

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

评论(2

醉态萌生 2024-10-25 11:39:33

我认为您应该注册您的活动以接收启动广播接收器,以便您的应用程序在操作系统启动完成时启动。这是链接 http://www.androidenea。 com/2009/09/starting-android-service-after-boot.html

它在通知方面没有帮助,但它会解决您的活动未启动的问题...

I think you should register your activity to receive boot broadcast receivers so that your application starts on the moment the OS boot up complete. here is the link http://www.androidenea.com/2009/09/starting-android-service-after-boot.html

It will not help in terms of notification but yes it will solve your problem of activity not starting...

茶色山野 2024-10-25 11:39:33

仅当您在凌晨 3 点之前执行您的代码时,它才会起作用。否则,你就会设置过去的闹钟。

Your code will only work if you execute it before 3am. Otherwise, you will be setting an alarm in the past.

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