即使在应用程序关闭时也运行时钟或计时器 - Android [英] Run a clock or timer even when app closes - Android

查看:86
本文介绍了即使在应用程序关闭时也运行时钟或计时器 - Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

玩过《糖果粉碎传奇》吗?知道你如何耗尽生命并且必须等待 30 分钟才能再生新生命,最多 5 分钟吗?这是我正在尝试在我的应用程序中实现的想法,但我不确定如何让代码运行,即使用户关闭应用程序和/或电话.

Ever played Candy Crush? Know how you run out of lives and have to wait 30 minutes to regenerate a new life and up to a maximum of 5? That is idea I am trying to implement in my app but I am uncertain on how to have code running even when the user closes app and/or phone.

我的问题是如何让计时器在手机后台不断运行,直到计时器达到 X 分钟.我会为此使用 Timer 类吗?因为我熟悉那个类,并且已经在我的应用中实现了它的一种形式.

My question is how to have a timer constantly running in the background of phone until the timer hits X minutes. Would I use the Timer class for this? Because I am familiar with that class and already have a form of it implemented in my app.

推荐答案

如果您希望计时器在后台运行,您可以使用 AlarmManager.您可以在指定的时间间隔设置警报,或者如果您想要单次警报,也可以将其设置为服务.此外,在使用 AlarmManager 时请注意,如果您的手机出现故障,那么您设置的所有警报都将消失.因此,请注意在电话响起之前保存闹钟时间.看一看:

If you want timer to run in background you may use AlarmManager. You can set Alarm at specified intervals or you can set it in service if you want single shot alarms. Also while using AlarmManager beware that if your phone goes down then all alarms you've set will be vanished. So take care that you are saving alarm times before phone goes off. Take a look at:

http://developer.android.com/reference/android/app/报警管理器.html

在使用 AlarmManager 时,请使用正确的 PendingIntent 标志,否则您可能会丢失以前的警报.如果您还想了解更多信息,可以在这里提出或使用谷歌搜索.

While using AlarmManager, use correct PendingIntent flags or you could lose previous alarms. If you still want more information you can raise here or have a google.

这篇关于即使在应用程序关闭时也运行时钟或计时器 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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