feat: 浮窗改侧边把手,补到点提醒与深色面板

This commit is contained in:
2026-11-23 20:43:59 +08:00
parent 1eb351b0dd
commit 289706d1fc
5 changed files with 401 additions and 242 deletions
@@ -0,0 +1,9 @@
package com.catshark.lpt.service
import com.catshark.lpt.session.SessionController
/** 纯判定:暂停、无倒计时、已提醒的同一分段均不重复触发。 */
internal fun countdownAlertKey(state: SessionController.State, nowMs: Long, lastAlertKey: String?): String? {
if (state.status != SessionController.Status.ONGOING || state.remainingMs(nowMs) != 0L) return null
return state.countdownKey?.takeUnless { it == lastAlertKey }
}
@@ -3,336 +3,370 @@ package com.catshark.lpt.service
import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.content.res.ColorStateList
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import com.catshark.lpt.session.SessionController
import com.catshark.lpt.util.formatDuration
import com.catshark.lpt.util.formatCountdown
import kotlin.math.abs
/**
* 系统级悬浮窗(经典 View 实现)。
*
* 职责被刻意压到最小——浮窗只做三件事:
* 1. 展示倒计时;
* 2. 记一条知识碎片(拉起 FragmentInputActivity,浮窗内不做文本输入);
* 3. 暂停 / 继续计时。
*
* 其余动作(改预期、结束会话、写报告、看历史)一律在 App 页面内完成,不要往浮窗里加。
*
* 两种形态:
* - 常态条:`● 12:34 + 暂停`,FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
*
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
*
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
* 所以「+」回调给 Service,由它拉起 FragmentInputActivity。
*/
/** 经典 View 浮窗:贴边计时胶囊 + 展开面板,仅提供记碎片与暂停/继续。 */
class OverlayView(private val context: Context) {
private val wm = context.getSystemService(WindowManager::class.java)
private val preferences = context.getSharedPreferences("study_overlay", Context.MODE_PRIVATE)
private var root: LinearLayout? = null
private var params: WindowManager.LayoutParams? = null
private var shown = false
private var halfHidden = false
private var compact = true
private var dockRight = preferences.getBoolean("dock_right", true)
private var verticalFraction = preferences.getFloat("vertical_fraction", 0.25f)
private var dragging = false
private var lastState: SessionController.State? = null
private lateinit var barRow: LinearLayout
private lateinit var dotView: View
private lateinit var panel: LinearLayout
private lateinit var capsule: LinearLayout
private lateinit var statusView: TextView
private lateinit var timeView: TextView
private lateinit var compactTime: TextView
private lateinit var compactDot: View
private lateinit var fragmentView: TextView
private lateinit var toggleView: TextView
private lateinit var compactRow: LinearLayout
private lateinit var compactDot: View
private lateinit var compactTime: TextView
var onTogglePause: (() -> Unit)? = null
var onRequestFragmentInput: (() -> Unit)? = null
val isShown: Boolean get() = root != null
val isShown: Boolean get() = shown
private val autoHideTask = Runnable {
if (shown && !halfHidden) setHalfHidden(true)
}
private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
private val collapseTask = Runnable { if (!dragging) setCompact(true) }
private fun dp(value: Int) = (value * context.resources.displayMetrics.density).toInt()
private fun background(color: Int, radius: Int, border: Boolean = false) = GradientDrawable().apply {
setColor(color)
cornerRadius = dp(radiusDp).toFloat()
}
private fun pill(label: String, bg: Int, textColor: Int = Color.WHITE): TextView = TextView(context).apply {
text = label
textSize = 13f
setTextColor(textColor)
gravity = Gravity.CENTER
background = rounded(bg, 10)
setPadding(dp(12), dp(6), dp(12), dp(6))
isClickable = true
isFocusable = false
cornerRadius = dp(radius).toFloat()
if (border) setStroke(dp(1), BORDER)
}
fun show() {
if (shown) return
if (!Settings.canDrawOverlays(context)) return
if (isShown || !Settings.canDrawOverlays(context)) return
compact = true
val view = buildRoot()
val p = createParams()
val layout = WindowManager.LayoutParams(
dp(COMPACT_WIDTH), WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT,
).apply {
gravity = Gravity.TOP or Gravity.LEFT
// 坐标使用完整屏幕,边界与系统栏由 screenBounds 统一处理。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) setFitInsetsTypes(0)
title = "LPT 学习悬浮窗"
}
root = view
params = p
runCatching { wm.addView(view, p) }.onFailure {
params = layout
applyMode()
position(view, layout)
try {
wm.addView(view, layout)
} catch (_: RuntimeException) {
root = null
params = null
return
}
shown = true
scheduleAutoHide()
}
/** 彻底移除(仅在会话结束/服务停止时调用) */
fun hide() {
if (!shown) return
cancelAutoHide()
root?.let { runCatching { wm.removeView(it) } }
val view = root ?: return
view.removeCallbacks(collapseTask)
view.animate().cancel()
runCatching { wm.removeView(view) }
root = null
params = null
shown = false
dragging = false
}
/** 恢复/重建浮窗(App 内「显示悬浮窗」入口) */
fun restore() {
if (!shown) {
show()
return
}
if (halfHidden) setHalfHidden(false)
scheduleAutoHide()
setCompact(false)
}
fun render(state: SessionController.State) {
lastState = state
if (!shown) return
if (!isShown) return
val ongoing = state.status == SessionController.Status.ONGOING
val text = formatDuration(state.effectiveSeconds())
timeView.text = text
compactTime.text = text
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
compactDot.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
val remaining = state.remainingMs()
val due = remaining == 0L
val accent = if (due || !ongoing) AMBER else MINT
val duration = formatCountdown(remaining)
timeView.text = duration
compactTime.text = if (dockRight) "‹" else "›"
compactTime.setTextColor(accent)
compactDot.background = background(accent, 4)
statusView.text = when {
state.writing -> "正在同步…"
state.syncError != null -> "同步失败 · 请打开 App"
due -> "时间到 · 请注意休息"
remaining == null -> "倒计时待同步"
ongoing -> "本轮剩余时间"
else -> "倒计时已暂停"
}
statusView.setTextColor(accent)
toggleView.text = if (ongoing) "暂停" else "继续"
toggleView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
barRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
compactRow.visibility = if (halfHidden) View.VISIBLE else View.GONE
toggleView.contentDescription = if (ongoing) "暂停学习" else "继续学习"
toggleView.isEnabled = !state.writing && state.hasSession
fragmentView.isEnabled = !state.writing && state.hasSession
toggleView.alpha = if (toggleView.isEnabled) 1f else 0.45f
fragmentView.alpha = if (fragmentView.isEnabled) 1f else 0.45f
capsule.contentDescription = "${if (due) "时间到" else if (ongoing) "学习倒计时" else "已暂停"},$duration,侧边收纳,点按展开,拖动调整位置"
}
// ---- 半隐藏 / 自动隐藏 ----
fun setHalfHidden(hidden: Boolean) {
/** 横竖屏、屏幕尺寸变化后仍保持贴边,按相对高度重新定位。 */
fun reposition() {
val view = root ?: return
val p = params ?: return
halfHidden = hidden
// 常态整条 80% 不透明;收起后再压一档,整体约 60%
view.alpha = if (hidden) 0.75f else 1f
lastState?.let { render(it) }
val screenWidth = context.resources.displayMetrics.widthPixels
// 等布局完成拿到新宽度后再贴边
view.post {
val width = view.width.takeIf { it > 0 } ?: dp(220)
if (hidden) {
val toRight = (p.x + width / 2) > screenWidth / 2
// 收向最近的屏幕边缘,只留约七成在屏幕内
p.x = if (toRight) screenWidth - (width * 0.7).toInt() else -(width * 0.3).toInt()
} else {
p.x = (screenWidth - width - dp(12)).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(0))
scheduleAutoHide()
}
runCatching { wm.updateViewLayout(view, p) }
}
val layout = params ?: return
position(view, layout)
updateLayout()
}
private fun scheduleAutoHide() {
root?.removeCallbacks(autoHideTask)
if (!halfHidden) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
private fun setCompact(value: Boolean) {
val view = root ?: return
compact = value
applyMode()
reposition()
view.animate().cancel()
view.alpha = 1f
scheduleCollapse()
}
private fun cancelAutoHide() {
root?.removeCallbacks(autoHideTask)
private fun applyMode() {
val view = root ?: return
panel.visibility = if (compact) View.GONE else View.VISIBLE
capsule.visibility = if (compact) View.VISIBLE else View.GONE
view.background = background(SURFACE, if (compact) 24 else 22, border = true)
params?.width = dp(if (compact) COMPACT_WIDTH else PANEL_WIDTH)
// 收入屏幕一半,只在屏内露出 24dp 的把手;计时在展开后完整显示。
capsule.setPadding(if (dockRight) 0 else dp(EDGE_HIDDEN_WIDTH), 0,
if (dockRight) dp(EDGE_HIDDEN_WIDTH) else 0, 0)
lastState?.let(::render)
}
private fun baseFlags(): Int =
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
private fun scheduleCollapse() {
root?.removeCallbacks(collapseTask)
if (!compact) root?.postDelayed(collapseTask, AUTO_COLLAPSE_MS)
}
private fun label(size: Float, color: Int) = TextView(context).apply {
textSize = size
setTextColor(color)
includeFontPadding = false
gravity = Gravity.CENTER_VERTICAL
maxLines = 1
}
/** 两个动作同权重:浮窗不设主操作,强调只留给倒计时(见 design-principles「浮窗」行)。 */
private fun action(text: String) = label(14f, TEXT).apply {
this.text = text
gravity = Gravity.CENTER
typeface = Typeface.DEFAULT_BOLD
// mask 与背景同为圆角形状,按下水波纹才会被 14dp 圆角裁切,不溢到面板上。
background = RippleDrawable(
ColorStateList.valueOf(0x3367E8C4),
background(BUTTON, 14, border = true),
background(BUTTON, 14, border = true),
)
isClickable = true
isFocusable = false
layoutParams = LinearLayout.LayoutParams(0, dp(48), 1f)
}
private fun buildRoot(): LinearLayout {
val container = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
background = rounded(COLOR_BG, 16)
setPadding(dp(12), dp(10), dp(12), dp(10))
elevation = dp(10).toFloat()
elevation = dp(6).toFloat()
}
// ---- 常态条:● 计时 + 暂停/继续 ----
barRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
dotView = View(context).apply {
background = rounded(COLOR_ONGOING, 4)
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
}
timeView = TextView(context).apply {
setTextColor(Color.WHITE)
textSize = 17f
typeface = Typeface.MONOSPACE
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
setPadding(dp(8), 0, dp(10), 0)
}
fragmentView = pill("+", COLOR_NEUTRAL).apply {
contentDescription = "记一条知识碎片"
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { marginEnd = dp(6) }
}
toggleView = pill("暂停", COLOR_ACTION)
barRow.addView(dotView)
barRow.addView(timeView)
barRow.addView(fragmentView)
barRow.addView(toggleView)
container.addView(barRow)
// ---- 半隐藏小胶囊:● 计时 ----
compactRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
visibility = View.GONE
setPadding(dp(4), dp(2), dp(4), dp(2))
capsule = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
gravity = Gravity.CENTER
minimumHeight = dp(56)
isClickable = true
}
compactDot = View(context).apply {
background = rounded(COLOR_ONGOING, 4)
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
background = background(MINT, 4)
layoutParams = LinearLayout.LayoutParams(dp(4), dp(4))
}
compactTime = TextView(context).apply {
setTextColor(Color.WHITE)
textSize = 15f
typeface = Typeface.MONOSPACE
setPadding(dp(6), 0, dp(4), 0)
compactTime = label(22f, MINT).apply {
gravity = Gravity.CENTER
text = "‹"
}
compactRow.addView(compactDot)
compactRow.addView(compactTime)
compactRow.setOnClickListener { setHalfHidden(false) }
container.addView(compactRow)
capsule.addView(compactDot)
capsule.addView(compactTime)
capsule.setOnClickListener { setCompact(false) }
// 侧边把手的拖动不能被系统「返回」手势抢走;只排除把手自身的小区域。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
capsule.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ ->
view.systemGestureExclusionRects = listOf(Rect(0, 0, view.width, view.height))
}
}
attachDrag(capsule)
container.addView(capsule)
fragmentView.setOnClickListener {
scheduleAutoHide()
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
setHalfHidden(true)
panel = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(12), dp(12), dp(12), dp(12))
}
val handle = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(4), dp(4), dp(4), dp(12))
isClickable = true
contentDescription = "学习计时,点按收起,拖动调整位置"
}
val heading = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL }
statusView = label(12f, MINT).apply { text = "专注学习中" }
heading.addView(statusView, LinearLayout.LayoutParams(0, dp(24), 1f))
timeView = label(30f, TEXT).apply {
text = "00:00"
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
setPadding(0, dp(2), 0, 0)
}
handle.addView(heading)
handle.addView(timeView)
handle.setOnClickListener { setCompact(true) }
attachDrag(handle)
panel.addView(handle)
val actions = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL }
fragmentView = action("记碎片").apply {
contentDescription = "记一条知识碎片"
setOnClickListener {
setCompact(true)
onRequestFragmentInput?.invoke()
}
toggleView.setOnClickListener {
scheduleAutoHide()
}
toggleView = action("暂停").apply {
setOnClickListener {
scheduleCollapse()
onTogglePause?.invoke()
}
attachDrag(barRow)
}
actions.addView(fragmentView)
actions.addView(View(context), LinearLayout.LayoutParams(dp(8), 1))
actions.addView(toggleView)
panel.addView(actions)
container.addView(panel)
return container
}
/** 拖动移动;未移动的单击 = 切换半隐藏/恢复 */
private fun attachDrag(handle: View) {
var startX = 0
var startY = 0
var downRawX = 0f
var downRawY = 0f
var moved = false
handle.setOnTouchListener { _, event ->
val p = params ?: return@setOnTouchListener false
when (event.action) {
var downX = 0f
var downY = 0f
val slop = ViewConfiguration.get(context).scaledTouchSlop
handle.setOnTouchListener { touched, event ->
val layout = params ?: return@setOnTouchListener false
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
startX = p.x
startY = p.y
downRawX = event.rawX
downRawY = event.rawY
moved = false
cancelAutoHide()
startX = layout.x
startY = layout.y
downX = event.rawX
downY = event.rawY
dragging = false
root?.removeCallbacks(collapseTask)
true
}
MotionEvent.ACTION_MOVE -> {
val dx = (event.rawX - downRawX).toInt()
val dy = (event.rawY - downRawY).toInt()
if (abs(dx) > dp(4) || abs(dy) > dp(4)) {
moved = true
val view = root
val width = view?.width ?: dp(200)
val height = view?.height ?: dp(60)
val screenWidth = context.resources.displayMetrics.widthPixels
val screenHeight = context.resources.displayMetrics.heightPixels
p.x = (startX + dx).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(dp(0)))
p.y = (startY + dy).coerceIn(dp(0), (screenHeight - height).coerceAtLeast(dp(0)))
view?.let { runCatching { wm.updateViewLayout(it, p) } }
val dx = (event.rawX - downX).toInt()
val dy = (event.rawY - downY).toInt()
if (dragging || abs(dx) > slop || abs(dy) > slop) {
dragging = true
val bounds = screenBounds()
layout.x = (startX + dx).coerceIn(bounds.left, (bounds.right - layout.width).coerceAtLeast(bounds.left))
val maxY = (bounds.bottom - (root?.height ?: dp(48))).coerceAtLeast(bounds.top)
layout.y = (startY + dy).coerceIn(bounds.top, maxY)
updateLayout()
}
true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (moved) {
scheduleAutoHide()
} else {
setHalfHidden(!halfHidden)
MotionEvent.ACTION_UP -> {
if (dragging) savePosition() else touched.performClick()
dragging = false
scheduleCollapse()
true
}
MotionEvent.ACTION_CANCEL -> {
// 系统取消手势不应被当作点击展开/收起。
if (dragging) savePosition()
dragging = false
scheduleCollapse()
true
}
else -> false
}
}
}
private fun createParams(): WindowManager.LayoutParams {
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
@Suppress("DEPRECATION")
WindowManager.LayoutParams.TYPE_PHONE
private fun savePosition() {
val layout = params ?: return
val bounds = screenBounds()
dockRight = layout.x + layout.width / 2 > bounds.centerX()
val available = (bounds.height() - (root?.height ?: dp(48))).coerceAtLeast(1)
verticalFraction = ((layout.y - bounds.top).toFloat() / available).coerceIn(0f, 1f)
preferences.edit().putBoolean("dock_right", dockRight)
.putFloat("vertical_fraction", verticalFraction).apply()
applyMode()
reposition()
}
return WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
type,
baseFlags(),
PixelFormat.TRANSLUCENT,
).apply {
gravity = Gravity.TOP or Gravity.START
x = dp(12)
y = dp(160)
private fun position(view: View, layout: WindowManager.LayoutParams) {
val bounds = screenBounds()
layout.width = dp(if (compact) COMPACT_WIDTH else PANEL_WIDTH).coerceAtMost(bounds.width())
view.measure(View.MeasureSpec.makeMeasureSpec(layout.width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val hidden = if (compact) dp(EDGE_HIDDEN_WIDTH) else 0
layout.x = if (dockRight) bounds.right - layout.width + hidden else bounds.left - hidden
layout.y = bounds.top + ((bounds.height() - view.measuredHeight).coerceAtLeast(0) * verticalFraction).toInt()
}
private fun updateLayout() {
val view = root ?: return
val layout = params ?: return
runCatching { wm.updateViewLayout(view, layout) }
}
private fun screenBounds(): Rect {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val metrics = wm.currentWindowMetrics
val insets = metrics.windowInsets.getInsetsIgnoringVisibility(
WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout(),
)
val edgeMargin = if (compact) 0 else dp(6)
return Rect(insets.left + edgeMargin, insets.top + dp(8),
metrics.bounds.width() - insets.right - edgeMargin, metrics.bounds.height() - insets.bottom - dp(8))
}
val metrics = context.resources.displayMetrics
val edgeMargin = if (compact) 0 else dp(6)
return Rect(edgeMargin, dp(32), metrics.widthPixels - edgeMargin, metrics.heightPixels - dp(48))
}
companion object {
private const val AUTO_HIDE_DELAY_MS = 12_000L
private const val COLOR_BG = 0xCC1B1F27.toInt()
private const val COLOR_ONGOING = 0xFF34D399.toInt()
private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
private const val COLOR_RESUME = 0xFF238636.toInt()
private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
private const val COMPACT_WIDTH = 48
private const val EDGE_HIDDEN_WIDTH = 24
private const val PANEL_WIDTH = 224
private const val AUTO_COLLAPSE_MS = 8_000L
private const val SURFACE = 0xF51A242B.toInt()
private const val BUTTON = 0xFF2B3941.toInt()
private const val BORDER = 0xFF40515A.toInt()
private const val TEXT = 0xFFF1F7F5.toInt()
private const val SECONDARY = 0xFFADBDBF.toInt()
private const val MINT = 0xFF80E6C1.toInt()
private const val AMBER = 0xFFFFD08A.toInt()
}
}
@@ -6,9 +6,11 @@ import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.res.Configuration
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.SystemClock
import android.os.IBinder
import android.provider.Settings
import androidx.core.app.NotificationCompat
@@ -16,6 +18,7 @@ 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.formatCountdown
import com.catshark.lpt.util.formatDuration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -33,6 +36,8 @@ class StudySessionService : Service() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private lateinit var overlay: OverlayView
private lateinit var controller: SessionController
private val alertPreferences by lazy { getSharedPreferences("countdown_alert", MODE_PRIVATE) }
private var lastAlertKey: String? = null
override fun onCreate() {
super.onCreate()
@@ -43,6 +48,7 @@ class StudySessionService : Service() {
onRequestFragmentInput = { openFragmentInput() }
}
createChannel()
lastAlertKey = alertPreferences.getString("last_key", null)
// 状态变化:更新通知 / 悬浮窗。
// 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时
@@ -51,7 +57,10 @@ class StudySessionService : Service() {
controller.state.collect { state ->
if (!state.hasSession) {
overlay.hide()
if (state.resolved) stopSelf()
if (state.resolved) {
getSystemService(NotificationManager::class.java).cancel(ALERT_NOTIFICATION_ID)
stopSelf()
}
return@collect
}
ensureForeground(state)
@@ -74,6 +83,7 @@ class StudySessionService : Service() {
}
overlay.render(state)
notify(buildNotification(state))
checkCountdown(state)
}
}
}
@@ -94,6 +104,11 @@ class StudySessionService : Service() {
return START_STICKY
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
overlay.reposition()
}
override fun onDestroy() {
overlay.hide()
scope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
@@ -147,6 +162,28 @@ class StudySessionService : Service() {
manager.notify(NOTIFICATION_ID, notification)
}
private fun checkCountdown(state: SessionController.State) {
val key = countdownAlertKey(state, SystemClock.elapsedRealtime(), lastAlertKey) ?: return
lastAlertKey = key
alertPreferences.edit().putString("last_key", key).apply()
// 即使系统通知被静音或禁止,仍展示可见的浮窗提示,不抢焦点。
overlay.restore()
overlay.render(state)
val notification = NotificationCompat.Builder(this, ALERT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("本轮学习时间到")
.setContentText("${state.taskName ?: "学习会话"}:请暂停休息,会话不会自动结束")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(this, 3,
Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(0, "暂停", servicePendingIntent(ACTION_PAUSE, 1))
.build()
runCatching { getSystemService(NotificationManager::class.java).notify(ALERT_NOTIFICATION_ID, notification) }
}
private fun buildNotification(state: SessionController.State): Notification {
val ongoing = state.status == SessionController.Status.ONGOING
val toggleLabel = if (ongoing) "暂停" else "继续"
@@ -164,7 +201,7 @@ class StudySessionService : Service() {
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(state.taskName ?: "学习会话")
.setContentText("${if (ongoing) "进行中" else "已暂停"} · 有效 ${formatDuration(state.effectiveSeconds())}")
.setContentText("${if (state.remainingMs() == 0L) "时间到" else if (ongoing) "倒计时" else "已暂停"} ${formatCountdown(state.remainingMs())} · 有效 ${formatDuration(state.effectiveSeconds())}")
.setContentIntent(contentIntent)
.setOngoing(true)
.setOnlyAlertOnce(true)
@@ -204,6 +241,12 @@ class StudySessionService : Service() {
private fun createChannel() {
val manager = getSystemService(NotificationManager::class.java)
val alertChannel = NotificationChannel(ALERT_CHANNEL_ID, "学习到时提醒", NotificationManager.IMPORTANCE_HIGH).apply {
description = "倒计时结束时提醒一次;声音和振动遵循系统设置"
enableVibration(true)
setShowBadge(true)
}
manager.createNotificationChannel(alertChannel)
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
val channel = NotificationChannel(
CHANNEL_ID,
@@ -219,6 +262,8 @@ class StudySessionService : Service() {
companion object {
const val CHANNEL_ID = "study_session"
const val NOTIFICATION_ID = 1001
const val ALERT_CHANNEL_ID = "study_countdown_alert"
const val ALERT_NOTIFICATION_ID = 1002
const val ACTION_PAUSE = "com.catshark.lpt.action.PAUSE"
const val ACTION_RESUME = "com.catshark.lpt.action.RESUME"
@@ -1,5 +1,6 @@
package com.catshark.lpt.util
import kotlin.math.ceil
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@@ -12,6 +13,10 @@ fun formatDuration(seconds: Double): String {
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
}
/** 倒计时向上取整:不足一秒仍显示 00:01,实际到零才显示 00:00。 */
fun formatCountdown(remainingMs: Long?): String =
remainingMs?.let { formatDuration(ceil(it.coerceAtLeast(0) / 1000.0)) } ?: "--:--"
private val DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
/** 服务端返回的 LocalDateTime 字符串(无时区),解析失败时原样展示 */
@@ -0,0 +1,66 @@
package com.catshark.lpt.service
import com.catshark.lpt.session.SessionController
import com.catshark.lpt.util.formatCountdown
import org.junit.Assert.*
import org.junit.Test
class CountdownAlertTest {
private fun running(ms: Long = 1500L) = SessionController.State(
sessionNum = "s1", status = SessionController.Status.ONGOING,
countdownBaseMs = ms, anchorRealtimeMs = 1000L, countdownKey = "s1|start1",
)
@Test fun countdownUsesMonotonicAnchorAndStopsAtZero() {
val state = running()
assertEquals(1500L, state.remainingMs(1000L))
assertEquals(500L, state.remainingMs(2000L))
assertEquals(0L, state.remainingMs(2500L))
assertEquals(0L, state.remainingMs(20000L))
assertEquals(1500L, state.remainingMs(500L))
}
@Test fun pausedCountdownDoesNotDecrease() {
val state = running().copy(status = SessionController.Status.PAUSED)
assertEquals(1500L, state.remainingMs(100000L))
assertNull(countdownAlertKey(state.copy(countdownBaseMs = 0L), 100000L, null))
}
@Test fun missingCountdownIsNotAnExpiredTimer() {
val state = running().copy(countdownBaseMs = null)
assertNull(state.remainingMs(100000L))
assertNull(countdownAlertKey(state, 100000L, null))
assertEquals("--:--", formatCountdown(null))
}
@Test fun countdownOnlyDisplaysZeroAtActualDeadline() {
assertEquals("00:01", formatCountdown(1))
assertEquals("00:01", formatCountdown(999))
assertEquals("00:02", formatCountdown(1001))
assertEquals("00:00", formatCountdown(0))
assertEquals("25:00", formatCountdown(1500000))
}
@Test fun expiryEmitsOnceAndSurvivesReconciliationOrRestart() {
val state = running()
assertNull(countdownAlertKey(state, 2499L, null))
val persistedKey = countdownAlertKey(state, 2500L, null)
assertEquals("s1|start1", persistedKey)
assertNull(countdownAlertKey(state, 5000L, persistedKey))
// 进程恢复只重新对锚,不改变后端分段标识。
val restored = state.copy(anchorRealtimeMs = 500L)
assertNull(countdownAlertKey(restored, 5000L, persistedKey))
}
@Test fun nextSegmentCanAlertButEndedSessionCannot() {
val state = running().copy(countdownKey = "s1|start2")
assertEquals("s1|start2", countdownAlertKey(state, 3000L, "s1|start1"))
assertNull(countdownAlertKey(state.copy(status = SessionController.Status.ENDED), 3000L, null))
}
@Test fun expiredSessionOnRecoveryAlertsOnceWithoutEndingSession() {
val state = running(0L)
assertEquals("s1|start1", countdownAlertKey(state, 1000L, null))
assertEquals(SessionController.Status.ONGOING, state.status)
}
}