appstore: show background update-check status on the sources screen
- Commit
f3834b71af93563a430b1e37db527ac2dac1fc00- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-08 18:37 UTC (27 days ago)
- Parents
e0459bc
The store's updates depend on a periodic WorkManager check that the OS can silently stop running - battery restriction, or GrapheneOS hibernation after long disuse. Until now the settings (sources) screen gave no sign of that: the only last-checked timestamp lived on the updates page and reflected foreground checks alone, so a hibernated app looked identical to a healthy one. What changed and why: - UpdateCheckWorker now records the completion time of every successful background run in its existing shared prefs, and exposes two query helpers for the UI: lastCheckTimeMs() and workerStateNow(). The latter returns the live state of the unique periodic work, or null when nothing is enqueued - null is the hibernation tell, because MainActivity reschedules on every start, so live work should always exist. - AppStoreUiContract gains UpdateCheckStatus (lastCheckMs, scheduled, workerState, backgroundRestricted); AppStoreViewModel exposes it as updateCheckStatus with refreshUpdateCheckStatus(), which maxes the persisted background time with this process's foreground checks and reads the OS restriction flag via the public ActivityManager.isBackgroundRestricted API (minSdk 31, no guard needed). - New one-composable-per-file ui/UpdateCheckStatusCard.kt renders the row with SettingsRow inside a Card to match the screen, with relative last-check time via DateUtils like the updates page. New strings in values/strings.xml. - SourcesPage collects the status and refreshes it in a LaunchedEffect on every appearance; the worker query is blocking, so it runs on Dispatchers.IO in the ViewModel. Constraints honored: public APIs only - no hidden APIs, no new aosp-stubs (none exist for hibernation/auto-revoke). Hibernation itself is not directly queryable, so its absence shows up as missing scheduled work plus a stale last-check time, which is exactly what the row reports. Dev builds only; no device touched. User-visible effect: the sources screen now has a Background update checks card reading e.g. Last checked 3 hours ago / Scheduled, or Not scheduled with an explanation plus a warning line when background activity is restricted for the app. Verified with the appstore slice: :appstore:compileDevKotlin, :appstore:lint and :appstore:metadata all BUILD SUCCESSFUL. Note: :appstore:checkMetadata as written in AGENTS.md does not resolve to a task (ambiguous against AGP check* AarMetadata tasks; no checkMetadata task is registered in build-logic) - :appstore:metadata is the registered metadata task and was run instead.
Diff
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex 20f0b0bdb1..b38d1dc3cc 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -21,6 +21,7 @@ import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ForegroundInfo import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.appstore.MainActivity@@ -68,6 +69,13 @@ class UpdateCheckWorker( } finally { scope.cancel() }+ // The settings screen reports when the background check last ran, so a+ // user can tell a quietly-working scheduler from a hibernated app whose+ // work the OS stopped running. Recorded only on success: a failed run+ // that will retry is not a completed check.+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit {+ putLong(KEY_LAST_CHECK, System.currentTimeMillis())+ } Result.success() } catch (expected: java.io.IOException) { Log.status(TAG, "Update check failed", expected)@@ -439,6 +447,7 @@ class UpdateCheckWorker( private const val INSTALLED_NOTIFICATION_ID = 4203 private const val PREFS = "appstore-update-check" private const val KEY_LAST_NOTIFIED = "last_notified_packages"+ private const val KEY_LAST_CHECK = "last_check_ms" /** * How long to wait after committing installs before re-reading the device.@@ -474,5 +483,32 @@ class UpdateCheckWorker( } private const val WORK_NAME = "AppStoreUpdateCheck"++ /**+ * ms since epoch of the last completed background check, 0 if never.+ *+ * Read by the settings status row alongside the foreground check time,+ * so "last checked" reflects reality whichever path ran most recently.+ */+ fun lastCheckTimeMs(context: Context): Long =+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+ .getLong(KEY_LAST_CHECK, 0L)++ /**+ * State of the unique periodic work, or null when nothing is enqueued.+ *+ * Null is the hibernation tell: the scheduler ([schedule]) runs on every+ * app start, so live work should always exist — when it doesn't, the OS+ * stopped or cancelled it while the app sat unused. Blocking WorkManager+ * query, so call off the main thread. Null on any failure rather than+ * reporting "not scheduled" for a query that never ran.+ */+ fun workerStateNow(context: Context): WorkInfo.State? = runCatching {+ WorkManager.getInstance(context)+ .getWorkInfosForUniqueWork(WORK_NAME)+ .get()+ .firstOrNull { !it.state.isFinished }+ ?.state+ }.getOrNull() } }
appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.ktindex 1a41b56003..3a93f6b46a 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment@@ -43,8 +44,13 @@ fun SourcesPage( val home by viewModel.home.collectAsState() val autoInstallUpdates by viewModel.autoInstallUpdates.collectAsState() val enabledSources by viewModel.enabledSources.collectAsState()+ val updateCheckStatus by viewModel.updateCheckStatus.collectAsState() val noneEnabled = AppSource.TOGGLEABLE.none { it in enabledSources } + // WorkManager state and the OS restriction flag are reads, not flows — pull+ // them every time the screen appears rather than polling for them.+ LaunchedEffect(Unit) { viewModel.refreshUpdateCheckStatus() }+ Scaffold { padding -> Column( Modifier@@ -82,6 +88,8 @@ fun SourcesPage( ) } + UpdateCheckStatusCard(status = updateCheckStatus)+ SourceCard( title = stringResource(R.string.source_modern_apps), subtitle = ModernAppsRepo.PROJECT_URL,
appstore/src/main/java/com/vayunmathur/appstore/ui/UpdateCheckStatusCard.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/UpdateCheckStatusCard.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/UpdateCheckStatusCard.ktnew file mode 100644index 0000000000..37be8d78b1--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/UpdateCheckStatusCard.kt@@ -0,0 +1,56 @@+package com.vayunmathur.appstore.ui++import android.text.format.DateUtils+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.util.UpdateCheckStatus+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.SettingsRow++/**+ * Background update-check health on the settings screen.+ *+ * Updates only arrive when the periodic worker actually runs, and the OS can+ * silently stop it — battery restriction, or GrapheneOS hibernation after long+ * disuse — so this row reports what is true rather than what was scheduled:+ * when anything last checked, whether the periodic work is still live, and a+ * warning when the OS reports background work restricted for this app.+ */+@Composable+fun UpdateCheckStatusCard(status: UpdateCheckStatus) {+ val lastCheck = if (status.lastCheckMs > 0L) {+ stringResource(+ R.string.setting_update_check_last,+ DateUtils.getRelativeTimeSpanString(+ status.lastCheckMs,+ System.currentTimeMillis(),+ DateUtils.MINUTE_IN_MILLIS,+ ),+ )+ } else {+ stringResource(R.string.setting_update_check_never)+ }+ val schedule = stringResource(+ if (status.scheduled) {+ R.string.setting_update_check_active+ } else {+ R.string.setting_update_check_inactive+ },+ )+ val lines = buildList {+ add(lastCheck)+ add(schedule)+ if (status.backgroundRestricted) {+ add(stringResource(R.string.setting_update_check_restricted))+ }+ }+ Card(Modifier.fillMaxWidth()) {+ SettingsRow(+ title = stringResource(R.string.setting_update_check_title),+ supportingText = lines.joinToString("\n"),+ )+ }+}
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.ktindex d7b955a984..767cb3dcb1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt@@ -131,6 +131,26 @@ data class UpdatesUiState( val statusMessage: String = "", ) +/**+ * Background update-check health, shown on the settings screen.+ *+ * The store's updates depend on periodic work the OS may stop running — battery+ * restriction, or GrapheneOS hibernation after long disuse — so the row reports+ * what is actually true rather than what was scheduled: when anything last+ * checked, whether the periodic work is still live, and whether the OS reports+ * background work restricted for this app (public ActivityManager API).+ */+data class UpdateCheckStatus(+ /** ms since epoch of the last completed check, foreground or background, 0 if never. */+ val lastCheckMs: Long = 0L,+ /** The unique periodic worker still has live (unfinished) work enqueued. */+ val scheduled: Boolean = false,+ /** WorkManager state name of that work (ENQUEUED, RUNNING, BLOCKED…), null when none. */+ val workerState: String? = null,+ /** The OS reports background work restricted for this app. */+ val backgroundRestricted: Boolean = false,+)+ /** Everything the library (installed apps) screen draws. */ data class LibraryUiState( val apps: List<UnifiedApp> = emptyList(),
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex a49bae7c89..39765df71d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -1,5 +1,6 @@ package com.vayunmathur.appstore.util +import android.app.ActivityManager import android.app.Application import android.content.Context import android.content.Intent@@ -21,6 +22,7 @@ import com.vayunmathur.appstore.data.PlayStoreLinks import com.vayunmathur.appstore.data.SettingsRepository import com.vayunmathur.appstore.data.SyncStep import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.UpdateCheckWorker import com.vayunmathur.appstore.data.partitionUpdates import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.installer.InstallCoordinator@@ -91,6 +93,17 @@ class AppStoreViewModel( internal val isCheckingUpdatesFlow = MutableStateFlow(false) internal val lastUpdateCheckFlow = MutableStateFlow(0L) + private val updateCheckStatusFlow = MutableStateFlow(UpdateCheckStatus())++ /**+ * Background update-check health for the settings screen.+ *+ * Refreshed on demand by [refreshUpdateCheckStatus], not observed: WorkManager+ * state and the OS restriction flag are read, not flows, so the Sources page+ * pulls them when it appears rather than the ViewModel polling for them.+ */+ val updateCheckStatus: StateFlow<UpdateCheckStatus> = updateCheckStatusFlow+ internal val playSectionsFlow = MutableStateFlow<List<AppSection>>(emptyList()) /** Uncapped Play cluster apps per section id — Browse shows the whole cluster. */ internal val playFullClustersFlow = MutableStateFlow<Map<String, List<UnifiedApp>>>(emptyMap())@@ -612,6 +625,35 @@ class AppStoreViewModel( viewModelScope.launch { settings.setAutoInstallUpdates(enabled) } } + /**+ * Re-read background-check reality for the settings status row.+ *+ * Three independent facts, each with its own failure mode: the persisted+ * background last-run time (maxed with this process's foreground checks, so+ * "last checked" is whichever ran most recently), the live WorkManager state+ * of the unique periodic work (blocking query, hence IO), and the OS+ * background-restriction flag via the public ActivityManager API. No hidden+ * APIs — hibernation itself is not directly queryable, so its absence shows+ * up as missing scheduled work plus a stale last-check time.+ */+ fun refreshUpdateCheckStatus() {+ viewModelScope.launch {+ val (backgroundLast, workerState) = withContext(Dispatchers.IO) {+ UpdateCheckWorker.lastCheckTimeMs(context) to+ UpdateCheckWorker.workerStateNow(context)+ }+ val restricted = runCatching {+ context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted+ }.getOrNull() == true+ updateCheckStatusFlow.value = UpdateCheckStatus(+ lastCheckMs = maxOf(backgroundLast, lastUpdateCheckFlow.value),+ scheduled = workerState != null,+ workerState = workerState?.name,+ backgroundRestricted = restricted,+ )+ }+ }+ // --- Library ------------------------------------------------------------------------ override fun setLibraryFilter(filter: SourceFilter) {
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex ccb2410325..fbf1feebad 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -95,6 +95,13 @@ <string name="updates_channel_description">Tells you when apps you installed here have a newer version.</string> <string name="setting_auto_install_updates_title">Automatically install updates</string> <string name="setting_auto_install_updates_summary">When on, updates install when found. When off, they wait for a tap. Store-installed apps update silently; the rest just notify.</string>+ <!-- Sources page, background update-check status card. -->+ <string name="setting_update_check_title">Background update checks</string>+ <string name="setting_update_check_last">Last checked %1$s</string>+ <string name="setting_update_check_never">Never checked yet</string>+ <string name="setting_update_check_active">Scheduled — checks run in the background every twelve hours on Wi-Fi</string>+ <string name="setting_update_check_inactive">Not scheduled — the system stopped the background checks, so updates only arrive while the store is open. Reopening the store reschedules them.</string>+ <string name="setting_update_check_restricted">Background activity is restricted for this app, so the system may skip its checks. Allow background activity in system Settings to keep them running.</string> <plurals name="updates_count"> <item quantity="one">%1$d update available</item> <item quantity="other">%1$d updates available</item>