package com.catshark.lpt.service import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.os.Build import android.os.IBinder import android.provider.Settings import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import com.catshark.lpt.MainActivity import com.catshark.lpt.R import com.catshark.lpt.session.SessionController import com.catshark.lpt.util.formatDuration import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch /** * 学习会话前台服务:持有悬浮窗与常驻通知,会话结束自动停止。 * 悬浮窗只做「显示 + 控制」,不承载文本输入,因此不会抢焦点。 */ class StudySessionService : Service() { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private lateinit var overlay: OverlayView private lateinit var controller: SessionController override fun onCreate() { super.onCreate() val container = (application as com.catshark.lpt.LptApp).container controller = container.session overlay = OverlayView(this).apply { onTogglePause = { togglePause() } onRequestFragmentInput = { openFragmentInput() } } createChannel() // 状态变化:更新通知 / 悬浮窗。 // 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时 // 对账是异步的,早期看到的空状态是「还不知道」,不能据此 stopSelf。 scope.launch { controller.state.collect { state -> if (!state.hasSession) { overlay.hide() if (state.resolved) stopSelf() return@collect } ensureForeground(state) if (Settings.canDrawOverlays(this@StudySessionService)) { overlay.show() } overlay.render(state) } } // 每秒刷新悬浮窗与通知上的计时 scope.launch { while (isActive) { delay(1000) val state = controller.state.value if (state.hasSession) { // 权限可能是服务启动后才被授予的,这里持续兜底 if (!overlay.isShown && Settings.canDrawOverlays(this@StudySessionService)) { overlay.show() } overlay.render(state) notify(buildNotification(state)) } } } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { ACTION_PAUSE -> controller.pause() ACTION_RESUME -> controller.resume() ACTION_END -> openApp(openEnd = true) ACTION_SHOW_OVERLAY -> overlay.restore() ACTION_STOP -> stopSelf() } // 进程被系统拉起(intent 为 null)时补一次对账,否则重启后浮窗不会再出现 controller.ensureReconciled() // 必须在 5 秒内 startForeground,先用当前状态占位 ensureForeground(controller.state.value) return START_STICKY } override fun onDestroy() { overlay.hide() scope.coroutineContext[kotlinx.coroutines.Job]?.cancel() super.onDestroy() } override fun onBind(intent: Intent?): IBinder? = null private fun togglePause() { if (controller.state.value.status == SessionController.Status.ONGOING) { controller.pause() } else { controller.resume() } } private fun openApp(openEnd: Boolean) { val intent = Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) if (openEnd) putExtra(MainActivity.EXTRA_OPEN_END, true) } startActivity(intent) } /** 从浮窗拉起碎片输入弹窗(后台弹 Activity 靠 SYSTEM_ALERT_WINDOW 豁免) */ private fun openFragmentInput() { // 独立 task:保存后回到用户原本在用的 App,而不是跳到 LPT 主界面 val intent = Intent(this, com.catshark.lpt.ui.FragmentInputActivity::class.java) .addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS or Intent.FLAG_ACTIVITY_NO_ANIMATION, ) runCatching { startActivity(intent) } } private fun ensureForeground(state: SessionController.State) { val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE } else { 0 } val notification = if (state.hasSession) buildNotification(state) else buildIdleNotification() runCatching { ServiceCompat.startForeground(this, NOTIFICATION_ID, notification, type) } } private fun notify(notification: Notification) { val manager = getSystemService(NotificationManager::class.java) manager.notify(NOTIFICATION_ID, notification) } private fun buildNotification(state: SessionController.State): Notification { val ongoing = state.status == SessionController.Status.ONGOING val toggleLabel = if (ongoing) "暂停" else "继续" val toggleAction = if (ongoing) ACTION_PAUSE else ACTION_RESUME val contentIntent = PendingIntent.getActivity( this, 0, Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) return NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(state.taskName ?: "学习会话") .setContentText("${if (ongoing) "进行中" else "已暂停"} · 有效 ${formatDuration(state.effectiveSeconds())}") .setContentIntent(contentIntent) .setOngoing(true) .setOnlyAlertOnce(true) .setPriority(NotificationCompat.PRIORITY_LOW) .addAction(0, toggleLabel, servicePendingIntent(toggleAction, 1)) .addAction(0, "结束", activityPendingIntent(2)) .build() } private fun buildIdleNotification(): Notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("学习会话") .setContentText("正在恢复会话状态…") .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_LOW) .build() private fun servicePendingIntent(action: String, requestCode: Int): PendingIntent = PendingIntent.getService( this, requestCode, Intent(this, StudySessionService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) private fun activityPendingIntent(requestCode: Int): PendingIntent = PendingIntent.getActivity( this, requestCode, Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) putExtra(MainActivity.EXTRA_OPEN_END, true) }, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) private fun createChannel() { val manager = getSystemService(NotificationManager::class.java) if (manager.getNotificationChannel(CHANNEL_ID) != null) return val channel = NotificationChannel( CHANNEL_ID, "学习会话", NotificationManager.IMPORTANCE_LOW, ).apply { description = "显示正在进行的 LPT 学习会话与计时" setShowBadge(false) } manager.createNotificationChannel(channel) } companion object { const val CHANNEL_ID = "study_session" const val NOTIFICATION_ID = 1001 const val ACTION_PAUSE = "com.catshark.lpt.action.PAUSE" const val ACTION_RESUME = "com.catshark.lpt.action.RESUME" const val ACTION_END = "com.catshark.lpt.action.END" const val ACTION_STOP = "com.catshark.lpt.action.STOP" const val ACTION_SHOW_OVERLAY = "com.catshark.lpt.action.SHOW_OVERLAY" fun start(context: Context) { val intent = Intent(context, StudySessionService::class.java) androidx.core.content.ContextCompat.startForegroundService(context, intent) } /** 从 App 里恢复被半隐藏/被系统收起的浮窗 */ fun showOverlay(context: Context) { val intent = Intent(context, StudySessionService::class.java).setAction(ACTION_SHOW_OVERLAY) runCatching { androidx.core.content.ContextCompat.startForegroundService(context, intent) } } fun stop(context: Context) { context.stopService(Intent(context, StudySessionService::class.java)) } } }