Files
lpt-android/app/src/main/java/com/catshark/lpt/service/StudySessionService.kt
T
cat-shark d9d4f4e69e feat: 补齐会话冲突出口、预期必填与报告闭环,精简悬浮窗
- 会话冲突出口:开始新任务前查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口,避免同时存在两个进行中的会话
- 学习预期必填:未填预期时用不可关闭弹窗挡住,只能保存预期或走误操作结束
- 收敛提示:把服务端 systemMessage / autoConverged 原样告知用户
- 学习报告:结束会话时取 REPORT_DRAFT 草稿(AI 不可用由后端规则降级)作为编辑起点,可直接手写结束;任务页新增报告查看(三段 + 本会话碎片)
- 悬浮窗只保留三件事:展示倒计时、记一条碎片、暂停/继续;结束、报告、预期等一律回到 App 页面
- 修复前台服务在进程被系统拉起时把「还不知道」当成「没有会话」而自杀(以 State.resolved 为准)
2026-11-08 19:14:40 +08:00

245 lines
9.5 KiB
Kotlin

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))
}
}
}