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
+11
View File
@@ -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>