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) // 暂停/结束时同步停掉 1 秒轮询,别让 Handler 空转 syncTicker() 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 -> { // 休息是纯计时:通知上的"结束"也走 endBreak,不产生任何记录 if (TimerCore.mode == TimerCore.MODE_FOCUS) TimerCore.stopEarly() else TimerCore.endBreak() 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) // 必须显式传类型:specialUse 是 Android 14 才引入的, // Android 12/13 不认识清单里的这个类型位,两参版本(读清单)会被拒绝, // 服务起不来 → 每秒 tick 停掉 → 息屏后到点无人结算,通知滚成负数。 // <34 用 dataSync(Android 12 原生支持,行为与历史版本一致); // >=34 用 specialUse 规避 dataSync 的 24 小时 6 小时累计上限。 val type = if (android.os.Build.VERSION.SDK_INT >= 34) { android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE } else { android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC } runCatching { startForeground(Notif.ID_ONGOING, notification, type) }.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() } }