Android:即使设备被锁定也保持线程运行
我正在为 Android 制作一个闹钟应用程序。一旦用户安排了闹钟,线程就会计数,直到达到闹钟,然后就会发出闹钟声音。
但是,当设备锁定时(我的意思是屏幕在半分钟后关闭时),计数线程会停止,如果再次解锁,计数线程会从离开的地方继续 - 即使是在几个小时后。
这就是一个非常奇怪的闹钟应用程序。我研究过 AlarmManager,但它似乎不适合我的情况,因为我只希望在我的应用程序仍在运行时发生警报。退出应用程序应该会停止它。 AlarmManager 的文档是这样说的:
注意:警报管理器的目的是 对于您想要拥有自己的 应用程序代码运行在特定的 时间,即使您的申请没有 当前正在运行。对于正常计时 操作(刻度、超时等) 更容易、更高效 使用处理程序。
它提到的“Handler”类似乎旨在实现与我想要实现的目标完全不同的目标。
所以我问你:即使设备被锁定,我怎样才能让我的线程保持活动状态并计数?或者还有别的办法吗?
I'm making an alarm app for android. Once the user scheduled an alarm, a thread will count until the alarm is reached and then there will be an alarm sound.
However, the counting thread stops when the device is locked (I mean when the screen turns off after half a minute) and continue from where it left if it is unlocked again - even if that is hours later.
That makes for a pretty weird alarm app. I've looked into AlarmManager, but it seems like it's not appropriate in my case, since I only want the alarm to happen if my app is still running. Quitting the app should stop it. Here's what AlarmManager's documentation says though:
Note: The Alarm Manager is intended
for cases where you want to have your
application code run at a specific
time, even if your application is not
currently running. For normal timing
operations (ticks, timeouts, etc) it
is easier and much more efficient to
use Handler.
The "Handler" class it mentions seems to be intended for something entirely different from what I'm trying to achieve.
So I'm asking you: How can I keep my thread alive and counting even if the device is locked? Or is there another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不必不这样做。不要留一根线来引起警报。使用 AlarmManager
另外,您的应用程序没有“运行”与否的概念。你的意思是只有当它可见时?只需在 onPause() 中清除闹钟即可。
You need not not doing this. Don't keep a thread around for an alarm. Use the AlarmManager
Also there's no concept of your app "running" or not. Do you mean only when it's visible? Just clear your alarm in onPause().
为什么使用而不使用通知?您可以设置声音、振动、灯光以及在状态栏中显示图标。如果您想取消通知,请使用NotificationManager。
http://developer.android.com/guide/topics/ui /notifiers/notifications.html#CreateANotification
吉尔特
Why using not using Notifications? You can set sound, vibrating, lights and a showing an icon in the status bar. If you want to cancel the Notification use the NotificationManager.
http://developer.android.com/guide/topics/ui/notifiers/notifications.html#CreateANotification
Geert