From e1d4bba2178e7903bec326c73a43e699af3997ad Mon Sep 17 00:00:00 2001
From: catShark <1716967236@qq.com>
Date: Thu, 29 Oct 2026 19:44:40 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20LPT=20Android=20=E5=AE=A2=E6=88=B7?=
=?UTF-8?q?=E7=AB=AF=E9=A6=96=E7=89=88=EF=BC=88=E5=AD=A6=E4=B9=A0=E4=BC=9A?=
=?UTF-8?q?=E8=AF=9D=20+=20=E6=82=AC=E6=B5=AE=E7=AA=97=EF=BC=89?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 15 +
AGENTS.md | 44 ++
README.md | 115 +++++
app/build.gradle.kts | 70 +++
app/proguard-rules.pro | 5 +
app/src/main/AndroidManifest.xml | 50 ++
app/src/main/java/com/catshark/lpt/LptApp.kt | 95 ++++
.../java/com/catshark/lpt/MainActivity.kt | 204 +++++++++
.../java/com/catshark/lpt/data/ApiClient.kt | 61 +++
.../main/java/com/catshark/lpt/data/LptApi.kt | 72 +++
.../com/catshark/lpt/data/LptRepository.kt | 93 ++++
.../main/java/com/catshark/lpt/data/Models.kt | 143 ++++++
.../java/com/catshark/lpt/data/TokenStore.kt | 57 +++
.../com/catshark/lpt/service/OverlayView.kt | 426 ++++++++++++++++++
.../lpt/service/StudySessionService.kt | 242 ++++++++++
.../catshark/lpt/session/SessionController.kt | 234 ++++++++++
.../catshark/lpt/ui/FragmentInputActivity.kt | 117 +++++
.../java/com/catshark/lpt/ui/LoginScreen.kt | 132 ++++++
.../com/catshark/lpt/ui/PermissionScreen.kt | 216 +++++++++
.../java/com/catshark/lpt/ui/SessionScreen.kt | 374 +++++++++++++++
.../com/catshark/lpt/ui/SettingsScreen.kt | 74 +++
.../com/catshark/lpt/ui/TaskListScreen.kt | 144 ++++++
.../java/com/catshark/lpt/ui/theme/Theme.kt | 30 ++
.../main/java/com/catshark/lpt/util/Format.kt | 10 +
.../res/drawable/ic_launcher_background.xml | 4 +
.../res/drawable/ic_launcher_foreground.xml | 16 +
app/src/main/res/drawable/ic_notification.xml | 14 +
.../res/mipmap-anydpi-v26/ic_launcher.xml | 5 +
app/src/main/res/values-night/themes.xml | 4 +
app/src/main/res/values/strings.xml | 4 +
app/src/main/res/values/themes.xml | 13 +
build.gradle.kts | 6 +
gradle.properties | 10 +
gradle/libs.versions.toml | 39 ++
gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 44309 bytes
gradle/wrapper/gradle-wrapper.properties | 7 +
gradlew | 251 +++++++++++
gradlew.bat | 94 ++++
settings.gradle.kts | 24 +
39 files changed, 3514 insertions(+)
create mode 100644 .gitignore
create mode 100644 AGENTS.md
create mode 100644 README.md
create mode 100644 app/build.gradle.kts
create mode 100644 app/proguard-rules.pro
create mode 100644 app/src/main/AndroidManifest.xml
create mode 100644 app/src/main/java/com/catshark/lpt/LptApp.kt
create mode 100644 app/src/main/java/com/catshark/lpt/MainActivity.kt
create mode 100644 app/src/main/java/com/catshark/lpt/data/ApiClient.kt
create mode 100644 app/src/main/java/com/catshark/lpt/data/LptApi.kt
create mode 100644 app/src/main/java/com/catshark/lpt/data/LptRepository.kt
create mode 100644 app/src/main/java/com/catshark/lpt/data/Models.kt
create mode 100644 app/src/main/java/com/catshark/lpt/data/TokenStore.kt
create mode 100644 app/src/main/java/com/catshark/lpt/service/OverlayView.kt
create mode 100644 app/src/main/java/com/catshark/lpt/service/StudySessionService.kt
create mode 100644 app/src/main/java/com/catshark/lpt/session/SessionController.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/FragmentInputActivity.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/LoginScreen.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/PermissionScreen.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/SessionScreen.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/SettingsScreen.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/TaskListScreen.kt
create mode 100644 app/src/main/java/com/catshark/lpt/ui/theme/Theme.kt
create mode 100644 app/src/main/java/com/catshark/lpt/util/Format.kt
create mode 100644 app/src/main/res/drawable/ic_launcher_background.xml
create mode 100644 app/src/main/res/drawable/ic_launcher_foreground.xml
create mode 100644 app/src/main/res/drawable/ic_notification.xml
create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
create mode 100644 app/src/main/res/values-night/themes.xml
create mode 100644 app/src/main/res/values/strings.xml
create mode 100644 app/src/main/res/values/themes.xml
create mode 100644 build.gradle.kts
create mode 100644 gradle.properties
create mode 100644 gradle/libs.versions.toml
create mode 100644 gradle/wrapper/gradle-wrapper.jar
create mode 100644 gradle/wrapper/gradle-wrapper.properties
create mode 100755 gradlew
create mode 100644 gradlew.bat
create mode 100644 settings.gradle.kts
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ca65454
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+# Gradle
+.gradle/
+build/
+app/build/
+local.properties
+
+# IDE
+.idea/
+*.iml
+captures/
+
+# 系统
+.DS_Store
+*.apk
+*.aab
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..ec6f1a7
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,44 @@
+# lpt-android 代理协作规范
+
+> LPT 的 Android 客户端:学习会话 + 系统级悬浮窗,不含复习。
+
+## 规则与技能位置
+
+- 通用规则(跨仓库):meta 仓库 `.agents/roles/`(提交规范见其中的 `commit-convention.md`)。
+- 本仓库暂无专属 `roles/` 与 `skills/`;出现 Android 专属约定时再建。
+
+## 技术栈
+
+- Kotlin 2.3.21 + Jetpack Compose(Material 3)
+- AGP 8.13.2 / Gradle 8.14.6 / JDK 17 / compileSdk 36 / minSdk 26
+- Retrofit + OkHttp + kotlinx.serialization;DataStore Preferences
+- 悬浮窗用经典 View + `WindowManager`,**不用 Compose-in-overlay**
+
+> Compose BOM 锁 `2026.03.01`。升到 ≥ 2026.04 会要求 AGP 9.1+ / compileSdk 37,见 README。
+
+## 目录职责
+
+| 目录 | 职责 |
+|------|------|
+| `data/` | 网络与本地存储;`LptApi` 是唯一接口定义处,`LptRepository` 负责 `code != 200 → ApiException` |
+| `session/` | `SessionController` 是会话状态机唯一入口;UI 与服务都只读它的 `StateFlow` |
+| `service/` | 前台服务与悬浮窗;不承载业务逻辑,只渲染状态并转发动作 |
+| `ui/` | Compose 页面;不直接调 Retrofit,只调 `SessionController` / `AppContainer` |
+
+## 必须遵守的约定
+
+- **会话状态只在 `SessionController` 里改**。UI 和 Service 都不得自行维护会话副本,否则会与服务端口径分叉。
+- **计时不得用 tick 累加**。显示值一律走 `State.effectiveSeconds(nowMs)`,基准取服务端 `effectiveTime`,锚点取 `SystemClock.elapsedRealtime()`。
+- **悬浮窗窗口标志不要随手改**:`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_NO_LIMITS` 三者缺一都会出问题(抢焦点 / 挡住下层 / 半隐藏被夹回屏幕内)。
+- **不要在浮窗里做文本输入**。App 不在前台时系统不允许后台窗口弹键盘;需要输入时拉起 Activity。
+- **对接后端先看部署环境的 OpenAPI**(`GET {baseUrl}/v3/api-docs`),不要假设源码与部署一致——两者已经分叉过一次。
+
+## 后端
+
+- dev:`https://lpt-dev.cat-shark.xyz/api`
+- 认证:Sa-Token,token 放请求头 `satoken`(不用 Cookie)
+- 只使用学习会话相关端点,**不碰 `review/*`**
+
+## 提交规范
+
+同 meta 仓库:简短中文,格式 `类型: 简述`,例如 `feat: 新增悬浮窗碎片录入`。
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6fc0dbd
--- /dev/null
+++ b/README.md
@@ -0,0 +1,115 @@
+# lpt-android
+
+> LPT 的 Android 客户端:**学习会话 + 系统级悬浮窗**。不含复习模块。
+
+## 它解决什么
+
+LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习场景经常是「手机/平板上看视频课,同时想记录学习时间」。浏览器做不到跨应用常驻,所以需要一个悬浮窗:
+
+- 浮窗常驻在其他 App 之上,学习计时不因切走而中断。
+- 不抢输入法焦点、不挡住下层 App 的触摸(`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL`)。
+- 12 秒无操作自动收成贴边小胶囊,点一下恢复;常态 80% 不透明,收起后 60%。
+- 可在浮窗里直接记一条知识碎片(拉起轻量输入弹窗)。
+
+## 功能范围
+
+| 模块 | 内容 |
+|------|------|
+| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头 |
+| 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
+| 任务列表 | `GET /tasks` |
+| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期、知识碎片、结束报告三段 |
+| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;暂停/继续/结束/记碎片/半隐藏 |
+| 设置 | API 地址可切(默认 dev) |
+
+**不做**:复习(`review/*`)、思维导图、回忆对比、学习录音。
+
+## 技术栈
+
+- Kotlin + Jetpack Compose(Material 3),单 module
+- 网络:Retrofit + OkHttp + kotlinx.serialization
+- 本地:DataStore Preferences(token / baseUrl / username)
+- 悬浮窗:经典 View + `WindowManager` + `TYPE_APPLICATION_OVERLAY`(不用 Compose-in-overlay,避开 lifecycle owner 问题)
+- 无 Hilt / Room / Navigation-Compose,手写依赖容器,减少构建面
+
+### 版本组合(已验证可构建)
+
+| 组件 | 版本 |
+|------|------|
+| AGP | 8.13.2 |
+| Gradle | 8.14.6 |
+| Kotlin | 2.3.21 |
+| Compose BOM | **2026.03.01**(compose 1.10.6) |
+| compileSdk / targetSdk | 36 / 36 |
+| minSdk | 26 |
+| JDK | 17 |
+
+> ⚠️ Compose BOM ≥ 2026.04(compose 1.11+)要求 **AGP 9.1+ 与 compileSdk 37**,配 AGP 8.13.2 会报 `requires Android Gradle plugin 9.1.0 or higher`。要么整体升 AGP 9,要么锁在 2026.03.01。
+
+## 构建与安装
+
+```bash
+export JAVA_HOME=$HOME/opt/jdk
+export ANDROID_HOME=$HOME/opt/android-sdk
+export PATH=$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$HOME/opt/gradle-8.14.6/bin:$PATH
+
+gradle :app:assembleDebug
+```
+
+国内直连 Google Maven 很慢,`settings.gradle.kts` 已配置阿里云镜像。
+
+### MIUI / 红米注意
+
+1. **`adb install` 会被拦**(`INSTALL_FAILED_USER_RESTRICTED`):需在开发者选项里开「USB 调试(安全设置)/ 通过 USB 安装」,手机端手动确认一次;或改用
+ ```bash
+ adb push app/build/outputs/apk/debug/app-debug.apk /data/local/tmp/lpt.apk
+ adb shell pm install -r -t /data/local/tmp/lpt.apk
+ ```
+2. **重装会重置悬浮窗权限**(appops 变 `ignore`),且装完立刻 `appops set` 会被 MIUI 异步覆盖。正确做法是装完等几秒再设:
+ ```bash
+ adb shell appops set com.catshark.lpt SYSTEM_ALERT_WINDOW allow
+ adb shell appops get com.catshark.lpt SYSTEM_ALERT_WINDOW # 应为 allow
+ ```
+3. MIUI 还会限制后台启动与后台弹窗,需手动放行「自启动」和「其他权限 → 后台弹出界面」,省电策略设「无限制」——App 的「权限」页有入口。
+
+## 关键实现决定
+
+- **计时口径**:显示值 = 服务端 `effectiveTime`(基准)+ 以 `SystemClock.elapsedRealtime()` 为锚点的增量。**不用 tick 累加**,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时用服务端 `lastStartTime` 重新对锚。
+- **窗口必须带 `FLAG_LAYOUT_NO_LIMITS`**:否则 WindowManager 会把越界位置夹回屏幕内,半隐藏会失效(实测 `mAttrs x=-651` 但 `mFrame` 仍是 `[0,...]`)。
+- **浮窗内不做文本输入**:App 不在前台时,系统不允许后台窗口弹软键盘——实测浮窗的 `EditText` 能拿到输入连接(`mServedView=EditText`),但 IME 窗口 `mViewVisibility=0x8`(GONE)。因此「记碎片」改为拉起 `FragmentInputActivity`(带 `SYSTEM_ALERT_WINDOW` 的 App 有后台启动 Activity 豁免),并给它独立 `taskAffinity`,保存后回到用户原本在用的 App。
+- **服务自恢复**:App 启动时 `GET /study-sessions/active` 对账,恢复未结束的会话;只要状态里有活跃会话就拉起前台服务,权限是后来才授予的也会每秒兜底重试 `overlay.show()`。
+
+## 后端契约兼容(重要)
+
+**dev 部署的后端比本地源码旧**,两者契约不同。客户端对二者都兼容(多发字段两边都会忽略):
+
+| 接口 | 部署版(旧) | 本地源码(新) | 客户端做法 |
+|------|--------------|----------------|-----------|
+| `POST /report-fragments` | `{sessionNum, content}` | `{contextNum, content}` | 两个字段都发 |
+| `POST .../study-sessions/ended` | `{content}`(单段,必填) | `{sessionSummary, expectationVerdict, freeSummary}` | 发 `content`(三段拼接)+ 三段字段 |
+| 报告草稿 | `GET .../report-draft`(同步 AI) | `POST /ai/tasks`(异步) | 暂未接入,报告由用户手写 |
+| `DELETE /report-fragments/{id}` | 不存在 | 存在 | 未使用 |
+
+排查这类问题的可靠手段:直接拉部署环境的 OpenAPI —— `GET {baseUrl}/v3/api-docs`。
+
+## 目录结构
+
+```text
+app/src/main/java/com/catshark/lpt/
+├── LptApp.kt Application + 手写依赖容器
+├── MainActivity.kt 导航(任务列表 / 会话 / 权限 / 设置)
+├── data/ Models / LptApi / ApiClient / TokenStore / LptRepository
+├── session/SessionController.kt 会话状态机(Application 级单例,StateFlow)
+├── service/
+│ ├── StudySessionService.kt 前台服务 + 通知 + 调度浮窗与输入弹窗
+│ └── OverlayView.kt 悬浮窗(完整条 / 半隐藏胶囊)
+├── ui/ Compose 页面 + FragmentInputActivity
+└── util/Format.kt
+```
+
+## 已知限制
+
+- 浮窗依赖悬浮窗权限,被系统回收后需要 App 进程还活着才能自动恢复(`START_STICKY` + 启动时对账)。
+- 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。
+- 报告草稿的 AI 生成未接入(旧后端同步接口慢、新后端是异步任务,两者差异大),报告目前由用户手写。
+- 学习录音(系统混音采集)未做,属于二期。
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..463825a
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,70 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+android {
+ namespace = "com.catshark.lpt"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "com.catshark.lpt"
+ minSdk = 26
+ targetSdk = 36
+ versionCode = 1
+ versionName = "0.1.0"
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro",
+ )
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ buildFeatures {
+ compose = true
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+dependencies {
+ implementation(platform(libs.androidx.compose.bom))
+
+ implementation(libs.androidx.core.ktx)
+ implementation(libs.androidx.activity.compose)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+ implementation(libs.androidx.lifecycle.service)
+ implementation(libs.androidx.datastore.preferences)
+
+ implementation(libs.androidx.compose.ui)
+ implementation(libs.androidx.compose.ui.tooling.preview)
+ implementation(libs.androidx.compose.material3)
+
+ implementation(libs.okhttp)
+ implementation(libs.retrofit)
+ implementation(libs.retrofit.serialization)
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.kotlinx.coroutines.android)
+
+ debugImplementation(libs.androidx.compose.ui.tooling)
+}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
new file mode 100644
index 0000000..dde84d0
--- /dev/null
+++ b/app/proguard-rules.pro
@@ -0,0 +1,5 @@
+# 保持 Retrofit / kotlinx.serialization 相关元数据(当前未开启混淆,保留备用)
+-keepattributes Signature, *Annotation*
+-keep class kotlinx.serialization.** { *; }
+-dontwarn okhttp3.**
+-dontwarn retrofit2.**
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..13c9c68
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/com/catshark/lpt/LptApp.kt b/app/src/main/java/com/catshark/lpt/LptApp.kt
new file mode 100644
index 0000000..99f9c4a
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/LptApp.kt
@@ -0,0 +1,95 @@
+package com.catshark.lpt
+
+import android.app.Application
+import com.catshark.lpt.data.ApiClient
+import com.catshark.lpt.data.LptRepository
+import com.catshark.lpt.data.TokenStore
+import com.catshark.lpt.session.SessionController
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+
+class LptApp : Application() {
+
+ lateinit var container: AppContainer
+ private set
+
+ override fun onCreate() {
+ super.onCreate()
+ container = AppContainer(this)
+ }
+}
+
+/** 手写依赖容器,不引 Hilt,减少构建复杂度 */
+class AppContainer(private val app: Application) {
+
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ val tokenStore = TokenStore(app)
+ val apiClient = ApiClient()
+ val repository = LptRepository(apiClient)
+ val session = SessionController(repository, scope)
+
+ private val _ready = MutableStateFlow(false)
+ val ready: StateFlow = _ready.asStateFlow()
+
+ private val _loggedIn = MutableStateFlow(false)
+ val loggedIn: StateFlow = _loggedIn.asStateFlow()
+
+ private val _username = MutableStateFlow(null)
+ val username: StateFlow = _username.asStateFlow()
+
+ private val _baseUrl = MutableStateFlow(ApiClient.DEFAULT_BASE_URL)
+ val baseUrl: StateFlow = _baseUrl.asStateFlow()
+
+ init {
+ scope.launch {
+ val settings = tokenStore.load()
+ apiClient.setBaseUrl(settings.baseUrl)
+ apiClient.token = settings.token
+ _baseUrl.value = settings.baseUrl
+ _username.value = settings.username
+ _loggedIn.value = !settings.token.isNullOrBlank()
+ _ready.value = true
+ if (_loggedIn.value) session.reconcile()
+ }
+ }
+
+ fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
+ scope.launch {
+ apiClient.setBaseUrl(baseUrl)
+ repository.login(username, password)
+ .onSuccess { token ->
+ apiClient.token = token
+ tokenStore.saveLogin(token, username, baseUrl)
+ _baseUrl.value = baseUrl
+ _username.value = username
+ _loggedIn.value = true
+ session.reconcile()
+ onResult(null)
+ }
+ .onFailure { onResult(it.message ?: "登录失败") }
+ }
+ }
+
+ fun logout() {
+ scope.launch {
+ repository.logout()
+ tokenStore.clearLogin()
+ apiClient.token = null
+ session.clear()
+ _loggedIn.value = false
+ }
+ }
+
+ fun updateBaseUrl(url: String) {
+ scope.launch {
+ apiClient.setBaseUrl(url)
+ tokenStore.saveBaseUrl(url)
+ _baseUrl.value = url
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/MainActivity.kt b/app/src/main/java/com/catshark/lpt/MainActivity.kt
new file mode 100644
index 0000000..7845c6a
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/MainActivity.kt
@@ -0,0 +1,204 @@
+package com.catshark.lpt
+
+import android.content.Intent
+import android.os.Bundle
+import android.provider.Settings
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import com.catshark.lpt.data.TaskItem
+import com.catshark.lpt.service.StudySessionService
+import com.catshark.lpt.ui.LoginScreen
+import com.catshark.lpt.ui.PermissionScreen
+import com.catshark.lpt.ui.SessionScreen
+import com.catshark.lpt.ui.SettingsScreen
+import com.catshark.lpt.ui.TaskListScreen
+import com.catshark.lpt.ui.theme.LptTheme
+import kotlinx.coroutines.launch
+
+class MainActivity : ComponentActivity() {
+
+ private val openEndRequest = mutableStateOf(false)
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ handleIntent(intent)
+ setContent {
+ LptTheme {
+ Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
+ AppRoot(openEndRequest)
+ }
+ }
+ }
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ handleIntent(intent)
+ }
+
+ private fun handleIntent(intent: Intent?) {
+ if (intent?.getBooleanExtra(EXTRA_OPEN_END, false) == true) {
+ openEndRequest.value = true
+ }
+ }
+
+ companion object {
+ const val EXTRA_OPEN_END = "open_end"
+ }
+}
+
+private enum class Screen { Tasks, Session, Permissions, Settings }
+
+@Composable
+private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState) {
+ val container = (LocalContext.current.applicationContext as LptApp).container
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+
+ val ready by container.ready.collectAsState()
+ val loggedIn by container.loggedIn.collectAsState()
+ val username by container.username.collectAsState()
+ val baseUrl by container.baseUrl.collectAsState()
+ val sessionState by container.session.state.collectAsState()
+ val openEnd by openEndRequest
+
+ var screen by remember { mutableStateOf(Screen.Tasks) }
+ var tasks by remember { mutableStateOf>(emptyList()) }
+ var tasksLoading by remember { mutableStateOf(false) }
+ var tasksError by remember { mutableStateOf(null) }
+
+ fun refreshTasks() {
+ tasksLoading = true
+ tasksError = null
+ scope.launch {
+ container.repository.tasks()
+ .onSuccess {
+ tasks = it
+ tasksLoading = false
+ }
+ .onFailure {
+ tasksError = it.message ?: "加载任务失败"
+ tasksLoading = false
+ }
+ }
+ }
+
+ LaunchedEffect(loggedIn) {
+ if (loggedIn) {
+ refreshTasks()
+ if (!Settings.canDrawOverlays(context)) screen = Screen.Permissions
+ } else {
+ tasks = emptyList()
+ screen = Screen.Tasks
+ }
+ }
+
+ LaunchedEffect(sessionState.hasSession) {
+ if (sessionState.hasSession) {
+ screen = Screen.Session
+ } else if (screen == Screen.Session) {
+ screen = Screen.Tasks
+ }
+ }
+
+ // 会话存在就把前台服务拉起来(重装/重启/被系统杀掉后恢复浮窗)
+ LaunchedEffect(ready, loggedIn, sessionState.hasSession) {
+ if (ready && loggedIn && sessionState.hasSession) {
+ StudySessionService.start(context)
+ }
+ }
+
+ when {
+ !ready -> LoadingScreen()
+
+ !loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
+ container.login(user, password, url, onResult)
+ }
+
+ else -> when (screen) {
+ Screen.Tasks -> TaskListScreen(
+ tasks = tasks,
+ loading = tasksLoading,
+ error = tasksError,
+ username = username,
+ onRefresh = { refreshTasks() },
+ onStart = { task ->
+ container.session.startOrContinue(task.taskNum) {
+ StudySessionService.start(context)
+ }
+ },
+ onOpenSettings = { screen = Screen.Settings },
+ onOpenPermissions = { screen = Screen.Permissions },
+ onLogout = {
+ StudySessionService.stop(context)
+ container.logout()
+ },
+ )
+
+ Screen.Session -> SessionScreen(
+ state = sessionState,
+ openEndDialog = openEnd,
+ onConsumeOpenEnd = { openEndRequest.value = false },
+ onTogglePause = {
+ if (sessionState.status == com.catshark.lpt.session.SessionController.Status.ONGOING) {
+ container.session.pause()
+ } else {
+ container.session.resume()
+ }
+ },
+ onEnd = { sections ->
+ container.session.end(sections) {
+ StudySessionService.stop(context)
+ refreshTasks()
+ }
+ },
+ onAbort = { phrase ->
+ container.session.abort(phrase) {
+ StudySessionService.stop(context)
+ refreshTasks()
+ }
+ },
+ onSaveExpectation = { container.session.saveExpectation(it) },
+ onAddFragment = { container.session.addFragment(it) },
+ onShowOverlay = { StudySessionService.showOverlay(context) },
+ onBack = { screen = Screen.Tasks },
+ )
+
+ Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
+
+ Screen.Settings -> SettingsScreen(
+ baseUrl = baseUrl,
+ onSave = { container.updateBaseUrl(it) },
+ onLogout = {
+ StudySessionService.stop(context)
+ container.logout()
+ },
+ onBack = { screen = Screen.Tasks },
+ )
+ }
+ }
+}
+
+@Composable
+private fun LoadingScreen() {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/data/ApiClient.kt b/app/src/main/java/com/catshark/lpt/data/ApiClient.kt
new file mode 100644
index 0000000..abbaea2
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/data/ApiClient.kt
@@ -0,0 +1,61 @@
+package com.catshark.lpt.data
+
+import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
+import kotlinx.serialization.json.Json
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import retrofit2.Retrofit
+import java.util.concurrent.TimeUnit
+
+/**
+ * 网络客户端。baseUrl 与 token 都可在运行时切换(设置页 / 登录),
+ * token 通过拦截器以 `satoken` 请求头注入,不依赖 Cookie。
+ */
+class ApiClient {
+
+ @Volatile
+ var token: String? = null
+
+ @Volatile
+ private var baseUrl: String? = null
+
+ @Volatile
+ private var retrofit: Retrofit? = null
+
+ private val json = Json {
+ ignoreUnknownKeys = true
+ isLenient = true
+ coerceInputValues = true
+ }
+
+ private val okHttp: OkHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val builder = chain.request().newBuilder()
+ token?.takeIf { it.isNotBlank() }?.let { builder.header("satoken", it) }
+ chain.proceed(builder.build())
+ }
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .readTimeout(300, TimeUnit.SECONDS)
+ .writeTimeout(60, TimeUnit.SECONDS)
+ .build()
+
+ fun setBaseUrl(url: String) {
+ val normalized = url.trim().let { if (it.endsWith("/")) it else "$it/" }
+ if (normalized == baseUrl && retrofit != null) return
+ baseUrl = normalized
+ retrofit = Retrofit.Builder()
+ .baseUrl(normalized)
+ .client(okHttp)
+ .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
+ .build()
+ }
+
+ val currentBaseUrl: String get() = baseUrl ?: DEFAULT_BASE_URL
+
+ val api: LptApi
+ get() = (retrofit ?: throw IllegalStateException("ApiClient 尚未设置 baseUrl")).create(LptApi::class.java)
+
+ companion object {
+ const val DEFAULT_BASE_URL = "https://lpt-dev.cat-shark.xyz/api"
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/data/LptApi.kt b/app/src/main/java/com/catshark/lpt/data/LptApi.kt
new file mode 100644
index 0000000..0a1129b
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/data/LptApi.kt
@@ -0,0 +1,72 @@
+package com.catshark.lpt.data
+
+import kotlinx.serialization.json.JsonElement
+import retrofit2.http.Body
+import retrofit2.http.GET
+import retrofit2.http.POST
+import retrofit2.http.PUT
+import retrofit2.http.Path
+import retrofit2.http.Query
+
+/**
+ * lpt-be 学习会话相关接口(不含复习模块)。
+ * 认证走请求头 `satoken`,由 ApiClient 的拦截器注入。
+ */
+interface LptApi {
+
+ @POST("login")
+ suspend fun login(@Body body: LoginRequest): ApiEnvelope
+
+ @POST("logout")
+ suspend fun logout(): ApiEnvelope
+
+ @GET("tasks")
+ suspend fun tasks(): ApiEnvelope
+
+ @GET("study-sessions/active")
+ suspend fun activeSession(
+ @Query("excludeTaskNum") excludeTaskNum: String? = null,
+ ): ApiEnvelope
+
+ @GET("tasks/{taskNum}/study-sessions/start-or-continue")
+ suspend fun startOrContinue(@Path("taskNum") taskNum: String): ApiEnvelope
+
+ @GET("study-sessions/{sessionNum}")
+ suspend fun sessionDetail(@Path("sessionNum") sessionNum: String): ApiEnvelope
+
+ @GET("study-sessions/{sessionNum}/expectation")
+ suspend fun getExpectation(@Path("sessionNum") sessionNum: String): ApiEnvelope
+
+ @PUT("study-sessions/{sessionNum}/expectation")
+ suspend fun putExpectation(
+ @Path("sessionNum") sessionNum: String,
+ @Body body: ExpectationRequest,
+ ): ApiEnvelope
+
+ @POST("study-sessions/{sessionNum}/study-sessions/continue")
+ suspend fun continueSession(@Path("sessionNum") sessionNum: String): ApiEnvelope
+
+ @POST("study-sessions/{sessionNum}/study-sessions/pause")
+ suspend fun pauseSession(
+ @Path("sessionNum") sessionNum: String,
+ @Query("endTime") endTime: String? = null,
+ ): ApiEnvelope
+
+ @POST("study-sessions/{sessionNum}/study-sessions/ended")
+ suspend fun endSession(
+ @Path("sessionNum") sessionNum: String,
+ @Body body: EndSessionRequest,
+ ): ApiEnvelope
+
+ @POST("study-sessions/{sessionNum}/study-sessions/abort")
+ suspend fun abortSession(
+ @Path("sessionNum") sessionNum: String,
+ @Body body: AbortRequest,
+ ): ApiEnvelope
+
+ @POST("report-fragments")
+ suspend fun createFragment(@Body body: CreateFragmentRequest): ApiEnvelope
+
+ @GET("report-fragments/session/{sessionNum}")
+ suspend fun fragmentsBySession(@Path("sessionNum") sessionNum: String): ApiEnvelope>
+}
diff --git a/app/src/main/java/com/catshark/lpt/data/LptRepository.kt b/app/src/main/java/com/catshark/lpt/data/LptRepository.kt
new file mode 100644
index 0000000..f8cac91
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/data/LptRepository.kt
@@ -0,0 +1,93 @@
+package com.catshark.lpt.data
+
+/** 业务错误:把后端的 message 直接带给 UI */
+class ApiException(message: String) : Exception(message)
+
+/**
+ * 学习会话仓库:把 Retrofit 调用包成 Result,并把 `code != 200` 转成 ApiException。
+ */
+class LptRepository(private val apiClient: ApiClient) {
+
+ private val api get() = apiClient.api
+
+ private inline fun envelope(env: ApiEnvelope, action: String): T {
+ if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "${action}失败")
+ @Suppress("UNCHECKED_CAST")
+ return env.data as T
+ }
+
+ suspend fun login(username: String, password: String): Result = runCatching {
+ val env = api.login(LoginRequest(username, password))
+ if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "登录失败")
+ extractToken(env.data)?.takeIf { it.isNotBlank() } ?: throw ApiException("登录响应缺少 token")
+ }
+
+ suspend fun logout(): Result = runCatching { api.logout() }
+
+ suspend fun tasks(): Result> = runCatching {
+ envelope(api.tasks(), "获取任务").records
+ }
+
+ suspend fun activeSession(): Result = runCatching {
+ api.activeSession().takeIf { it.code == 200 }?.data
+ }
+
+ suspend fun startOrContinue(taskNum: String): Result = runCatching {
+ envelope(api.startOrContinue(taskNum), "开始学习会话")
+ }
+
+ suspend fun sessionDetail(sessionNum: String): Result = runCatching {
+ envelope(api.sessionDetail(sessionNum), "获取会话")
+ }
+
+ suspend fun getExpectation(sessionNum: String): Result = runCatching {
+ api.getExpectation(sessionNum).takeIf { it.code == 200 }?.data?.description.orEmpty()
+ }
+
+ suspend fun putExpectation(sessionNum: String, description: String): Result = runCatching {
+ envelope(api.putExpectation(sessionNum, ExpectationRequest(description)), "保存学习预期")
+ Unit
+ }
+
+ suspend fun continueSession(sessionNum: String): Result = runCatching {
+ envelope(api.continueSession(sessionNum), "继续学习会话")
+ Unit
+ }
+
+ suspend fun pauseSession(sessionNum: String): Result = runCatching {
+ envelope(api.pauseSession(sessionNum), "暂停学习会话")
+ Unit
+ }
+
+ /** 结束会话;后端可能返回一条提示(如有效时间不足),作为 message 带回 */
+ suspend fun endSession(sessionNum: String, sections: ReportSections): Result = runCatching {
+ val env = api.endSession(
+ sessionNum,
+ EndSessionRequest(
+ content = sections.asLegacyContent(),
+ sessionSummary = sections.sessionSummary.ifBlank { null },
+ expectationVerdict = sections.expectationVerdict.ifBlank { null },
+ freeSummary = sections.freeSummary.ifBlank { null },
+ ),
+ )
+ if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "结束学习会话失败")
+ env.message
+ }
+
+ suspend fun abortSession(sessionNum: String, confirmation: String): Result = runCatching {
+ envelope(api.abortSession(sessionNum, AbortRequest(confirmation)), "误操作结束")
+ Unit
+ }
+
+ suspend fun createFragment(sessionNum: String, content: String): Result = runCatching {
+ envelope(
+ api.createFragment(CreateFragmentRequest(contextNum = sessionNum, sessionNum = sessionNum, content = content)),
+ "记录碎片",
+ )
+ Unit
+ }
+
+ suspend fun fragments(sessionNum: String): Result> = runCatching {
+ api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/data/Models.kt b/app/src/main/java/com/catshark/lpt/data/Models.kt
new file mode 100644
index 0000000..a92c2ed
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/data/Models.kt
@@ -0,0 +1,143 @@
+package com.catshark.lpt.data
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonElement
+
+/** lpt-be 的统一响应包装:{ code, message, data } */
+@Serializable
+data class ApiEnvelope(
+ val code: Int = 0,
+ val message: String? = null,
+ val data: T? = null,
+)
+
+@Serializable
+data class LoginRequest(
+ val username: String,
+ val password: String,
+)
+
+@Serializable
+data class TaskItem(
+ val id: Long = 0,
+ val taskNum: String = "",
+ val taskName: String = "",
+ val taskDescription: String? = null,
+ val materialUrl: String? = null,
+ val taskPriority: Double = 0.0,
+ val lastLearningStatus: String? = null,
+)
+
+@Serializable
+data class TaskPage(
+ val records: List = emptyList(),
+ val total: Int = 0,
+ val size: Int = 0,
+ val current: Int = 0,
+ val pages: Int = 0,
+)
+
+@Serializable
+data class SessionDetail(
+ val sessionNum: String = "",
+ val taskNum: String? = null,
+ val taskName: String? = null,
+ val taskId: Long? = null,
+ val materialUrl: String? = null,
+ val startTime: String? = null,
+ val lastStartTime: String? = null,
+ val endTime: String? = null,
+ val actualTime: Double = 0.0,
+ val effectiveTime: Double = 0.0,
+ val effectivenessRatio: Double = 0.0,
+ val sessionState: String = "",
+ val pointerPosition: Double = 0.0,
+ val systemMessage: String? = null,
+ val autoConverged: Boolean = false,
+)
+
+@Serializable
+data class ActiveSession(
+ val taskNum: String = "",
+ val sessionNum: String = "",
+ val taskName: String? = null,
+ val sessionState: String? = null,
+ val autoConverged: Boolean = false,
+)
+
+@Serializable
+data class Expectation(
+ val description: String = "",
+)
+
+@Serializable
+data class ExpectationRequest(
+ val description: String,
+)
+
+@Serializable
+data class EndSessionRequest(
+ /** 旧版后端(部署版)要的单段报告正文 */
+ val content: String? = null,
+ val sessionSummary: String? = null,
+ val expectationVerdict: String? = null,
+ val freeSummary: String? = null,
+)
+
+@Serializable
+data class AbortRequest(
+ val confirmation: String,
+)
+
+@Serializable
+data class CreateFragmentRequest(
+ /** 新版后端(本地源码)用 contextNum;旧版后端(部署版)用 sessionNum,两个都发 */
+ val contextNum: String,
+ val sessionNum: String,
+ val content: String,
+)
+
+@Serializable
+data class FragmentItem(
+ val id: Int = 0,
+ val contextNum: String = "",
+ val contextType: String = "SESSION",
+ val ownerTaskNum: String? = null,
+ val content: String = "",
+ val createdTime: String? = null,
+)
+
+/** 结束会话时提交的三段报告文本 */
+data class ReportSections(
+ val sessionSummary: String,
+ val expectationVerdict: String,
+ val freeSummary: String,
+) {
+ val allBlank: Boolean
+ get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank()
+
+ /**
+ * 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题,
+ * 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。
+ */
+ fun asLegacyContent(): String = buildString {
+ if (sessionSummary.isNotBlank()) appendLine("【会话摘要】$sessionSummary")
+ if (expectationVerdict.isNotBlank()) appendLine("【预期达成判断】$expectationVerdict")
+ if (freeSummary.isNotBlank()) appendLine("【自由总结】$freeSummary")
+ }.trim().ifBlank { "(在手机上结束了本次学习,未填写总结)" }
+}
+
+/** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */
+fun extractToken(element: JsonElement?): String? {
+ if (element == null) return null
+ return when {
+ element is JsonElement && element.toString().trim().startsWith("\"") ->
+ element.toString().trim().trim('"')
+ else -> {
+ val obj = element as? kotlinx.serialization.json.JsonObject
+ obj?.get("token")?.let { token ->
+ if (token.toString().trim().startsWith("\"")) token.toString().trim().trim('"') else token.toString()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/data/TokenStore.kt b/app/src/main/java/com/catshark/lpt/data/TokenStore.kt
new file mode 100644
index 0000000..a82f8cf
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/data/TokenStore.kt
@@ -0,0 +1,57 @@
+package com.catshark.lpt.data
+
+import android.content.Context
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStore
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+
+private val Context.dataStore by preferencesDataStore(name = "lpt_settings")
+
+/** 本地持久化:token / baseUrl / username */
+class TokenStore(private val context: Context) {
+
+ private val keyToken: Preferences.Key = stringPreferencesKey("token")
+ private val keyBaseUrl: Preferences.Key = stringPreferencesKey("base_url")
+ private val keyUsername: Preferences.Key = stringPreferencesKey("username")
+
+ val tokenFlow: Flow = context.dataStore.data.map { it[keyToken] }
+ val baseUrlFlow: Flow = context.dataStore.data.map { it[keyBaseUrl] ?: ApiClient.DEFAULT_BASE_URL }
+ val usernameFlow: Flow = context.dataStore.data.map { it[keyUsername] }
+
+ suspend fun load(): Settings = context.dataStore.data.first().let {
+ Settings(
+ token = it[keyToken],
+ baseUrl = it[keyBaseUrl] ?: ApiClient.DEFAULT_BASE_URL,
+ username = it[keyUsername],
+ )
+ }
+
+ suspend fun saveLogin(token: String, username: String, baseUrl: String) {
+ context.dataStore.edit {
+ it[keyToken] = token
+ it[keyUsername] = username
+ it[keyBaseUrl] = baseUrl
+ }
+ }
+
+ suspend fun saveBaseUrl(baseUrl: String) {
+ context.dataStore.edit { it[keyBaseUrl] = baseUrl }
+ }
+
+ suspend fun clearLogin() {
+ context.dataStore.edit {
+ it.remove(keyToken)
+ it.remove(keyUsername)
+ }
+ }
+
+ data class Settings(
+ val token: String?,
+ val baseUrl: String,
+ val username: String?,
+ )
+}
diff --git a/app/src/main/java/com/catshark/lpt/service/OverlayView.kt b/app/src/main/java/com/catshark/lpt/service/OverlayView.kt
new file mode 100644
index 0000000..d1e161c
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/service/OverlayView.kt
@@ -0,0 +1,426 @@
+package com.catshark.lpt.service
+
+import android.content.Context
+import android.graphics.Color
+import android.graphics.PixelFormat
+import android.graphics.Typeface
+import android.graphics.drawable.GradientDrawable
+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.WindowManager
+import android.widget.LinearLayout
+import android.widget.TextView
+import com.catshark.lpt.session.SessionController
+import com.catshark.lpt.util.formatDuration
+import kotlin.math.abs
+
+/**
+ * 系统级悬浮窗(经典 View 实现)。
+ *
+ * 三种形态:
+ * - 浏览:完整条(任务名 + 计时 + 暂停 + 展开),FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
+ * - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
+ *
+ * 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
+ *
+ * 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
+ * 所以「+ 记一条碎片」回调给 Service,由它拉起 FragmentInputActivity。
+ */
+class OverlayView(private val context: Context) {
+
+ private val wm = context.getSystemService(WindowManager::class.java)
+
+ private var root: LinearLayout? = null
+ private var params: WindowManager.LayoutParams? = null
+ private var shown = false
+ private var expanded = false
+ private var halfHidden = false
+ private var lastState: SessionController.State? = null
+
+ private lateinit var headerRow: LinearLayout
+ private lateinit var dotView: View
+ private lateinit var nameView: TextView
+ private lateinit var timeView: TextView
+ private lateinit var pauseView: TextView
+ private lateinit var expandView: TextView
+ private lateinit var compactView: LinearLayout
+ private lateinit var compactDot: View
+ private lateinit var compactTime: TextView
+ private lateinit var expandedPanel: LinearLayout
+ private lateinit var expectationView: TextView
+ private lateinit var fragmentView: TextView
+ private lateinit var latestFragmentView: TextView
+ private lateinit var addFragmentView: TextView
+ private lateinit var endView: TextView
+ private lateinit var openAppView: TextView
+ private lateinit var hideView: TextView
+
+ var onTogglePause: (() -> Unit)? = null
+ var onEnd: (() -> Unit)? = null
+ var onOpenApp: (() -> Unit)? = null
+ var onRequestFragmentInput: (() -> Unit)? = null
+
+ val isShown: Boolean get() = shown
+
+ private val autoHideTask = Runnable {
+ if (shown && !expanded) setHalfHidden(true)
+ }
+
+ private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
+
+ private fun rounded(color: Int, radiusDp: Int): GradientDrawable = 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
+ }
+
+ private fun label(text: String, color: Int, size: Float = 12f): TextView = TextView(context).apply {
+ this.text = text
+ textSize = size
+ setTextColor(color)
+ maxLines = 2
+ ellipsize = TextUtils.TruncateAt.END
+ }
+
+ fun show() {
+ if (shown) return
+ if (!Settings.canDrawOverlays(context)) return
+ val view = buildRoot()
+ val p = createParams()
+ root = view
+ params = p
+ runCatching { wm.addView(view, p) }.onFailure {
+ root = null
+ params = null
+ return
+ }
+ shown = true
+ scheduleAutoHide()
+ }
+
+ /** 彻底移除(仅在会话结束/服务停止时调用) */
+ fun hide() {
+ if (!shown) return
+ cancelAutoHide()
+ root?.let { runCatching { wm.removeView(it) } }
+ root = null
+ params = null
+ shown = false
+ }
+
+ /** 恢复/重建浮窗(App 内「显示悬浮窗」入口) */
+ fun restore() {
+ if (!shown) {
+ show()
+ return
+ }
+ if (halfHidden) setHalfHidden(false)
+ scheduleAutoHide()
+ }
+
+ fun render(state: SessionController.State) {
+ lastState = state
+ if (!shown) return
+ val ongoing = state.status == SessionController.Status.ONGOING
+ val text = formatDuration(state.effectiveSeconds())
+
+ nameView.text = state.taskName?.takeIf { it.isNotBlank() } ?: "学习会话"
+ 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)
+ pauseView.text = if (ongoing) "暂停" else "继续"
+ pauseView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
+
+ expectationView.text =
+ if (state.expectation.isBlank()) "预期:未填写" else "预期:${state.expectation}"
+ fragmentView.text = "本次碎片 ${state.fragments.size} 条"
+ latestFragmentView.text = state.fragments.lastOrNull()?.content?.let { "最新:$it" } ?: ""
+
+ headerRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
+ compactView.visibility = if (halfHidden) View.VISIBLE else View.GONE
+ expandedPanel.visibility = if (!halfHidden && expanded) View.VISIBLE else View.GONE
+ expandView.text = if (expanded) "▴" else "▾"
+ }
+
+ private fun toggleExpanded() {
+ expanded = !expanded
+ lastState?.let { render(it) }
+ scheduleAutoHide()
+ }
+
+ // ---- 半隐藏 / 自动隐藏 ----
+
+ fun setHalfHidden(hidden: Boolean) {
+ val view = root ?: return
+ val p = params ?: return
+ if (hidden) expanded = false
+ halfHidden = hidden
+ view.alpha = if (hidden) 0.6f 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) }
+ }
+ }
+
+ private fun scheduleAutoHide() {
+ root?.removeCallbacks(autoHideTask)
+ if (!halfHidden && !expanded) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
+ }
+
+ private fun cancelAutoHide() {
+ root?.removeCallbacks(autoHideTask)
+ }
+
+ 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 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()
+ }
+
+ // ---- 完整条 ----
+ headerRow = 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))
+ }
+ nameView = TextView(context).apply {
+ setTextColor(Color.WHITE)
+ textSize = 13f
+ maxLines = 1
+ ellipsize = TextUtils.TruncateAt.END
+ layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
+ .apply { marginStart = dp(8) }
+ }
+ timeView = TextView(context).apply {
+ setTextColor(Color.WHITE)
+ textSize = 16f
+ typeface = Typeface.MONOSPACE
+ setPadding(dp(8), 0, dp(8), 0)
+ }
+ pauseView = pill("暂停", COLOR_ACTION)
+ expandView = pill("▾", COLOR_NEUTRAL).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ ).apply { marginStart = dp(6) }
+ }
+ headerRow.addView(dotView)
+ headerRow.addView(nameView)
+ headerRow.addView(timeView)
+ headerRow.addView(pauseView)
+ headerRow.addView(expandView)
+ container.addView(headerRow)
+
+ // ---- 半隐藏小胶囊 ----
+ compactView = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ visibility = View.GONE
+ setPadding(dp(4), dp(2), dp(4), dp(2))
+ isClickable = true
+ }
+ compactDot = View(context).apply {
+ background = rounded(COLOR_ONGOING, 4)
+ layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
+ }
+ compactTime = TextView(context).apply {
+ setTextColor(Color.WHITE)
+ textSize = 14f
+ typeface = Typeface.MONOSPACE
+ setPadding(dp(6), 0, 0, 0)
+ }
+ compactView.addView(compactDot)
+ compactView.addView(compactTime)
+ compactView.setOnClickListener { setHalfHidden(false) }
+ container.addView(compactView)
+
+ // ---- 展开面板 ----
+ expandedPanel = LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ visibility = View.GONE
+ }
+ expectationView = label("预期:", Color.parseColor("#C9D1D9")).apply {
+ setPadding(0, dp(10), 0, dp(2))
+ }
+ fragmentView = label("本次碎片 0 条", Color.parseColor("#8B949E"), 12f)
+ latestFragmentView = label("", Color.parseColor("#8B949E"), 12f)
+
+ addFragmentView = pill("+ 记一条碎片", COLOR_ACTION).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ ).apply { topMargin = dp(8) }
+ }
+ addFragmentView.setOnClickListener {
+ // 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
+ setHalfHidden(true)
+ onRequestFragmentInput?.invoke()
+ }
+
+ val actions = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ setPadding(0, dp(10), 0, 0)
+ }
+ endView = pill("结束", COLOR_END)
+ openAppView = pill("打开 App", COLOR_NEUTRAL).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ ).apply { marginStart = dp(8) }
+ }
+ hideView = pill("隐藏", COLOR_NEUTRAL).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT,
+ ).apply { marginStart = dp(8) }
+ }
+ actions.addView(endView)
+ actions.addView(openAppView)
+ actions.addView(hideView)
+
+ expandedPanel.addView(expectationView)
+ expandedPanel.addView(fragmentView)
+ expandedPanel.addView(latestFragmentView)
+ expandedPanel.addView(addFragmentView)
+ expandedPanel.addView(actions)
+ container.addView(expandedPanel)
+
+ pauseView.setOnClickListener {
+ scheduleAutoHide()
+ onTogglePause?.invoke()
+ }
+ expandView.setOnClickListener { toggleExpanded() }
+ endView.setOnClickListener {
+ scheduleAutoHide()
+ onEnd?.invoke()
+ }
+ openAppView.setOnClickListener {
+ scheduleAutoHide()
+ onOpenApp?.invoke()
+ }
+ hideView.setOnClickListener { setHalfHidden(true) }
+
+ attachDrag(headerRow)
+ 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) {
+ MotionEvent.ACTION_DOWN -> {
+ startX = p.x
+ startY = p.y
+ downRawX = event.rawX
+ downRawY = event.rawY
+ moved = false
+ cancelAutoHide()
+ 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) } }
+ }
+ true
+ }
+
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
+ if (moved) {
+ scheduleAutoHide()
+ } else {
+ setHalfHidden(!halfHidden)
+ }
+ 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
+ }
+ 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)
+ }
+ }
+
+ 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_END = 0xFFB62324.toInt()
+ private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/service/StudySessionService.kt b/app/src/main/java/com/catshark/lpt/service/StudySessionService.kt
new file mode 100644
index 0000000..a93d57e
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/service/StudySessionService.kt
@@ -0,0 +1,242 @@
+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() }
+ onEnd = { openApp(openEnd = true) }
+ onOpenApp = { openApp(openEnd = false) }
+ onRequestFragmentInput = { openFragmentInput() }
+ }
+ createChannel()
+
+ // 状态变化:更新通知 / 悬浮窗;会话没了就停服务
+ scope.launch {
+ controller.state.collect { state ->
+ if (!state.hasSession) {
+ overlay.hide()
+ 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()
+ }
+ // 必须在 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))
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/session/SessionController.kt b/app/src/main/java/com/catshark/lpt/session/SessionController.kt
new file mode 100644
index 0000000..a048d62
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/session/SessionController.kt
@@ -0,0 +1,234 @@
+package com.catshark.lpt.session
+
+import android.os.SystemClock
+import com.catshark.lpt.data.FragmentItem
+import com.catshark.lpt.data.LptRepository
+import com.catshark.lpt.data.ReportSections
+import com.catshark.lpt.data.SessionDetail
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import java.time.Duration
+import java.time.LocalDateTime
+
+/**
+ * 学习会话状态机(Application 级单例)。
+ *
+ * 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。
+ * 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
+ */
+class SessionController(
+ private val repo: LptRepository,
+ private val scope: CoroutineScope,
+) {
+
+ enum class Status { NONE, ONGOING, PAUSED, ENDED }
+
+ data class State(
+ val sessionNum: String? = null,
+ val taskNum: String? = null,
+ val taskName: String? = null,
+ val status: Status = Status.NONE,
+ val baseEffectiveSeconds: Double = 0.0,
+ val anchorRealtimeMs: Long = 0L,
+ val expectation: String = "",
+ val fragments: List = emptyList(),
+ val busy: Boolean = false,
+ val error: String? = null,
+ val notice: String? = null,
+ ) {
+ val hasSession: Boolean
+ get() = status == Status.ONGOING || status == Status.PAUSED
+
+ fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
+ if (status == Status.ONGOING) {
+ baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
+ } else {
+ baseEffectiveSeconds
+ }
+ }
+
+ private val _state = MutableStateFlow(State())
+ val state: StateFlow = _state.asStateFlow()
+
+ fun consumeError() = _state.update { it.copy(error = null) }
+
+ fun consumeNotice() = _state.update { it.copy(notice = null) }
+
+ /** 启动或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务) */
+ fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
+ if (_state.value.busy) return
+ _state.update { it.copy(busy = true, error = null) }
+ scope.launch {
+ repo.startOrContinue(taskNum)
+ .onSuccess { detail ->
+ applyDetail(detail)
+ loadAuxiliary(detail.sessionNum)
+ _state.update { it.copy(busy = false) }
+ onSuccess()
+ }
+ .onFailure { e ->
+ _state.update { it.copy(busy = false, error = e.message ?: "开始学习会话失败") }
+ }
+ }
+ }
+
+ fun pause() {
+ val num = _state.value.sessionNum ?: return
+ if (_state.value.busy) return
+ _state.update { it.copy(busy = true) }
+ scope.launch {
+ repo.pauseSession(num)
+ .onSuccess { refreshDetail(num) }
+ .onFailure { e -> _state.update { it.copy(error = e.message ?: "暂停失败") } }
+ _state.update { it.copy(busy = false) }
+ }
+ }
+
+ fun resume() {
+ val num = _state.value.sessionNum ?: return
+ if (_state.value.busy) return
+ _state.update { it.copy(busy = true) }
+ scope.launch {
+ repo.continueSession(num)
+ .onSuccess { refreshDetail(num) }
+ .onFailure { e -> _state.update { it.copy(error = e.message ?: "继续失败") } }
+ _state.update { it.copy(busy = false) }
+ }
+ }
+
+ fun saveExpectation(text: String) {
+ val num = _state.value.sessionNum ?: return
+ scope.launch {
+ repo.putExpectation(num, text)
+ .onSuccess {
+ _state.update { it.copy(expectation = text, notice = "学习预期已保存") }
+ }
+ .onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } }
+ }
+ }
+
+ fun addFragment(content: String) {
+ val num = _state.value.sessionNum ?: return
+ if (content.isBlank()) return
+ scope.launch {
+ repo.createFragment(num, content)
+ .onSuccess {
+ repo.fragments(num).onSuccess { list ->
+ _state.update { it.copy(fragments = list, notice = "已记录一条碎片") }
+ }
+ }
+ .onFailure { e -> _state.update { it.copy(error = e.message ?: "记录碎片失败") } }
+ }
+ }
+
+ fun end(sections: ReportSections, onDone: () -> Unit = {}) {
+ val num = _state.value.sessionNum ?: return
+ if (_state.value.busy) return
+ _state.update { it.copy(busy = true) }
+ scope.launch {
+ repo.endSession(num, sections)
+ .onSuccess { message ->
+ _state.value = State(notice = message ?: "学习会话已结束")
+ onDone()
+ }
+ .onFailure { e ->
+ _state.update { it.copy(busy = false, error = e.message ?: "结束学习会话失败") }
+ }
+ }
+ }
+
+ fun abort(confirmation: String, onDone: () -> Unit = {}) {
+ val num = _state.value.sessionNum ?: return
+ if (_state.value.busy) return
+ _state.update { it.copy(busy = true) }
+ scope.launch {
+ repo.abortSession(num, confirmation)
+ .onSuccess {
+ _state.value = State(notice = "已放弃该会话,未产生任何数据")
+ onDone()
+ }
+ .onFailure { e ->
+ _state.update { it.copy(busy = false, error = e.message ?: "放弃会话失败") }
+ }
+ }
+ }
+
+ /** App 启动时与服务端对账:把未结束的会话恢复出来 */
+ fun reconcile() {
+ scope.launch {
+ repo.activeSession()
+ .onSuccess { active ->
+ if (active == null || active.sessionNum.isBlank()) {
+ if (!_state.value.hasSession) _state.update { it.copy(status = Status.NONE) }
+ return@onSuccess
+ }
+ // 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
+ _state.update {
+ it.copy(
+ sessionNum = active.sessionNum,
+ taskNum = active.taskNum.ifBlank { it.taskNum },
+ taskName = active.taskName ?: it.taskName,
+ )
+ }
+ refreshDetail(active.sessionNum)
+ loadAuxiliary(active.sessionNum)
+ }
+ }
+ }
+
+ fun clear() {
+ _state.value = State()
+ }
+
+ // ---- 内部 ----
+
+ private suspend fun refreshDetail(sessionNum: String) {
+ repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
+ }
+
+ private suspend fun loadAuxiliary(sessionNum: String) {
+ repo.getExpectation(sessionNum).onSuccess { text ->
+ _state.update { it.copy(expectation = text) }
+ }
+ repo.fragments(sessionNum).onSuccess { list ->
+ _state.update { it.copy(fragments = list) }
+ }
+ }
+
+ private fun applyDetail(detail: SessionDetail) {
+ val status = when (detail.sessionState) {
+ "ONGOING" -> Status.ONGOING
+ "PAUSED" -> Status.PAUSED
+ "ENDED" -> Status.ENDED
+ else -> Status.NONE
+ }
+ val anchor = if (status == Status.ONGOING) {
+ SystemClock.elapsedRealtime() - secondsSince(detail.lastStartTime) * 1000L
+ } else {
+ SystemClock.elapsedRealtime()
+ }
+ _state.update {
+ it.copy(
+ sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
+ taskNum = detail.taskNum ?: it.taskNum,
+ taskName = detail.taskName ?: it.taskName,
+ status = status,
+ baseEffectiveSeconds = detail.effectiveTime,
+ anchorRealtimeMs = anchor,
+ error = null,
+ )
+ }
+ }
+
+ private fun secondsSince(iso: String?): Long {
+ if (iso.isNullOrBlank()) return 0
+ return runCatching {
+ val start = LocalDateTime.parse(iso)
+ Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
+ }.getOrDefault(0)
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/FragmentInputActivity.kt b/app/src/main/java/com/catshark/lpt/ui/FragmentInputActivity.kt
new file mode 100644
index 0000000..bd0dc55
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/FragmentInputActivity.kt
@@ -0,0 +1,117 @@
+package com.catshark.lpt.ui
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.unit.dp
+import com.catshark.lpt.LptApp
+import com.catshark.lpt.ui.theme.LptTheme
+
+/**
+ * 从悬浮窗拉起的一条碎片输入弹窗。
+ *
+ * 之所以不复用悬浮窗内输入:App 不在前台时,系统不允许后台窗口弹软键盘
+ * (实测浮窗的 EditText 能拿到输入连接,但 IME 窗口 mViewVisibility=GONE)。
+ * 带 SYSTEM_ALERT_WINDOW 的 App 有后台启动 Activity 的豁免,所以这里用 Activity 输入。
+ */
+class FragmentInputActivity : ComponentActivity() {
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContent {
+ LptTheme {
+ FragmentInputDialog(
+ sessionNum = (application as LptApp).container.session.state.value.sessionNum,
+ onSubmit = { text ->
+ (application as LptApp).container.session.addFragment(text)
+ finish()
+ },
+ onDismiss = { finish() },
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun FragmentInputDialog(
+ sessionNum: String?,
+ onSubmit: (String) -> Unit,
+ onDismiss: () -> Unit,
+) {
+ var text by remember { mutableStateOf("") }
+ val focusRequester = remember { FocusRequester() }
+ val context = LocalContext.current
+
+ LaunchedEffect(Unit) { focusRequester.requestFocus() }
+
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(20.dp),
+ shape = RoundedCornerShape(18.dp),
+ color = MaterialTheme.colorScheme.surface,
+ tonalElevation = 6.dp,
+ shadowElevation = 12.dp,
+ ) {
+ Column(modifier = Modifier.padding(18.dp)) {
+ Text("记一条知识碎片", style = MaterialTheme.typography.titleMedium)
+ Spacer(Modifier.height(4.dp))
+ Text(
+ sessionNum?.let { "归属会话:$it" } ?: "当前没有进行中的会话",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(12.dp))
+ OutlinedTextField(
+ value = text,
+ onValueChange = { text = it },
+ label = { Text("这条碎片记了什么?") },
+ minLines = 2,
+ maxLines = 4,
+ modifier = Modifier
+ .fillMaxWidth()
+ .focusRequester(focusRequester),
+ )
+ Spacer(Modifier.height(14.dp))
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.End,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ TextButton(onClick = onDismiss) { Text("取消") }
+ Spacer(Modifier.height(0.dp))
+ Button(
+ onClick = { onSubmit(text.trim()) },
+ enabled = text.isNotBlank() && sessionNum != null,
+ modifier = Modifier.padding(start = 8.dp),
+ ) { Text("保存") }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/LoginScreen.kt b/app/src/main/java/com/catshark/lpt/ui/LoginScreen.kt
new file mode 100644
index 0000000..d9376f8
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/LoginScreen.kt
@@ -0,0 +1,132 @@
+package com.catshark.lpt.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.unit.dp
+
+@Composable
+fun LoginScreen(
+ initialBaseUrl: String,
+ onLogin: (username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) -> Unit,
+) {
+ var username by remember { mutableStateOf("") }
+ var password by remember { mutableStateOf("") }
+ var baseUrl by remember { mutableStateOf(initialBaseUrl) }
+ var showAdvanced by remember { mutableStateOf(false) }
+ var loading by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf(null) }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(24.dp),
+ verticalArrangement = Arrangement.Center,
+ ) {
+ Text("LPT 学习", style = MaterialTheme.typography.headlineMedium)
+ Spacer(Modifier.height(4.dp))
+ Text(
+ "移动端学习会话 · 悬浮窗计时",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(24.dp))
+
+ OutlinedTextField(
+ value = username,
+ onValueChange = { username = it },
+ label = { Text("账号") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Spacer(Modifier.height(12.dp))
+ OutlinedTextField(
+ value = password,
+ onValueChange = { password = it },
+ label = { Text("密码") },
+ singleLine = true,
+ visualTransformation = PasswordVisualTransformation(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ modifier = Modifier.fillMaxWidth(),
+ )
+
+ if (showAdvanced) {
+ Spacer(Modifier.height(12.dp))
+ OutlinedTextField(
+ value = baseUrl,
+ onValueChange = { baseUrl = it },
+ label = { Text("API 地址") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ } else {
+ TextButton(onClick = { showAdvanced = true }) { Text("高级:修改 API 地址") }
+ }
+
+ if (error != null) {
+ Spacer(Modifier.height(8.dp))
+ Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
+ }
+
+ Spacer(Modifier.height(20.dp))
+ Button(
+ onClick = {
+ error = null
+ loading = true
+ onLogin(username.trim(), password, baseUrl.trim()) { message ->
+ loading = false
+ error = message
+ }
+ },
+ enabled = !loading && username.isNotBlank() && password.isNotBlank(),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ if (loading) {
+ CircularProgressIndicator(
+ modifier = Modifier.height(18.dp),
+ strokeWidth = 2.dp,
+ color = MaterialTheme.colorScheme.onPrimary,
+ )
+ } else {
+ Text("登录")
+ }
+ }
+ Spacer(Modifier.height(8.dp))
+ Text(
+ "提示:dev 环境默认 https://lpt-dev.cat-shark.xyz/api",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(24.dp))
+ Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ "LPT",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/PermissionScreen.kt b/app/src/main/java/com/catshark/lpt/ui/PermissionScreen.kt
new file mode 100644
index 0000000..18aa2c7
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/PermissionScreen.kt
@@ -0,0 +1,216 @@
+package com.catshark.lpt.ui
+
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.os.PowerManager
+import android.provider.Settings
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+
+@Composable
+fun PermissionScreen(onBack: () -> Unit) {
+ val context = LocalContext.current
+ var refreshKey by remember { mutableIntStateOf(0) }
+
+ // 从系统设置页返回时自动刷新权限状态
+ val lifecycleOwner = LocalLifecycleOwner.current
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) refreshKey++
+ }
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+
+ val overlayGranted = remember(refreshKey) { Settings.canDrawOverlays(context) }
+ val batteryIgnored = remember(refreshKey) { isIgnoringBatteryOptimizations(context) }
+ val notificationGranted = remember(refreshKey) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
+ android.content.pm.PackageManager.PERMISSION_GRANTED
+ } else {
+ true
+ }
+ }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text("权限与后台", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
+ TextButton(onClick = onBack) { Text("返回") }
+ }
+ Text(
+ "悬浮窗是核心功能:没有悬浮窗权限,跨应用计时就不成立。MIUI 还需要额外放行后台。",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+
+ PermissionCard(
+ title = "悬浮窗权限(必须)",
+ description = "允许 LPT 在其他应用之上显示学习计时浮窗。",
+ granted = overlayGranted,
+ actionLabel = "去开启",
+ onAction = { openOverlaySettings(context) },
+ )
+
+ PermissionCard(
+ title = "通知权限",
+ description = "前台服务需要一条常驻通知;Android 13+ 需要授权。",
+ granted = notificationGranted,
+ actionLabel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) "去开启" else "无需(本机低于 13)",
+ onAction = { openAppNotificationSettings(context) },
+ )
+
+ PermissionCard(
+ title = "电池优化白名单",
+ description = "避免长时间学习时被系统冻结计时。",
+ granted = batteryIgnored,
+ actionLabel = "去设置",
+ onAction = { requestIgnoreBatteryOptimizations(context) },
+ )
+
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Text("小米 / MIUI 额外设置", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
+ Spacer(Modifier.height(6.dp))
+ Text(
+ "MIUI 会限制后台启动与后台弹窗,需要手动放行「自启动」和「其他权限 → 后台弹出界面」,并把省电策略设为「无限制」。",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(10.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(onClick = { openMiuiAutostart(context) }) { Text("自启动管理") }
+ OutlinedButton(onClick = { openAppDetailSettings(context) }) { Text("应用详情") }
+ }
+ }
+ }
+
+ Button(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("完成") }
+ Spacer(Modifier.height(16.dp))
+ }
+}
+
+@Composable
+private fun PermissionCard(
+ title: String,
+ description: String,
+ granted: Boolean,
+ actionLabel: String,
+ onAction: () -> Unit,
+) {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
+ Text(
+ if (granted) "已授权" else "未授权",
+ style = MaterialTheme.typography.labelMedium,
+ color = if (granted) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.error,
+ )
+ }
+ Spacer(Modifier.height(4.dp))
+ Text(
+ description,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ if (!granted) {
+ Spacer(Modifier.height(8.dp))
+ Button(onClick = onAction) { Text(actionLabel) }
+ }
+ }
+ }
+}
+
+private fun openOverlaySettings(context: Context) {
+ val intent = Intent(
+ Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
+ Uri.parse("package:${context.packageName}"),
+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+ .onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) } }
+}
+
+private fun openAppNotificationSettings(context: Context) {
+ val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
+ .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+ .onFailure { openAppDetailSettings(context) }
+}
+
+private fun openAppDetailSettings(context: Context) {
+ val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
+ .setData(Uri.parse("package:${context.packageName}"))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+}
+
+private fun requestIgnoreBatteryOptimizations(context: Context) {
+ val intent = Intent(
+ Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
+ Uri.parse("package:${context.packageName}"),
+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+ .onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } }
+}
+
+private fun openMiuiAutostart(context: Context) {
+ val candidates = listOf(
+ ComponentName(
+ "com.miui.securitycenter",
+ "com.miui.permcenter.autostart.AutoStartManagementActivity",
+ ),
+ ComponentName(
+ "com.miui.securitycenter",
+ "com.miui.powercenter.PowerSettings",
+ ),
+ )
+ for (component in candidates) {
+ val intent = Intent().setComponent(component).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ if (runCatching { context.startActivity(intent) }.isSuccess) return
+ }
+ openAppDetailSettings(context)
+}
+
+private fun isIgnoringBatteryOptimizations(context: Context): Boolean {
+ val powerManager = context.getSystemService(PowerManager::class.java) ?: return false
+ return powerManager.isIgnoringBatteryOptimizations(context.packageName)
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/SessionScreen.kt b/app/src/main/java/com/catshark/lpt/ui/SessionScreen.kt
new file mode 100644
index 0000000..efd6b0d
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/SessionScreen.kt
@@ -0,0 +1,374 @@
+package com.catshark.lpt.ui
+
+import android.os.SystemClock
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.catshark.lpt.data.ReportSections
+import com.catshark.lpt.session.SessionController
+import com.catshark.lpt.util.formatDuration
+import kotlinx.coroutines.delay
+
+private const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
+
+@Composable
+fun SessionScreen(
+ state: SessionController.State,
+ openEndDialog: Boolean,
+ onConsumeOpenEnd: () -> Unit,
+ onTogglePause: () -> Unit,
+ onEnd: (ReportSections) -> Unit,
+ onAbort: (String) -> Unit,
+ onSaveExpectation: (String) -> Unit,
+ onAddFragment: (String) -> Unit,
+ onShowOverlay: () -> Unit,
+ onBack: () -> Unit,
+) {
+ var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
+ LaunchedEffect(state.status) {
+ while (true) {
+ delay(1000)
+ nowMs = SystemClock.elapsedRealtime()
+ }
+ }
+ val seconds = state.effectiveSeconds(nowMs)
+ val ongoing = state.status == SessionController.Status.ONGOING
+
+ var expectationDraft by remember { mutableStateOf(state.expectation) }
+ LaunchedEffect(state.expectation) { expectationDraft = state.expectation }
+
+ var fragmentDraft by remember { mutableStateOf("") }
+ var showEnd by remember { mutableStateOf(false) }
+ var showAbort by remember { mutableStateOf(false) }
+
+ LaunchedEffect(openEndDialog) {
+ if (openEndDialog) {
+ showEnd = true
+ onConsumeOpenEnd()
+ }
+ }
+
+ Column(modifier = Modifier.fillMaxSize()) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ TextButton(onClick = onBack) { Text("‹ 任务") }
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ state.taskName ?: "学习会话",
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ )
+ Text(
+ state.sessionNum ?: "",
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ if (state.busy) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
+ }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(horizontal = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ // 计时卡片
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(20.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(
+ if (ongoing) "有效学习时间" else "已暂停 · 有效学习时间",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(6.dp))
+ Text(
+ formatDuration(seconds),
+ fontSize = 44.sp,
+ fontFamily = FontFamily.Monospace,
+ fontWeight = FontWeight.Bold,
+ color = if (ongoing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ "状态:${statusLabel(state.status)}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+
+ // 控制按钮
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
+ Button(
+ onClick = onTogglePause,
+ enabled = !state.busy,
+ modifier = Modifier.weight(1f),
+ ) {
+ Text(if (ongoing) "暂停" else "继续")
+ }
+ Button(
+ onClick = { showEnd = true },
+ enabled = !state.busy,
+ modifier = Modifier.weight(1f),
+ ) {
+ Text("结束")
+ }
+ }
+ OutlinedButton(
+ onClick = { showAbort = true },
+ enabled = !state.busy && state.fragments.isEmpty(),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Text(if (state.fragments.isEmpty()) "误操作结束(零数据)" else "误操作结束(已产生碎片,不可用)")
+ }
+ OutlinedButton(
+ onClick = onShowOverlay,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Text("显示 / 恢复悬浮窗")
+ }
+
+ // 学习预期
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Text("本次学习预期", style = MaterialTheme.typography.titleSmall)
+ Spacer(Modifier.height(8.dp))
+ OutlinedTextField(
+ value = expectationDraft,
+ onValueChange = { expectationDraft = it },
+ label = { Text("开始前写下这次想学会什么") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Spacer(Modifier.height(8.dp))
+ Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
+ Button(onClick = { onSaveExpectation(expectationDraft) }) { Text("保存预期") }
+ }
+ }
+ }
+
+ // 碎片
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Text("知识碎片(${state.fragments.size})", style = MaterialTheme.typography.titleSmall)
+ Spacer(Modifier.height(8.dp))
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ OutlinedTextField(
+ value = fragmentDraft,
+ onValueChange = { fragmentDraft = it },
+ label = { Text("记一条…") },
+ singleLine = true,
+ modifier = Modifier.weight(1f),
+ )
+ Spacer(Modifier.height(0.dp))
+ TextButton(
+ onClick = {
+ onAddFragment(fragmentDraft)
+ fragmentDraft = ""
+ },
+ enabled = fragmentDraft.isNotBlank(),
+ ) { Text("记录") }
+ }
+ state.fragments.forEachIndexed { index, fragment ->
+ Spacer(Modifier.height(8.dp))
+ Row {
+ Text(
+ "${index + 1}.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(0.dp))
+ Text(
+ fragment.content,
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.padding(start = 6.dp),
+ )
+ }
+ }
+ }
+ }
+
+ if (state.error != null) {
+ Text(state.error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
+ }
+ if (state.notice != null) {
+ Text(state.notice, color = MaterialTheme.colorScheme.secondary, style = MaterialTheme.typography.bodySmall)
+ }
+ Spacer(Modifier.height(24.dp))
+ }
+ }
+
+ if (showEnd) {
+ EndSessionDialog(
+ defaultSummary = "",
+ busy = state.busy,
+ onDismiss = { showEnd = false },
+ onConfirm = { sections ->
+ showEnd = false
+ onEnd(sections)
+ },
+ )
+ }
+
+ if (showAbort) {
+ AbortSessionDialog(
+ busy = state.busy,
+ onDismiss = { showAbort = false },
+ onConfirm = { phrase ->
+ showAbort = false
+ onAbort(phrase)
+ },
+ )
+ }
+}
+
+@Composable
+private fun EndSessionDialog(
+ defaultSummary: String,
+ busy: Boolean,
+ onDismiss: () -> Unit,
+ onConfirm: (ReportSections) -> Unit,
+) {
+ var summary by remember { mutableStateOf(defaultSummary) }
+ var verdict by remember { mutableStateOf("") }
+ var free by remember { mutableStateOf("") }
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("结束本次学习") },
+ text = {
+ Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
+ Text(
+ "三段都可留空,但至少要写一段。全空时会记为「未填写总结」。",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedTextField(
+ value = summary,
+ onValueChange = { summary = it },
+ label = { Text("会话摘要(这次实际学了什么)") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedTextField(
+ value = verdict,
+ onValueChange = { verdict = it },
+ label = { Text("预期达成判断") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedTextField(
+ value = free,
+ onValueChange = { free = it },
+ label = { Text("自由总结") },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ },
+ confirmButton = {
+ Button(
+ onClick = {
+ val sections = if (summary.isBlank() && verdict.isBlank() && free.isBlank()) {
+ ReportSections("", "", "(在手机上结束了本次学习,未填写总结)")
+ } else {
+ ReportSections(summary, verdict, free)
+ }
+ onConfirm(sections)
+ },
+ enabled = !busy,
+ ) { Text("确认结束") }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
+ )
+}
+
+@Composable
+private fun AbortSessionDialog(
+ busy: Boolean,
+ onDismiss: () -> Unit,
+ onConfirm: (String) -> Unit,
+) {
+ var phrase by remember { mutableStateOf("") }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("误操作结束") },
+ text = {
+ Column {
+ Text(
+ "此操作会删除本次会话与学习预期,不产生碎片和报告,且不可恢复。",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ )
+ Spacer(Modifier.height(10.dp))
+ Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
+ Spacer(Modifier.height(8.dp))
+ OutlinedTextField(
+ value = phrase,
+ onValueChange = { phrase = it },
+ label = { Text("确认语") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ }
+ },
+ confirmButton = {
+ Button(
+ onClick = { onConfirm(phrase) },
+ enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
+ ) { Text("确认放弃") }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
+ )
+}
+
+private fun statusLabel(status: SessionController.Status): String = when (status) {
+ SessionController.Status.ONGOING -> "进行中"
+ SessionController.Status.PAUSED -> "已暂停"
+ SessionController.Status.ENDED -> "已结束"
+ SessionController.Status.NONE -> "无"
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/SettingsScreen.kt b/app/src/main/java/com/catshark/lpt/ui/SettingsScreen.kt
new file mode 100644
index 0000000..e11ec62
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/SettingsScreen.kt
@@ -0,0 +1,74 @@
+package com.catshark.lpt.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+
+@Composable
+fun SettingsScreen(
+ baseUrl: String,
+ onSave: (String) -> Unit,
+ onLogout: () -> Unit,
+ onBack: () -> Unit,
+) {
+ var draft by remember { mutableStateOf(baseUrl) }
+ var saved by remember { mutableStateOf(false) }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text("设置", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
+ TextButton(onClick = onBack) { Text("返回") }
+ }
+
+ OutlinedTextField(
+ value = draft,
+ onValueChange = {
+ draft = it
+ saved = false
+ },
+ label = { Text("API 地址") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth(),
+ )
+ Text(
+ "例如 https://lpt-dev.cat-shark.xyz/api",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Button(
+ onClick = {
+ onSave(draft.trim())
+ saved = true
+ },
+ modifier = Modifier.fillMaxWidth(),
+ ) { Text(if (saved) "已保存" else "保存") }
+
+ Spacer(Modifier.height(8.dp))
+ TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
+ Text("退出登录", color = MaterialTheme.colorScheme.error)
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/TaskListScreen.kt b/app/src/main/java/com/catshark/lpt/ui/TaskListScreen.kt
new file mode 100644
index 0000000..49ea615
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/TaskListScreen.kt
@@ -0,0 +1,144 @@
+package com.catshark.lpt.ui
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.Card
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import com.catshark.lpt.data.TaskItem
+
+@Composable
+fun TaskListScreen(
+ tasks: List,
+ loading: Boolean,
+ error: String?,
+ username: String?,
+ onRefresh: () -> Unit,
+ onStart: (TaskItem) -> Unit,
+ onOpenSettings: () -> Unit,
+ onOpenPermissions: () -> Unit,
+ onLogout: () -> Unit,
+) {
+ Column(modifier = Modifier.fillMaxSize()) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text("学习任务", style = MaterialTheme.typography.titleLarge)
+ Text(
+ username?.let { "已登录:$it" } ?: "",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ TextButton(onClick = onOpenPermissions) { Text("权限") }
+ TextButton(onClick = onOpenSettings) { Text("设置") }
+ }
+
+ if (error != null) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ error,
+ color = MaterialTheme.colorScheme.error,
+ style = MaterialTheme.typography.bodySmall,
+ modifier = Modifier.weight(1f),
+ )
+ TextButton(onClick = onRefresh) { Text("重试") }
+ }
+ }
+
+ if (loading && tasks.isEmpty()) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ return@Column
+ }
+
+ if (tasks.isEmpty() && !loading) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text("还没有学习任务", style = MaterialTheme.typography.bodyLarge)
+ Spacer(Modifier.height(8.dp))
+ TextButton(onClick = onRefresh) { Text("刷新") }
+ }
+ }
+ return@Column
+ }
+
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ items(tasks, key = { it.taskNum }) { task ->
+ Card(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { onStart(task) },
+ ) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Text(
+ task.taskName,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ )
+ if (!task.taskDescription.isNullOrBlank()) {
+ Spacer(Modifier.height(4.dp))
+ Text(
+ task.taskDescription,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 2,
+ )
+ }
+ Spacer(Modifier.height(8.dp))
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ "优先级 %.2f".format(task.taskPriority),
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Spacer(Modifier.weight(1f))
+ Text(
+ "开始学习 ›",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ }
+ }
+ }
+ }
+ item {
+ Spacer(Modifier.height(4.dp))
+ TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
+ Text("退出登录", color = MaterialTheme.colorScheme.error)
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/catshark/lpt/ui/theme/Theme.kt b/app/src/main/java/com/catshark/lpt/ui/theme/Theme.kt
new file mode 100644
index 0000000..6476fbc
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/ui/theme/Theme.kt
@@ -0,0 +1,30 @@
+package com.catshark.lpt.ui.theme
+
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.material3.lightColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
+
+private val LightColors = lightColorScheme(
+ primary = Color(0xFF1F6FEB),
+ onPrimary = Color.White,
+ secondary = Color(0xFF238636),
+ error = Color(0xFFB62324),
+)
+
+private val DarkColors = darkColorScheme(
+ primary = Color(0xFF6EA8FE),
+ onPrimary = Color(0xFF0B1220),
+ secondary = Color(0xFF3FB950),
+ error = Color(0xFFF85149),
+)
+
+@Composable
+fun LptTheme(content: @Composable () -> Unit) {
+ MaterialTheme(
+ colorScheme = if (isSystemInDarkTheme()) DarkColors else LightColors,
+ content = content,
+ )
+}
diff --git a/app/src/main/java/com/catshark/lpt/util/Format.kt b/app/src/main/java/com/catshark/lpt/util/Format.kt
new file mode 100644
index 0000000..7acf79b
--- /dev/null
+++ b/app/src/main/java/com/catshark/lpt/util/Format.kt
@@ -0,0 +1,10 @@
+package com.catshark.lpt.util
+
+/** 把秒数格式化成 mm:ss 或 h:mm:ss */
+fun formatDuration(seconds: Double): String {
+ val total = seconds.toLong().coerceAtLeast(0)
+ val h = total / 3600
+ val m = (total % 3600) / 60
+ val s = total % 60
+ return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
+}
diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..74e851b
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..513eee6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_notification.xml b/app/src/main/res/drawable/ic_notification.xml
new file mode 100644
index 0000000..f1f4153
--- /dev/null
+++ b/app/src/main/res/drawable/ic_notification.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..6b78462
--- /dev/null
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml
new file mode 100644
index 0000000..f809301
--- /dev/null
+++ b/app/src/main/res/values-night/themes.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..2715645
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ LPT 学习
+
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..c97c120
--- /dev/null
+++ b/app/src/main/res/values/themes.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..132ad8d
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,6 @@
+plugins {
+ alias(libs.plugins.android.application) apply false
+ alias(libs.plugins.kotlin.android) apply false
+ alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.kotlin.serialization) apply false
+}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..e7694b7
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,10 @@
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+org.gradle.parallel=true
+org.gradle.caching=true
+# 项目位于 NTFS 挂载盘,关闭文件系统监视以避免 inotify 问题
+org.gradle.vfs.watch=false
+
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+
+kotlin.code.style=official
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 0000000..beb1299
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,39 @@
+[versions]
+agp = "8.13.2"
+kotlin = "2.3.21"
+coreKtx = "1.17.0"
+activityCompose = "1.12.2"
+lifecycle = "2.9.3"
+datastore = "1.1.7"
+# Compose 1.12.x 要求 AGP 9.1+ / compileSdk 37;这里用 1.10.6,配 AGP 8.13.2 + compileSdk 36
+composeBom = "2026.03.01"
+okhttp = "4.12.0"
+retrofit = "2.11.0"
+retrofitSerialization = "1.0.0"
+serializationJson = "1.7.3"
+coroutines = "1.10.2"
+
+[libraries]
+androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
+androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
+androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
+androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
+androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
+androidx-lifecycle-service = { group = "androidx.lifecycle", name = "lifecycle-service", version.ref = "lifecycle" }
+androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }
+androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
+androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
+androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
+androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
+androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
+okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
+retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
+retrofit-serialization = { group = "com.jakewharton.retrofit", name = "retrofit2-kotlinx-serialization-converter", version.ref = "retrofitSerialization" }
+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serializationJson" }
+kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
+
+[plugins]
+android-application = { id = "com.android.application", version.ref = "agp" }
+kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000000000000000000000000000000000000..02f06ab2a396743f0052e4328b0e5ac2cdd8b3d2
GIT binary patch
literal 44309
zcma&NV|b+9x-FcJQL*igZFOv$9jjs+osMnWwr!i8bXc)E=$L)-uC=fIoxS#1@3-o@
zo?lgeX3a6jm}A`IQIds#!~lbZg#`lxBmH>(zYhu+9GJYgnlOX3f&`PCw5Yg(s<^ru
z6xgS~ezK{f>%7j1PE`Rk&^SH+}Mohz9wp*#JH2nDr~C>p(x&dU3<
z0QLs;xWc`wK>A8ScwnIO(~LXPt&Go!#r&jG?GVh@ikWgvrmiO@vuw`nN4NJDl-_Z>
zq46g`F!-|bh##{-@Kk~Aij`(+MXJYu5c}dQJR@H@U%657h?n6
zHvq*dO{t){Px5Teg3f7`Gir9#3ph2R6fg%Wwlb{fuN^_+pw48sz~yz+T!a&`VBHEC
zn^@yQ8LZ!kW3A>JzlMcy-Nsmmk~?7aJ@^kfX{`?oo^&l`KlV9Cw1kQgpzC)d@j&&zHhrGr~h;XBF}%qHRR@sj{+gXpDY=D?@GF1=Ww
z^{?Qq4m_-xj}7HjVS(z8b8!n$IncQ=U!f*t7F$Yg5?&*B^FjqCL5N4Y-StJ1f9501`=PSuvNMG_O<*-!QAs_Z9MQ
z91OTpylb^ck-Wu6VJ;VY5=@U$cr2qn$2k=XqdUc}pAk_mcR*X;Poz*kpT4yEx0n0^
zq=h09Lq-SU_njU?I3%hwNAl76_&ECo}{uzv7bA+q_mUAR@?A5EQf)8$gWYE9k
zwpz*;gDevoXt}lA&DauXNZ`aRpy!V@_AYiLElxq-KnIqh4l+4p-ijM1|uOThHQdqCw?)Y$9?YFKHCSD
z#UX_FZK~;1IgySfqM!YXVh}h2KK_>g*vmuy%r53CrwQSrxI0Q4b37S%trGW+z^^mD
zeleq;N>8Pqv3Hkzw!Cnrx7;bVG!ZLx%1!(#^mQUInh*#J)ipRI#{w_daP1K0zdJ6B
zYkY+%wFV>8olJ-ji(ekITw*Jp!jzWsn244rt-(TU0Og7?^@^;^f{5M-JyH9-l9*|qY^WqtaUSBXR$p^04bWpqG
z4lahR;?Xh1%zhH>`BwI&air~f{{HQ{tUtAzZmy5@;{|rIPKqP$+X@&C_Hl5v4Rs6>
z)(=;)FC#O$28LMs5}M;mmZkm0rlc>OyTd9N^>o`1@08hKsIGyL_<2br40PJ@@a={8
zYG+Qcp&5L%^rV!_Qh%U3iRp+NlgFB!3bApcKfUyx``~es;s4PIdD7fqE}WT@X7~hfR*!Z`A_sEgOGy
z>f@F(K=sN?#AmvLO`~WhG&Fi|s#*_Y)&jo^M_oup0aJYAtAfURcLaOAxYJVn$=kVI
zVj#1a7-GKF`5Iw?cH{mlzn`IoF`JX)UA!?kSb9q%{hv?FnE2jJ`~71Be7v3#;otkL%EwT
zsfj-lMpZ)WWBP-QGQ1iRAs+91
z`qDfUf-WI$qXU(TZ%qHFXgMjn8R`~}FnS^X{vh1{pe7%YGy69t>JBoFwCP>bxr;D2
zihEnn&+pH2ze^^b7?6%5l+F%~wG024FzthtGnW*qLU)^B?knu(!tML)`6a_^?60hF
zKV$$xMyaR6Uc&_gkBTk#`=h=33OTJt#lh&Yk`%LcATbTVxhvqR+HR`d5>!7Q5e(LU
z7t}GXAPFg7Wk-WBgP$&&O`5YTBDkSss-vwzN-H?-Mxk4P8qnw;MDdyLAVGW?ipbyT
zY}cyvVP!9^*7cMdbBhr97Rc+62}ji3_j`;|3g4&^RVZc`78mh#dnkh6HnTlQFwj)o
zDtL^9rb(xGb+Q?lN45J*RChM2WKp}%k?Rs9wVvNoM)ZKcqk$+XHaAgje~xs0be@-R
zItZk?Mo*rvJK|hVgy9O8F(D3q<3o0(4?$@{?il0-UCf)UlMfBYNu;lKT#n&H9LTvd
zHfC4jk@QFOWj12vbU@4<-#V;~I1XZar(FZ~devG)N@sPGW`Sab4tE6tFVHlD(BfbDfxT
zA+>XUEPhIwa~;5?Pw!OwG<$%ro29D_U6U%`?ql!JFLNhdf)elzDJ~ld-1ZI+*)yu=
z#Ni7JA{!b4Wj1WEa3x->cbfvmGLT)la^gC7VtuoqWbrXEcGYVtyI)^{l8=etB(;em^Fg888
z&lwuRvqSuSF{Rg|A)Xgoy9MDYn!-)VA$M|M3eX1WbV^}@k~OR``|J%XaFgAAJByZ=
z1Ieh7;};QfzQUPg#q#pgyVvO&6uC3QYGj^muAI}d@L8K0@)ZuIo7}RWX`>z4aVLiq
z4vNszxc9xS++O9u9xB42I@s^CEbiGQ7S=%S8WTlAdCe+V$D_F3(%>BNa&t*e
z`*PvIJ7!eTI$b*ZN7nifh*h2r1&A~})d^mg)bC}5V2o(xQZr}?$z+vVCv0}tl91xy
z65(;EQ1L+x0>-ru*$D=_f=qK`^zVZ2!BQ9km=Vi}?qu7@NX%xz7WJdA?X>|rBm=J#zM
zjy5ImRTcl-Nc>-At^=~`IzHg
z(=B0!LYFdFy>rGeQO$IZv||aq+ti~@PRqS^t