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:
+16
-2
@@ -7,6 +7,8 @@
|
||||
- 今日日程列表:按日期前后切换、完成状态、编辑、长按删除。
|
||||
- 本地 SQLite:task / timeblock / outbox / sync_state。
|
||||
- 同步:设备注册、outbox 推送、增量拉取、LWW、WebSocket 通知、定时轮询。
|
||||
- 提醒:日程结束后对未完成项发本地通知;通知点击回到对应日期。
|
||||
- 后台:WorkManager 每 15 分钟同步一次;开机接收 `BOOT_COMPLETED` 重新登记任务。
|
||||
- 设置:同步服务地址与启用开关;不支持 AI 对话和附件提取(桌面端功能)。
|
||||
|
||||
## 构建
|
||||
@@ -45,8 +47,20 @@ adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||
> App 允许明文 HTTP 以便局域网自部署测试;公网部署请使用 HTTPS 反向代理。
|
||||
> Token 存在 SharedPreferences 中,明文保存;后续可接入 Android Keystore。
|
||||
|
||||
## 通知与后台同步
|
||||
|
||||
- 提醒使用 Android 本地通知,不依赖服务端推送/FCM。
|
||||
- 通知在工作线程中检查过去 24 小时内已结束、仍未完成的日程;同一时间块只提醒一次。
|
||||
- Android 13+ 首次启动会请求通知权限;拒绝后提醒不显示,但同步不受影响。
|
||||
- WorkManager 周期最小为 15 分钟;省电模式/Doze 或厂商后台限制可能进一步延迟。
|
||||
- 开机广播会重新安排提醒与同步任务;不会自动打开 App 界面。
|
||||
- 如需即时后台推送,需要后续接入 FCM 或常驻前台服务(会增加耗电/复杂度)。
|
||||
|
||||
> 部分国产 ROM 需要手动允许「自启动」「后台运行」或关闭电池优化,否则开机任务和周期同步可能被系统拦截。
|
||||
|
||||
## 当前限制
|
||||
|
||||
- 无 AI 对话 / 文件附件 / 精力曲线 / 重复日程创建 / 每日复盘;这些仍由桌面端提供。
|
||||
- 无后台同步;Activity 进入后台后会停止同步,回到前台再恢复。
|
||||
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建和 JVM 单元测试。
|
||||
- 提醒不是精确闹钟:周期任务可能延迟,且没有“提前 N 分钟”提醒。
|
||||
- 无 FCM 推送;App 被强制停止后,Android 不会执行周期任务,直到下次手动打开。
|
||||
- 未在真机或模拟器上做交互验证;当前验证到 APK 构建、JVM 单元测试和 Manifest 检查。
|
||||
|
||||
@@ -40,6 +40,7 @@ dependencies {
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
implementation("androidx.work:work-runtime-ktx:2.9.1")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.json:json:20240303")
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<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
|
||||
android:allowBackup="true"
|
||||
@@ -20,5 +22,14 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</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>
|
||||
</manifest>
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
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.view.View
|
||||
import android.widget.TextView
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
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.ScheduleItem
|
||||
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.sync.SyncManager
|
||||
import com.misaki.schedule.ui.ScheduleAdapter
|
||||
@@ -38,6 +45,9 @@ class MainActivity : AppCompatActivity() {
|
||||
private lateinit var syncStatus: TextView
|
||||
private var selectedDate: LocalDate = LocalDate.now()
|
||||
private val dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日 EEEE", Locale.CHINA)
|
||||
private val notificationPermission = registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { }
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -46,6 +56,17 @@ class MainActivity : AppCompatActivity() {
|
||||
repository = ScheduleRepository(this)
|
||||
prefs = Prefs(this)
|
||||
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)
|
||||
emptyText = findViewById(R.id.emptyText)
|
||||
@@ -58,6 +79,7 @@ class MainActivity : AppCompatActivity() {
|
||||
onDoneChanged = { item, done ->
|
||||
repository.setDone(item.block.id, done, prefs.deviceId)
|
||||
syncManager.triggerSync()
|
||||
BackgroundScheduler.syncNow(this)
|
||||
},
|
||||
)
|
||||
list.layoutManager = LinearLayoutManager(this)
|
||||
@@ -115,6 +137,17 @@ class MainActivity : AppCompatActivity() {
|
||||
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() {
|
||||
super.onStart()
|
||||
syncManager.start()
|
||||
@@ -154,6 +187,7 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
selectedDate = newStart.toLocalDate()
|
||||
syncManager.triggerSync()
|
||||
BackgroundScheduler.syncNow(this)
|
||||
refresh()
|
||||
}
|
||||
dialog.show()
|
||||
@@ -167,6 +201,7 @@ class MainActivity : AppCompatActivity() {
|
||||
.setPositiveButton(R.string.delete) { _, _ ->
|
||||
repository.delete(item.block.id)
|
||||
syncManager.triggerSync()
|
||||
BackgroundScheduler.syncNow(this)
|
||||
refresh()
|
||||
}
|
||||
.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.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) {
|
||||
super.onConfigure(db)
|
||||
db.setForeignKeyConstraintsEnabled(true)
|
||||
@@ -63,12 +63,19 @@ class ScheduleDb(context: Context) : SQLiteOpenHelper(context, "schedule.db", nu
|
||||
""".trimIndent()
|
||||
)
|
||||
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_task ON timeblock(task_id)")
|
||||
db.execSQL("CREATE INDEX idx_outbox_entity ON outbox(entity_type, entity_id)")
|
||||
}
|
||||
|
||||
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 hoursAgo(hours: Long): String =
|
||||
isoFormatter.format(Instant.now().minus(hours, ChronoUnit.HOURS).truncatedTo(ChronoUnit.MILLIS))
|
||||
|
||||
fun defaultStart(date: LocalDate): LocalDateTime {
|
||||
val today = LocalDate.now()
|
||||
if (date == today) {
|
||||
|
||||
@@ -184,6 +184,41 @@ class ScheduleRepository(context: Context) {
|
||||
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 {
|
||||
db.rawQuery("SELECT last_seq FROM sync_state WHERE device_id = ?", arrayOf(deviceId)).use { cursor ->
|
||||
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.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
@@ -31,9 +29,9 @@ class SyncManager(
|
||||
val status = MutableStateFlow(Status("本地"))
|
||||
|
||||
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 mutex = Mutex()
|
||||
private var job: Job? = null
|
||||
|
||||
@Volatile private var webSocket: WebSocket? = null
|
||||
@@ -94,27 +92,9 @@ class SyncManager(
|
||||
prefs.token = token
|
||||
}
|
||||
|
||||
private suspend fun syncOnce() = mutex.withLock {
|
||||
private suspend fun syncOnce() {
|
||||
status.value = Status("同步中…")
|
||||
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
|
||||
}
|
||||
engine.runOnce()
|
||||
}
|
||||
|
||||
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.textfield.TextInputEditText
|
||||
import com.misaki.schedule.R
|
||||
import com.misaki.schedule.background.BackgroundScheduler
|
||||
import com.misaki.schedule.data.Prefs
|
||||
import com.misaki.schedule.sync.SyncManager
|
||||
|
||||
@@ -24,6 +25,7 @@ object SettingsDialog {
|
||||
.setPositiveButton(R.string.save) { _, _ ->
|
||||
prefs.serverUrl = url.text?.toString().orEmpty()
|
||||
prefs.enabled = enabled.isChecked
|
||||
BackgroundScheduler.update(context, prefs)
|
||||
syncManager.reload()
|
||||
}
|
||||
.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="enable_sync">启用多设备同步</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>
|
||||
|
||||
Reference in New Issue
Block a user