Files
FocusBox/src/main/java/com/focusbox/app/service/TimerService.kt
XIGE d52deeff5e 导入 v0.1.0 / v0.2.0 源码:五模块首版、交互重构、重复任务、任务分布
- 源码镜像 src/main(81 个文件):首页双模式、任务、项目、统计、设置
- 补齐 README / LICENSE / CHANGELOG / CONTRIBUTING / .gitignore
- 不含构建配置、签名材料、编译产物与备份数据
2026-11-28 00:25:22 +08:00

153 lines
5.0 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.focusbox.app.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import androidx.core.content.ContextCompat
/**
* 计时前台服务。
*
* 之所以必须用前台服务而不是页面里的 Handler:息屏后 Activity 会被暂停、
* 进程随时可能被回收,只有带常驻通知的前台服务能稳定维持计时与到时提醒。
*
* 真正的计时逻辑在 [TimerCore],这里只做三件事:撑住进程、每秒推进、刷新通知。
*/
class TimerService : Service() {
companion object {
const val ACTION_SYNC = "com.focusbox.app.SYNC"
const val ACTION_PAUSE = "com.focusbox.app.PAUSE"
const val ACTION_RESUME = "com.focusbox.app.RESUME"
const val ACTION_STOP = "com.focusbox.app.STOP"
fun ensureRunning(context: Context) {
val intent = Intent(context, TimerService::class.java).setAction(ACTION_SYNC)
runCatching { ContextCompat.startForegroundService(context, intent) }
}
fun refresh(context: Context) {
Notif.updateOngoing(context)
}
fun stop(context: Context) {
runCatching { context.stopService(Intent(context, TimerService::class.java)) }
Notif.cancelOngoing(context)
}
}
private val handler = Handler(Looper.getMainLooper())
private var wakeLock: PowerManager.WakeLock? = null
private val ticker = object : Runnable {
override fun run() {
// 只推进状态,不再每秒重发通知:通知里的时间是系统的 Chronometer 在走,
// 每秒 notify 反而会让锁屏上的计时被系统限流后"冻住"。
TimerCore.tick()
handler.postDelayed(this, 1000L)
}
}
override fun onCreate() {
super.onCreate()
TimerCore.addListener(onStateChanged)
}
private val onStateChanged: () -> Unit = {
Notif.updateOngoing(this)
syncWakeLock()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_PAUSE -> {
TimerCore.pause()
stopTicker()
}
ACTION_RESUME -> {
TimerCore.resume()
syncTicker()
}
ACTION_STOP -> {
TimerCore.stopEarly()
stopTicker()
stopSelf()
return START_NOT_STICKY
}
else -> Unit
}
// 必须在启动后立即进入前台,否则 5 秒内会被系统判定为 ANR 级违规
startForegroundCompat()
syncTicker()
syncWakeLock()
Notif.updateOngoing(this)
return START_NOT_STICKY
}
/**
* 只有倒计时需要每秒推进(判断是否到点)。
* 正计时靠时间戳现算、通知靠系统 Chronometer 走时,
* 既不用轮询也不用占着 WakeLock,长时间正计时不会白耗电。
*/
private fun syncTicker() {
if (TimerCore.running && !TimerCore.countUp) startTicker() else stopTicker()
}
private fun startForegroundCompat() {
val notification = Notif.buildOngoing(this)
runCatching {
// 两参版本会读清单里声明的前台服务类型(dataSync)。
// 不用三参 + SPECIAL_USE:该类型 Android 14 才引入,
// 在 P30 的 Android 12 上传进去会直接抛 IllegalArgumentException。
startForeground(Notif.ID_ONGOING, notification)
}.onFailure {
// 前台服务被系统拒绝(省电策略/权限)时退化为普通服务,
// 计时本身仍在 TimerCore 里走,只是通知可能不显示。
stopSelf()
}
}
private fun startTicker() {
handler.removeCallbacks(ticker)
handler.postDelayed(ticker, 1000L)
}
private fun stopTicker() {
handler.removeCallbacks(ticker)
}
private fun syncWakeLock() {
if (TimerCore.running && !TimerCore.countUp) {
if (wakeLock?.isHeld != true) {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FocusBox:timer").apply {
setReferenceCounted(false)
// 超时兜底:正常路径会主动释放,这里防止异常退出后一直亮着 CPU
acquire(4 * 60 * 60 * 1000L)
}
}
} else {
releaseWakeLock()
}
}
private fun releaseWakeLock() {
runCatching { if (wakeLock?.isHeld == true) wakeLock?.release() }
wakeLock = null
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
stopTicker()
releaseWakeLock()
TimerCore.removeListener(onStateChanged)
super.onDestroy()
}
}