Android 应用程序和计时器
你好,我有一个 Android 应用程序,它正在运行一个服务。 该服务和其他系统(例如 GPS
)启动 20 分钟后,我希望它自动停止。 我想我需要为此使用计时器吗?
有人可以举例说明我该如何做到这一点吗?
Hello I have an android application which has a service running. After 20 mins from that service and other systems (such as GPS
) starting I would like it to automaticly stop. I assume I need to use a Timer for that?
Can someone show an example of how I could do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您甚至不需要计时器。 只需通过存储 [
System.currentTimeMillis()
](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis() 在成员变量和 [stopSelf< /code>](http://developer.android.com每当您达到超时时, /reference/android/app/Service.html#stopSelf() 您的服务
例如,在您的服务的繁忙部分中包含以下内容:
Maybe you don't even need a timer for that. Just keep track of when your service was started by storing [
System.currentTimeMillis()
](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis() in a member variable and [stopSelf
](http://developer.android.com/reference/android/app/Service.html#stopSelf() your Service whenever you reach the timeout.For example, include the following in your Service's busy part:
我会使用
AlarmManager
。 设置单响警报,使其在 20 分钟内响起。 在接收警报的独立BroadcastReceiver
中,调用stopService()
。我有一篇博客文章和一些我的一本书中涵盖
AlarmManager
的示例代码,尽管它们都涵盖“cron
场景”,其中您想在启动时获得控制并设置重复警报。I would use
AlarmManager
. Set up a single-shot alarm to go off in 20 minutes. In the standaloneBroadcastReceiver
that receives the alarm, callstopService()
.I have a blog post and some sample code in one of my books that cover
AlarmManager
, though they are all covering "thecron
scenario", where you want to get control at boot time and set up a repeating alarm.