Android 应用程序和计时器

发布于 2024-07-26 05:51:10 字数 136 浏览 3 评论 0原文

你好,我有一个 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 技术交流群。

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

发布评论

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

评论(2

梦忆晨望 2024-08-02 05:51:10

也许您甚至不需要计时器。 只需通过存储 [System.currentTimeMillis()](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis() 在成员变量和 [stopSelf< /code>](http://developer.android.com每当您达到超时时, /reference/android/app/Service.html#stopSelf() 您的服务

例如,在您的服务的繁忙部分中包含以下内容:

if(System.currentTimeMillis() - TIMEOUT > startTime) {
    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:

if(System.currentTimeMillis() - TIMEOUT > startTime) {
    stopSelf();
}
默嘫て 2024-08-02 05:51:10

我会使用AlarmManager。 设置单响警报,使其在 20 分钟内响起。 在接收警报的独立 BroadcastReceiver 中,调用 stopService()

我有一篇博客文章和一些我的一本书中涵盖 AlarmManager 的示例代码,尽管它们都涵盖“cron 场景”,其中您想在启动时获得控制并设置重复警报。

I would use AlarmManager. Set up a single-shot alarm to go off in 20 minutes. In the standalone BroadcastReceiver that receives the alarm, call stopService().

I have a blog post and some sample code in one of my books that cover AlarmManager, though they are all covering "the cron scenario", where you want to get control at boot time and set up a repeating alarm.

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