开发者

Android: Keep a thread running even if the device is locked

开发者 https://www.devze.com 2023-02-05 11:56 出处:网络
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.

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 le开发者_开发知识库ft 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?


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().


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号