简体   繁体   中英

How to properly implement timers in Android?

I am trying to make a simple app that tracks work time. MainActivity features a TextView representing a timer and four buttons, for starting, pausing, resuming and stopping.

So far I have two classes for modelling the timer, TimerCountdown and TimerCountup (for overtime) that initiate timers using android.os.CountDownTimer; , update the TextView and trigger a system notification to notify the user once they have finished. TimerCountdown updates tView every second and after 8 hours it will send a notification to the user and initiate TimerCountup to track overtime for another 2 hours.

What is the correct way to ensure those timers keep running if the application is in the background? Do I have to wrap the two Timer classes into a Service? If so, how would I do this, since they are holding references to the context, which is apparently not allowed? Unfortunately the documentation for android.os.CountDownTimer; does not mention how it behaves when the applications enters the background. In order to restore progress once the application is destroyed I will probably use a serialized object eventually, I am just not sure how to properly handle background activity.

Also, what would be the best way to ensure the notification (such as a vibration) gets triggered after the timer reaches 0? The app will probably be either in background by then, or destroyed.

如果我理解你正确你想要一个可以在后台工作的计时器,那么你应该扩展服务类。有一个类似于你的答案问题。你可以在后台查看Android倒数计时器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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