设备休眠时Timer Task暂停问题求助(已排除电池优化)
计时器应用锁屏休眠后TimerTask停止触发问题
我正在开发一款类似Focus To Do的计时器应用,用前台服务(Foreground Service)结合TimerTask实现核心计时功能。现在碰到个问题:设备锁屏休眠后,TimerTask就不再触发了;等设备亮屏,之前没执行的任务会一下子批量触发。
我的Timer间隔设的是100ms,但UI每1秒更新一次,而且应用已经被排除在电池优化之外了。
自定义CustomTimer类代码如下:
abstract class CustomTimer @JvmOverloads constructor( private val totalTime: Long, private val interval: Long, private val delay: Long = 0 ) : Timer("PreciseCountdownTimer", true) { private var task: TimerTask private var startTime: Long = -1 private var timeLeft: Long = 0 private var restart = false private var wasCancelled = false private var isDisposed = false private var wasStarted = false init { task = buildTask(totalTime) isDisposed = false } private fun buildTask(totalTime: Long): TimerTask { return object : TimerTask() { override fun run() { if (startTime < 0 || restart) { startTime = scheduledExecutionTime() timeLeft = totalTime restart = false } else { timeLeft = totalTime - (scheduledExecutionTime() - startTime) if (timeLeft <= 0) { this.cancel() wasCancelled = true startTime = -1 Log.d("shower", "run: ") onFinished() return } } onTick(timeLeft) } } } fun getTimeLeft() = timeLeft fun start() { wasStarted = true isDisposed = false this.scheduleAtFixedRate(task, delay, interval) } fun stop() { wasCancelled = true task.cancel() onStop() } fun restart() { if (!wasStarted) { start() } else if (wasCancelled) { wasCancelled = false task = buildTask(totalTime) start() } else { restart = true } } fun isDisposed() = isDisposed fun pause() { wasCancelled = true task.cancel() onPaused() } fun updateWithNewTime(time : Long){ task.cancel() task = buildTask(time) startTime = -1 start() } fun resume() { wasCancelled = false isDisposed = false task = buildTask(timeLeft) startTime = -1 start() onResumed() } // Call this when there's no further use for this timer fun dispose() { this.cancel() this.purge() isDisposed = true } abstract fun onTick(timeLeft: Long) abstract fun onFinished() abstract fun onPaused() abstract fun onResumed() abstract fun onStop() }
日志文件验证了这个问题:第3秒到第16秒期间没有任务触发,第16、17秒时任务快速批量触发(日志每1秒更新一次)。
内容的提问来源于stack exchange,提问作者shahram_javadi
相关产品推荐
相关产品推荐

