feat(android): add reminders and background sync

- Add local overdue reminders with notification channel and tap-to-date\n- Extract shared sync engine for foreground and WorkManager sync\n- Schedule 15-minute sync/reminder work and restore tasks after boot\n- Request notification permission and document Android background limits
This commit is contained in:
Misaki
2026-10-26 21:02:55 +08:00
parent 082c1229f9
commit 121e66d527
21 changed files with 421 additions and 50 deletions
+2 -1
View File
@@ -135,7 +135,8 @@ Windows/macOS 使用 Qt 原生输入法支持,不需要该插件。
- 今日日程列表、完成状态、编辑、长按删除、新建。 - 今日日程列表、完成状态、编辑、长按删除、新建。
- SQLite outbox、LWW、WebSocket + 15 秒轮询、设备注册。 - SQLite outbox、LWW、WebSocket + 15 秒轮询、设备注册。
- 暂不含 AI 对话/附件、精力曲线、复盘和后台同步。 - 日程结束本地通知;WorkManager 每 15 分钟后台同步;开机重建任务。
- 暂不含 AI 对话/附件、精力曲线、复盘。
```bash ```bash
cd android cd android
+16 -2
View File
@@ -7,6 +7,8 @@
- 今日日程列表:按日期前后切换、完成状态、编辑、长按删除。 - 今日日程列表:按日期前后切换、完成状态、编辑、长按删除。
- 本地 SQLite:task / timeblock / outbox / sync_state。 - 本地 SQLite:task / timeblock / outbox / sync_state。
- 同步:设备注册、outbox 推送、增量拉取、LWW、WebSocket 通知、定时轮询。 - 同步:设备注册、outbox 推送、增量拉取、LWW、WebSocket 通知、定时轮询。
- 提醒:日程结束后对未完成项发本地通知;通知点击回到对应日期。
- 后台:WorkManager 每 15 分钟同步一次;开机接收 `BOOT_COMPLETED` 重新登记任务。
- 设置:同步服务地址与启用开关;不支持 AI 对话和附件提取(桌面端功能)。 - 设置:同步服务地址与启用开关;不支持 AI 对话和附件提取(桌面端功能)。
## 构建 ## 构建
@@ -45,8 +47,20 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
> App 允许明文 HTTP 以便局域网自部署测试;公网部署请使用 HTTPS 反向代理。 > App 允许明文 HTTP 以便局域网自部署测试;公网部署请使用 HTTPS 反向代理。
> Token 存在 SharedPreferences 中,明文保存;后续可接入 Android Keystore。 > Token 存在 SharedPreferences 中,明文保存;后续可接入 Android Keystore。
## 通知与后台同步
- 提醒使用 Android 本地通知,不依赖服务端推送/FCM。
- 通知在工作线程中检查过去 24 小时内已结束、仍未完成的日程;同一时间块只提醒一次。
- Android 13+ 首次启动会请求通知权限;拒绝后提醒不显示,但同步不受影响。
- WorkManager 周期最小为 15 分钟;省电模式/Doze 或厂商后台限制可能进一步延迟。
- 开机广播会重新安排提醒与同步任务;不会自动打开 App 界面。
- 如需即时后台推送,需要后续接入 FCM 或常驻前台服务(会增加耗电/复杂度)。
> 部分国产 ROM 需要手动允许「自启动」「后台运行」或关闭电池优化,否则开机任务和周期同步可能被系统拦截。
## 当前限制 ## 当前限制
- 无 AI 对话 / 文件附件 / 精力曲线 / 重复日程创建 / 每日复盘;这些仍由桌面端提供。 - 无 AI 对话 / 文件附件 / 精力曲线 / 重复日程创建 / 每日复盘;这些仍由桌面端提供。
- 无后台同步;Activity 进入后台后会停止同步,回到前台再恢复。 - 提醒不是精确闹钟:周期任务可能延迟,且没有“提前 N 分钟”提醒。
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建和 JVM 单元测试。 - 无 FCM 推送;App 被强制停止后,Android 不会执行周期任务,直到下次手动打开。
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建、JVM 单元测试和 Manifest 检查。
+1
View File
@@ -40,6 +40,7 @@ dependencies {
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
implementation("com.squareup.okhttp3:okhttp:4.12.0") implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("androidx.work:work-runtime-ktx:2.9.1")
testImplementation("junit:junit:4.13.2") testImplementation("junit:junit:4.13.2")
testImplementation("org.json:json:20240303") testImplementation("org.json:json:20240303")
+11
View File
@@ -3,6 +3,8 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application <application
android:allowBackup="true" android:allowBackup="true"
@@ -20,5 +22,14 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<receiver
android:name=".background.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application> </application>
</manifest> </manifest>
@@ -1,8 +1,13 @@
package com.misaki.schedule package com.misaki.schedule
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import android.widget.TextView import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
@@ -17,6 +22,8 @@ import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.misaki.schedule.data.Prefs import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleItem import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.ScheduleRepository import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.background.NotificationHelper
import com.misaki.schedule.data.TimeUtils import com.misaki.schedule.data.TimeUtils
import com.misaki.schedule.sync.SyncManager import com.misaki.schedule.sync.SyncManager
import com.misaki.schedule.ui.ScheduleAdapter import com.misaki.schedule.ui.ScheduleAdapter
@@ -38,6 +45,9 @@ class MainActivity : AppCompatActivity() {
private lateinit var syncStatus: TextView private lateinit var syncStatus: TextView
private var selectedDate: LocalDate = LocalDate.now() private var selectedDate: LocalDate = LocalDate.now()
private val dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.CHINA) private val dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.CHINA)
private val notificationPermission = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@@ -46,6 +56,17 @@ class MainActivity : AppCompatActivity() {
repository = ScheduleRepository(this) repository = ScheduleRepository(this)
prefs = Prefs(this) prefs = Prefs(this)
syncManager = SyncManager(this, prefs, repository) syncManager = SyncManager(this, prefs, repository)
NotificationHelper.ensureChannel(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
}
BackgroundScheduler.update(this, prefs)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let { selectedDate = it }
}
list = findViewById(R.id.scheduleList) list = findViewById(R.id.scheduleList)
emptyText = findViewById(R.id.emptyText) emptyText = findViewById(R.id.emptyText)
@@ -58,6 +79,7 @@ class MainActivity : AppCompatActivity() {
onDoneChanged = { item, done -> onDoneChanged = { item, done ->
repository.setDone(item.block.id, done, prefs.deviceId) repository.setDone(item.block.id, done, prefs.deviceId)
syncManager.triggerSync() syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
}, },
) )
list.layoutManager = LinearLayoutManager(this) list.layoutManager = LinearLayoutManager(this)
@@ -115,6 +137,17 @@ class MainActivity : AppCompatActivity() {
refresh() refresh()
} }
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
intent.getStringExtra("date")?.let { value ->
TimeUtils.dateOf(value)?.let {
selectedDate = it
refresh()
}
}
}
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
syncManager.start() syncManager.start()
@@ -154,6 +187,7 @@ class MainActivity : AppCompatActivity() {
} }
selectedDate = newStart.toLocalDate() selectedDate = newStart.toLocalDate()
syncManager.triggerSync() syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh() refresh()
} }
dialog.show() dialog.show()
@@ -167,6 +201,7 @@ class MainActivity : AppCompatActivity() {
.setPositiveButton(R.string.delete) { _, _ -> .setPositiveButton(R.string.delete) { _, _ ->
repository.delete(item.block.id) repository.delete(item.block.id)
syncManager.triggerSync() syncManager.triggerSync()
BackgroundScheduler.syncNow(this)
refresh() refresh()
} }
.show() .show()
@@ -0,0 +1,65 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.misaki.schedule.data.Prefs
import java.util.concurrent.TimeUnit
object BackgroundScheduler {
private const val SYNC_WORK = "schedule-sync"
private const val REMINDER_WORK = "schedule-reminders"
private const val SYNC_NOW_WORK = "schedule-sync-now"
fun update(context: Context, prefs: Prefs) {
scheduleReminders(context)
if (prefs.enabled) scheduleSync(context) else cancelSync(context)
}
fun scheduleSync(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
SYNC_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun cancelSync(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK)
WorkManager.getInstance(context).cancelUniqueWork(SYNC_NOW_WORK)
}
fun scheduleReminders(context: Context) {
val request = PeriodicWorkRequestBuilder<ReminderWorker>(15, TimeUnit.MINUTES).build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
REMINDER_WORK,
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
}
fun syncNow(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
SYNC_NOW_WORK,
ExistingWorkPolicy.REPLACE,
request,
)
}
}
@@ -0,0 +1,13 @@
package com.misaki.schedule.background
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.misaki.schedule.data.Prefs
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
BackgroundScheduler.update(context, Prefs(context))
}
}
@@ -0,0 +1,72 @@
package com.misaki.schedule.background
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.misaki.schedule.MainActivity
import com.misaki.schedule.R
import com.misaki.schedule.data.ScheduleItem
import com.misaki.schedule.data.TimeUtils
object NotificationHelper {
const val CHANNEL_ID = "schedule_reminders"
fun ensureChannel(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
val channel = NotificationChannel(
CHANNEL_ID,
context.getString(R.string.reminder_channel_name),
NotificationManager.IMPORTANCE_HIGH,
).apply {
description = context.getString(R.string.reminder_channel_description)
}
manager.createNotificationChannel(channel)
}
fun canNotify(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
return false
}
return NotificationManagerCompat.from(context).areNotificationsEnabled()
}
fun notifyReminder(context: Context, item: ScheduleItem): Boolean {
if (!canNotify(context)) return false
ensureChannel(context)
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra("date", item.block.startAt)
}
val pending = PendingIntent.getActivity(
context,
item.block.id.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val range = TimeUtils.formatRange(item.block.startAt, item.block.endAt)
val text = context.getString(R.string.reminder_text, item.task.title, range)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.reminder_title))
.setContentText(text)
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pending)
.build()
NotificationManagerCompat.from(context).notify(item.block.id.hashCode(), notification)
return true
}
}
@@ -0,0 +1,30 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.data.TimeUtils
class ReminderWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
return try {
NotificationHelper.ensureChannel(applicationContext)
if (!NotificationHelper.canNotify(applicationContext)) {
return Result.success()
}
val repository = ScheduleRepository(applicationContext)
val now = TimeUtils.nowIso()
val since = TimeUtils.hoursAgo(24)
val pending = repository.pendingReminders(now, since)
for ((item, key) in pending) {
if (NotificationHelper.notifyReminder(applicationContext, item)) {
repository.markReminderSent(key, item.block.id, now)
}
}
Result.success()
} catch (_: Exception) {
Result.retry()
}
}
}
@@ -0,0 +1,34 @@
package com.misaki.schedule.background
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import com.misaki.schedule.sync.SyncEngine
import com.misaki.schedule.sync.UnauthorizedException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
class SyncWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val prefs = Prefs(applicationContext)
if (!prefs.enabled || prefs.serverUrl.isBlank()) return Result.success()
val repository = ScheduleRepository(applicationContext)
val engine = SyncEngine(prefs, repository)
return withContext(Dispatchers.IO) {
try {
engine.runOnce()
Result.success()
} catch (_: UnauthorizedException) {
prefs.clearToken()
Result.retry()
} catch (_: IOException) {
Result.retry()
} catch (_: Exception) {
Result.retry()
}
}
}
}
@@ -4,7 +4,7 @@ import android.content.Context
import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteOpenHelper
class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", null, 1) { class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", null, 2) {
override fun onConfigure(db: SQLiteDatabase) { override fun onConfigure(db: SQLiteDatabase) {
super.onConfigure(db) super.onConfigure(db)
db.setForeignKeyConstraintsEnabled(true) db.setForeignKeyConstraintsEnabled(true)
@@ -63,12 +63,19 @@ class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", nu
""".trimIndent() """.trimIndent()
) )
db.execSQL("CREATE TABLE sync_state(device_id TEXT PRIMARY KEY, last_seq INTEGER DEFAULT 0)") db.execSQL("CREATE TABLE sync_state(device_id TEXT PRIMARY KEY, last_seq INTEGER DEFAULT 0)")
db.execSQL(
"CREATE TABLE reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
db.execSQL("CREATE INDEX idx_timeblock_start ON timeblock(start_at)") db.execSQL("CREATE INDEX idx_timeblock_start ON timeblock(start_at)")
db.execSQL("CREATE INDEX idx_timeblock_task ON timeblock(task_id)") db.execSQL("CREATE INDEX idx_timeblock_task ON timeblock(task_id)")
db.execSQL("CREATE INDEX idx_outbox_entity ON outbox(entity_type, entity_id)") db.execSQL("CREATE INDEX idx_outbox_entity ON outbox(entity_type, entity_id)")
} }
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// The mobile schema is versioned together with the desktop change stream. if (oldVersion < 2) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS reminder_sent(key TEXT PRIMARY KEY, block_id TEXT NOT NULL, sent_at TEXT NOT NULL)"
)
}
} }
} }
@@ -85,6 +85,9 @@ object TimeUtils {
fun startOfDay(date: LocalDate): LocalDateTime = date.atStartOfDay() fun startOfDay(date: LocalDate): LocalDateTime = date.atStartOfDay()
fun hoursAgo(hours: Long): String =
isoFormatter.format(Instant.now().minus(hours, ChronoUnit.HOURS).truncatedTo(ChronoUnit.MILLIS))
fun defaultStart(date: LocalDate): LocalDateTime { fun defaultStart(date: LocalDate): LocalDateTime {
val today = LocalDate.now() val today = LocalDate.now()
if (date == today) { if (date == today) {
@@ -184,6 +184,41 @@ class ScheduleRepository(context: Context) {
db.delete("outbox", "id <= ?", arrayOf(maxId.toString())) db.delete("outbox", "id <= ?", arrayOf(maxId.toString()))
} }
fun pendingReminders(nowIso: String, sinceIso: String): List<Pair<ScheduleItem, String>> {
val result = mutableListOf<Pair<ScheduleItem, String>>()
db.rawQuery(
"""
SELECT t.id, t.title, t.description, t.source, t.source_ref, t.estimated_min,
t.energy_req, t.deadline, t.priority, t.status, t.created_at, t.updated_at,
t.version, t.device_id,
b.id, b.task_id, b.start_at, b.end_at, b.granularity, b.splittable,
b.breakable, b.status, b.done_at, b.created_at, b.updated_at, b.version, b.device_id,
b.id || '@' || b.updated_at
FROM timeblock b JOIN task t ON t.id = b.task_id
LEFT JOIN reminder_sent r ON r.key = b.id || '@' || b.updated_at
WHERE b.status IN ('scheduled', 'in_progress')
AND b.end_at <= ? AND b.end_at >= ?
AND r.key IS NULL
ORDER BY b.end_at ASC
""".trimIndent(),
arrayOf(nowIso, sinceIso)
).use { cursor ->
while (cursor.moveToNext()) {
result.add(readItem(cursor) to cursor.getString(27))
}
}
return result
}
fun markReminderSent(key: String, blockId: String, sentAt: String) {
val values = ContentValues().apply {
put("key", key)
put("block_id", blockId)
put("sent_at", sentAt)
}
db.insertWithOnConflict("reminder_sent", null, values, SQLiteDatabase.CONFLICT_IGNORE)
}
fun lastSeq(deviceId: String): Long { fun lastSeq(deviceId: String): Long {
db.rawQuery("SELECT last_seq FROM sync_state WHERE device_id = ?", arrayOf(deviceId)).use { cursor -> db.rawQuery("SELECT last_seq FROM sync_state WHERE device_id = ?", arrayOf(deviceId)).use { cursor ->
return if (cursor.moveToFirst()) cursor.getLong(0) else 0L return if (cursor.moveToFirst()) cursor.getLong(0) else 0L
@@ -0,0 +1,49 @@
package com.misaki.schedule.sync
import com.misaki.schedule.data.Prefs
import com.misaki.schedule.data.ScheduleRepository
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* Shared one-pass sync implementation used by the foreground controller and WorkManager.
*/
class SyncEngine(
private val prefs: Prefs,
private val repository: ScheduleRepository,
) {
val api = SyncApi(prefs)
suspend fun runOnce() = mutex.withLock {
if (!prefs.enabled || prefs.serverUrl.isBlank()) {
return@withLock
}
if (prefs.token.isBlank()) {
prefs.token = api.register(prefs.deviceId, prefs.deviceName)
}
var pushes = 0
while (pushes < 10) {
val batch = repository.pendingChanges()
if (batch.count == 0) break
val accepted = api.push(prefs.token, batch.changes)
if (accepted < batch.count) throw IllegalStateException("服务端未接受全部变更")
repository.clearOutboxThrough(batch.maxId)
pushes++
}
var cursor = repository.lastSeq(prefs.deviceId)
var pages = 0
while (pages < 10) {
val page = api.pull(prefs.token, cursor)
repository.applyRemote(prefs.deviceId, page.changes, page.latestSeq)
cursor = page.latestSeq
pages++
if (!page.hasMore) break
}
}
companion object {
private val mutex = Mutex()
}
}
@@ -13,8 +13,6 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.Response import okhttp3.Response
import okhttp3.WebSocket import okhttp3.WebSocket
@@ -31,9 +29,9 @@ class SyncManager(
val status = MutableStateFlow(Status("本地")) val status = MutableStateFlow(Status("本地"))
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val api = SyncApi(prefs) private val engine = SyncEngine(prefs, repository)
private val api = engine.api
private val trigger = Channel<Unit>(Channel.CONFLATED) private val trigger = Channel<Unit>(Channel.CONFLATED)
private val mutex = Mutex()
private var job: Job? = null private var job: Job? = null
@Volatile private var webSocket: WebSocket? = null @Volatile private var webSocket: WebSocket? = null
@@ -94,27 +92,9 @@ class SyncManager(
prefs.token = token prefs.token = token
} }
private suspend fun syncOnce() = mutex.withLock { private suspend fun syncOnce() {
status.value = Status("同步中…") status.value = Status("同步中…")
var pushes = 0 engine.runOnce()
while (pushes < 10) {
val batch = repository.pendingChanges()
if (batch.count == 0) break
val accepted = api.push(prefs.token, batch.changes)
if (accepted < batch.count) throw IllegalStateException("服务端未接受全部变更")
repository.clearOutboxThrough(batch.maxId)
pushes++
}
var cursor = repository.lastSeq(prefs.deviceId)
var pages = 0
while (pages < 10) {
val page = api.pull(prefs.token, cursor)
repository.applyRemote(prefs.deviceId, page.changes, page.latestSeq)
cursor = page.latestSeq
pages++
if (!page.hasMore) break
}
} }
private fun ensureWebSocket() { private fun ensureWebSocket() {
@@ -6,6 +6,7 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.materialswitch.MaterialSwitch import com.google.android.material.materialswitch.MaterialSwitch
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
import com.misaki.schedule.R import com.misaki.schedule.R
import com.misaki.schedule.background.BackgroundScheduler
import com.misaki.schedule.data.Prefs import com.misaki.schedule.data.Prefs
import com.misaki.schedule.sync.SyncManager import com.misaki.schedule.sync.SyncManager
@@ -24,6 +25,7 @@ object SettingsDialog {
.setPositiveButton(R.string.save) { _, _ -> .setPositiveButton(R.string.save) { _, _ ->
prefs.serverUrl = url.text?.toString().orEmpty() prefs.serverUrl = url.text?.toString().orEmpty()
prefs.enabled = enabled.isChecked prefs.enabled = enabled.isChecked
BackgroundScheduler.update(context, prefs)
syncManager.reload() syncManager.reload()
} }
.show() .show()
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,2a10,10 0,1 0,0 20a10,10 0,0 0,0 -20zM12,4a8,8 0,1 1,0 16a8,8 0,0 1,0 -16zM11,7h2v5.4l3.2,3.2l-1.4,1.4l-3.8,-3.8z" />
</vector>
@@ -29,4 +29,9 @@
<string name="server_url_hint">http://192.168.1.2:8787</string> <string name="server_url_hint">http://192.168.1.2:8787</string>
<string name="enable_sync">启用多设备同步</string> <string name="enable_sync">启用多设备同步</string>
<string name="settings_hint">服务端需与手机在同一网络,或使用可访问的 HTTPS 地址。</string> <string name="settings_hint">服务端需与手机在同一网络,或使用可访问的 HTTPS 地址。</string>
<string name="reminder_channel_name">日程提醒</string>
<string name="reminder_channel_description">日程结束时提醒未完成事项</string>
<string name="reminder_title">日程已结束</string>
<string name="reminder_text">「%1$s」原定 %2 尚未完成,点击处理。</string>
<string name="notification_permission_hint">开启通知权限后,日程结束时会收到提醒。</string>
</resources> </resources>
+3 -1
View File
@@ -150,9 +150,11 @@ Schedule/
- [x] 设备注册、push/pull、WebSocket + 轮询、设置页 - [x] 设备注册、push/pull、WebSocket + 轮询、设置页
- [x] 今日列表、日期切换、完成/编辑/删除/新建、Material 3 - [x] 今日列表、日期切换、完成/编辑/删除/新建、Material 3
- [x] Debug APK 构建成功;JVM 单元测试 6/6 - [x] Debug APK 构建成功;JVM 单元测试 6/6
- [x] 本地通知提醒(结束未完成)、通知权限、通知点击回到日期
- [x] WorkManager 15 分钟后台同步、开机广播重建任务
- [ ] 真机/模拟器交互验证 - [ ] 真机/模拟器交互验证
- [ ] AI 对话 / 附件 / 精力曲线 / 复盘 / 重复日程创建 - [ ] AI 对话 / 附件 / 精力曲线 / 复盘 / 重复日程创建
- [ ] WorkManager 后台同步、通知、Keystore、发布签名 - [ ] FCM 即时推送、精确提醒、Keystore、发布签名
- 验收:`assembleDebug` + `testDebugUnitTest`;见 [`validation/phase-5.md`](validation/phase-5.md) - 验收:`assembleDebug` + `testDebugUnitTest`;见 [`validation/phase-5.md`](validation/phase-5.md)
## 3. 质量门槛(每阶段) ## 3. 质量门槛(每阶段)
+17 -17
View File
@@ -17,45 +17,45 @@ Daemon will be stopped at the end of the build
> Task :app:processDebugManifest UP-TO-DATE > Task :app:processDebugManifest UP-TO-DATE
> Task :app:processDebugManifestForPackage UP-TO-DATE > Task :app:processDebugManifestForPackage UP-TO-DATE
> Task :app:processDebugResources UP-TO-DATE > Task :app:processDebugResources UP-TO-DATE
> Task :app:compileDebugKotlin UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:compileDebugJavaWithJavac NO-SOURCE
> Task :app:mergeDebugShaders UP-TO-DATE > Task :app:mergeDebugShaders UP-TO-DATE
> Task :app:compileDebugShaders NO-SOURCE > Task :app:compileDebugShaders NO-SOURCE
> Task :app:generateDebugAssets UP-TO-DATE > Task :app:generateDebugAssets UP-TO-DATE
> Task :app:mergeDebugAssets UP-TO-DATE > Task :app:mergeDebugAssets UP-TO-DATE
> Task :app:compressDebugAssets UP-TO-DATE > Task :app:compressDebugAssets UP-TO-DATE
> Task :app:desugarDebugFileDependencies UP-TO-DATE > Task :app:desugarDebugFileDependencies UP-TO-DATE
> Task :app:dexBuilderDebug UP-TO-DATE
> Task :app:mergeDebugGlobalSynthetics UP-TO-DATE
> Task :app:processDebugJavaRes UP-TO-DATE
> Task :app:mergeDebugJavaResource UP-TO-DATE
> Task :app:checkDebugDuplicateClasses UP-TO-DATE > Task :app:checkDebugDuplicateClasses UP-TO-DATE
> Task :app:mergeDebugStartupProfile UP-TO-DATE > Task :app:mergeDebugStartupProfile UP-TO-DATE
> Task :app:mergeExtDexDebug UP-TO-DATE > Task :app:mergeExtDexDebug UP-TO-DATE
> Task :app:mergeLibDexDebug UP-TO-DATE > Task :app:mergeLibDexDebug UP-TO-DATE
> Task :app:mergeProjectDexDebug UP-TO-DATE
> Task :app:mergeDebugJniLibFolders UP-TO-DATE > Task :app:mergeDebugJniLibFolders UP-TO-DATE
> Task :app:mergeDebugNativeLibs NO-SOURCE > Task :app:mergeDebugNativeLibs NO-SOURCE
> Task :app:stripDebugDebugSymbols NO-SOURCE > Task :app:stripDebugDebugSymbols NO-SOURCE
> Task :app:validateSigningDebug UP-TO-DATE > Task :app:validateSigningDebug UP-TO-DATE
> Task :app:writeDebugAppMetadata UP-TO-DATE > Task :app:writeDebugAppMetadata UP-TO-DATE
> Task :app:writeDebugSigningConfigVersions UP-TO-DATE > Task :app:writeDebugSigningConfigVersions UP-TO-DATE
> Task :app:packageDebug UP-TO-DATE
> Task :app:createDebugApkListingFileRedirect UP-TO-DATE
> Task :app:assembleDebug UP-TO-DATE
> Task :app:bundleDebugClassesToRuntimeJar UP-TO-DATE
> Task :app:bundleDebugClassesToCompileJar UP-TO-DATE
> Task :app:compileDebugUnitTestKotlin UP-TO-DATE
> Task :app:preDebugUnitTestBuild UP-TO-DATE > Task :app:preDebugUnitTestBuild UP-TO-DATE
> Task :app:javaPreCompileDebugUnitTest UP-TO-DATE > Task :app:javaPreCompileDebugUnitTest UP-TO-DATE
> Task :app:compileDebugKotlin
> Task :app:compileDebugJavaWithJavac NO-SOURCE
> Task :app:dexBuilderDebug
> Task :app:mergeDebugGlobalSynthetics UP-TO-DATE
> Task :app:processDebugJavaRes UP-TO-DATE
> Task :app:mergeDebugJavaResource UP-TO-DATE
> Task :app:bundleDebugClassesToRuntimeJar
> Task :app:bundleDebugClassesToCompileJar
> Task :app:mergeProjectDexDebug
> Task :app:compileDebugUnitTestKotlin
> Task :app:compileDebugUnitTestJavaWithJavac NO-SOURCE > Task :app:compileDebugUnitTestJavaWithJavac NO-SOURCE
> Task :app:processDebugUnitTestJavaRes UP-TO-DATE > Task :app:processDebugUnitTestJavaRes UP-TO-DATE
> Task :app:testDebugUnitTest > Task :app:testDebugUnitTest UP-TO-DATE
> Task :app:packageDebug
> Task :app:createDebugApkListingFileRedirect UP-TO-DATE
> Task :app:assembleDebug
BUILD SUCCESSFUL in 15s BUILD SUCCESSFUL in 8s
41 actionable tasks: 9 executed, 32 up-to-date 41 actionable tasks: 1 executed, 40 up-to-date
APK: android/app/build/outputs/apk/debug/app-debug.apk (6.1 MB) APK: android/app/build/outputs/apk/debug/app-debug.apk (6.5 MB)
JVM unit tests: TimeUtilsTest 3 passed; LwwTest 3 passed; 0 failures. JVM unit tests: TimeUtilsTest 3 passed; LwwTest 3 passed; 0 failures.
+6 -3
View File
@@ -12,6 +12,8 @@
- 今日日程:日期切换、完成/取消完成、编辑、长按删除、FAB 新建。 - 今日日程:日期切换、完成/取消完成、编辑、长按删除、FAB 新建。
- 同步:设备注册、outbox 推送、按 `seq` 增量拉取、`updated_at` LWW、WebSocket 通知、15 秒轮询兜底。 - 同步:设备注册、outbox 推送、按 `seq` 增量拉取、`updated_at` LWW、WebSocket 通知、15 秒轮询兜底。
- 设置:服务地址、启用开关;首次启用自动注册。 - 设置:服务地址、启用开关;首次启用自动注册。
- 提醒:`ReminderWorker` 每 15 分钟检查过去 24 小时内结束且未完成的日程,发本地通知;通知点击回到对应日期。
- 后台:`SyncWorker` 由 WorkManager 每 15 分钟执行;`BOOT_COMPLETED` 广播重建同步/提醒任务。
- 单测:LWW 时间比较、时间格式与 ISO 转换。 - 单测:LWW 时间比较、时间格式与 ISO 转换。
## 2. 构建与测试 ## 2. 构建与测试
@@ -24,9 +26,9 @@ cd android
| 项目 | 结果 | | 项目 | 结果 |
|---|---| |---|---|
| Debug APK | 构建成功:`android/app/build/outputs/apk/debug/app-debug.apk`(约 6.1 MB) | | Debug APK | 构建成功:`android/app/build/outputs/apk/debug/app-debug.apk`(约 6.5 MB) |
| JVM 单元测试 | 6/6 通过(LwwTest 3 + TimeUtilsTest 3) | | JVM 单元测试 | 6/6 通过(LwwTest 3 + TimeUtilsTest 3) |
| `aapt dump badging` | package `com.misaki.schedule`,minSdk 26,targetSdk 34 | | `aapt dump badging` | package `com.misaki.schedule`,minSdk 26,targetSdk 34;包含通知/开机权限和 WorkManager 服务 |
完整构建/测试输出见 [`android-build-test-phase-5.txt`](android-build-test-phase-5.txt)。 完整构建/测试输出见 [`android-build-test-phase-5.txt`](android-build-test-phase-5.txt)。
@@ -45,6 +47,7 @@ Android 发送与桌面端相同的字段:
- 本地删除会写入删除时刻的顶层 `updated_at`,避免墓碑被旧时间戳忽略。 - 本地删除会写入删除时刻的顶层 `updated_at`,避免墓碑被旧时间戳忽略。
- 重复日程在 Android 上以物化后的普通 timeblock 显示。 - 重复日程在 Android 上以物化后的普通 timeblock 显示。
- 精力曲线、复盘、AI 对话不参与 Android v1。 - 精力曲线、复盘、AI 对话不参与 Android v1。
- 提醒为本地通知,不是服务端推送;后台同步周期为 15 分钟,受 Doze/厂商限制。
## 4. 运行与配置 ## 4. 运行与配置
@@ -75,7 +78,7 @@ SYNC_TOKEN_PEPPER=<固定随机值> go run ./cmd/server
## 6. 后续移动端工作 ## 6. 后续移动端工作
- WorkManager 后台同步 + 通知(超时/变更)。 - FCM 即时推送 + 精确提醒(AlarmManager 或服务端调度)。
- 移动端 AI 对话与文件上传/提取;需要服务端增加附件能力。 - 移动端 AI 对话与文件上传/提取;需要服务端增加附件能力。
- 移动端重复日程创建、精力/复盘视图。 - 移动端重复日程创建、精力/复盘视图。
- Android Keystore 保存 Token、HTTPS 默认、发布签名。 - Android Keystore 保存 Token、HTTPS 默认、发布签名。