简体   繁体   English

Android如何实现在应用程序关闭时不会停止的计时器

[英]Android how to implement timer that doesn't stop if app closes

I want app to start a timer at certain point and run for four hour and is displayed in UI. 我希望应用程序在某个时间点启动计时器并运行四个小时,并显示在UI中。 Now problem with using service is that it closes if app is closed. 现在使用服务的问题是,如果关闭了应用程序,它将关闭。 (Same with Handler) And if I use system time than if someone changes system time, 4 hours extends So is there a better way to implement such task? (与Handler相同)如果我使用系统时间比有人更改系统时间要花费4个小时,那么有没有更好的方法来实现这种任务?

You can make services not close when the activity (visible) is stopped. 当活动(可见)停止时,可以使服务不关闭。 One way to guarantee it stays alive is to make it a foreground service (will show a notification). 保证其存活的一种方法是使其成为前台服务(将显示通知)。 But if you don't make it a foreground service it will still last for some time unless your device is running out of battery for example. 但是,如果您不将其设置为前台服务,它将持续一段时间,除非您的设备电量耗尽。

In your case, to make it last four hours, perhaps use the foreground service alternative (showing a notification) 就您而言,要持续四个小时,也许可以使用前台服务替代方案(显示通知)

Foreground service Vogella foreground service 前台服务Vogella前台服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM