当活动不在前面时暂停 Android 中的 CountDownTimer [英] Pause CountDownTimer in Android when activity is not in front

查看:18
本文介绍了当活动不在前面时暂停 Android 中的 CountDownTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动使用从 10 开始倒计时的 CountDownTimer.当活动不再处于焦点时,我如何暂停该计时器,例如用户接到电话或其他事情,然后在用户离开时恢复计时器回到活动?这甚至可能吗?

I have an activity that uses a CountDownTimer that counts down from 10. How do I pause that timer when the activity is no longer in focus, like if the user get a call or something, then resume the timer when the user goes back to the activity? Is this even possible?

推荐答案

我会向 onTick 处理程序添加一些内容,以保存类中计时器的进度(剩余毫秒数).

I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).

在活动调用的 onPause() 方法中对计时器调用 cancel().

In the onPause() method for the activity call cancel() on the timer.

在活动的 onResume() 方法中创建一个新的计时器,并保留剩余的毫秒数.

In the onResume() method for the activity create a new timer with the saved number of milliseconds left.

这篇关于当活动不在前面时暂停 Android 中的 CountDownTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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