如何确保服务在每天上午 9 点开始并在晚上 9 点停止? [英] How can I ensure a service is started at 9am and stopped 9pm every day?

查看:39
本文介绍了如何确保服务在每天上午 9 点开始并在晚上 9 点停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,可以每天监控位置变化.到目前为止我所知道的是在启动时启动服务,我必须遵循链接的教程.这样我就可以在启动时启动服务,但为了节省电池电量,我只需要在上午 9 点到晚上 9 点之间使用.

I have a service that will monitor location changes daily. What I know so far that to start a service at boot, I have to follow the linked tutorial. This way I can get the service started at boot, but to save battery I need it only between 9am-9pm.

问题很简单,所以我再重复一遍:

Question is pretty simple, so I will repeat:

如何确保服务在每天上午 9 点开始并在晚上 9 点停止?

How can I ensure a service is started at 9am and stopped 9pm every day?

推荐答案

使用 AlarmManager 设置两个闹钟,每个闹钟都有一个 PendingIntent 会调用 startService() 在您的服务上,但具有不同的操作字符串(开始"、停止").当您的服务的 onStart() 检测到停止"操作 Intent 时,它会安排有序关闭(例如,stopSelf()).

Use AlarmManager to set two alarms, each with a PendingIntent that will call startService() on your service, but with distinct action strings ('start', 'stop'). When onStart() of your service detects the 'stop' action Intent, it arranges for an orderly shutdown (e.g., stopSelf()).

如果用户在 Android 2.1 或更早版本中为您应用任务管理器,这将失败,因为他们倾向于使用的技术会消除您的警报(除了终止服务).在这种情况下,用户可能会投票支持您的服务不运行,因此您应该尽量满足用户的意愿.

This will fail if the user applies a task manager to you in Android 2.1 or earlier, since the technique they tend to use will wipe out your alarms (in addition to killing the service). In that case, the user is presumably voting for your service to not run, so you should try to accommodate the user's wishes.

这篇关于如何确保服务在每天上午 9 点开始并在晚上 9 点停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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