appstore: add opt-in automatic background update installation
- Commit
00dfb99302453795107b39f5eebb5c83b62a9c4e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-11 15:07 UTC (3 months ago)
- Parents
b36e848
Diff
appstore/src/main/java/com/vayunmathur/appstore/data/SettingsRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/SettingsRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/SettingsRepository.ktindex d4c9a4ba1a..541cb3882f 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/SettingsRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/SettingsRepository.kt@@ -1,6 +1,7 @@ package com.vayunmathur.appstore.data import android.content.Context+import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences@@ -10,6 +11,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch+import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.io.IOException@@ -33,12 +35,23 @@ class SettingsRepository( /** Whether updates to store-owned apps install without a per-app confirmation prompt. */ val backgroundUpdateInstall: StateFlow<Boolean> = _backgroundUpdateInstall.asStateFlow() + private val _autoInstallUpdates = MutableStateFlow(DEFAULT_AUTO_INSTALL_UPDATES)++ /**+ * Whether the periodic update check may also download and install updates on its own,+ * with no tap. Off by default: this installs apps without the user present, so it is+ * strictly opt-in. Only ever acts on updates that install silently (see the worker).+ */+ val autoInstallUpdates: StateFlow<Boolean> = _autoInstallUpdates.asStateFlow()+ init { scope.launch { context.settingsDataStore.data .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }- .map { it[KEY_BACKGROUND_UPDATE_INSTALL] ?: DEFAULT_BACKGROUND_UPDATE_INSTALL }- .collect { _backgroundUpdateInstall.value = it }+ .collect { prefs ->+ _backgroundUpdateInstall.value = prefs.backgroundUpdateInstall()+ _autoInstallUpdates.value = prefs.autoInstallUpdates()+ } } } @@ -46,9 +59,36 @@ class SettingsRepository( context.settingsDataStore.edit { it[KEY_BACKGROUND_UPDATE_INSTALL] = enabled } } + suspend fun setAutoInstallUpdates(enabled: Boolean) {+ context.settingsDataStore.edit { it[KEY_AUTO_INSTALL_UPDATES] = enabled }+ }++ /**+ * One-shot read of the persisted values, for callers with no long-lived scope to+ * collect a flow — the [UpdateCheckWorker] is cold-started by WorkManager and needs the+ * committed choice, not the not-yet-populated flow default.+ */+ suspend fun readAutoInstallUpdates(): Boolean = read().autoInstallUpdates()++ suspend fun readBackgroundUpdateInstall(): Boolean = read().backgroundUpdateInstall()++ private suspend fun read(): Preferences =+ context.settingsDataStore.data+ .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }+ .first()++ private fun Preferences.backgroundUpdateInstall(): Boolean =+ this[KEY_BACKGROUND_UPDATE_INSTALL] ?: DEFAULT_BACKGROUND_UPDATE_INSTALL++ private fun Preferences.autoInstallUpdates(): Boolean =+ this[KEY_AUTO_INSTALL_UPDATES] ?: DEFAULT_AUTO_INSTALL_UPDATES+ companion object { const val DEFAULT_BACKGROUND_UPDATE_INSTALL = true+ const val DEFAULT_AUTO_INSTALL_UPDATES = false private val KEY_BACKGROUND_UPDATE_INSTALL = booleanPreferencesKey("background_update_installation")+ private val KEY_AUTO_INSTALL_UPDATES =+ booleanPreferencesKey("auto_install_updates") } }
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 3c0eef643a..f639d4d7a9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -7,6 +7,7 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager+import android.content.pm.ServiceInfo import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat@@ -16,13 +17,16 @@ import androidx.core.content.edit import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.ForegroundInfo import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.appstore.MainActivity import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.installer.InstallCoordinator import com.vayunmathur.appstore.data.play.PlayRepository+import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.room.buildDatabase@@ -36,13 +40,15 @@ import java.util.concurrent.TimeUnit * * The store used to require two manual taps — "Sync F-Droid", then "Check Play" — which * is not something anyone remembers to do, so an app installed here would sit on a stale- * version indefinitely. This refreshes the offline catalogues, asks Play about the+ * It refreshes the offline catalogues, asks Play about the * packages neither of them lists, and posts a notification only when the set of available * updates has actually changed since the last notification. *- * It deliberately does not install anything. Every install path in this store shows a- * verification outcome and, on most devices, a system confirmation dialog; doing that- * unattended would either bury the user in prompts or hide the outcome.+ * If the user has opted in to unattended updates ([SettingsRepository.autoInstallUpdates]),+ * it also downloads and installs — as a foreground service — the updates it can apply+ * silently: packages this store is the installer or update owner of, on API 31+ with+ * background installation enabled. Everything it can't install without a prompt is left to+ * the notification, exactly as before. Auto-install is off by default. */ class UpdateCheckWorker( private val context: Context,@@ -77,7 +83,27 @@ class UpdateCheckWorker( } val updates = (fromCatalog + fromPlay).distinctBy { it.packageName }- notifyIfChanged(updates.map { it.packageName }.toSortedSet(), updates.size)++ val settings = SettingsRepository(context, scope)+ val autoInstall = settings.readAutoInstallUpdates()+ // Unattended installs are only safe when they will not raise a dialog: silent+ // install requires API 31+ and the background-install toggle. Below that, or with it+ // off, fall back to notify-only regardless of the auto-install choice.+ val silentCapable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&+ settings.readBackgroundUpdateInstall()++ if (autoInstall && silentCapable && updates.isNotEmpty()) {+ val eligible = updates.filter { canSilentlyUpdate(it.packageName) }+ if (eligible.isNotEmpty()) {+ autoInstall(eligible, db, play)+ installedRepo.refresh()+ }+ // Only nag about the updates we could not apply on our own.+ val remaining = updates.filterNot { canSilentlyUpdate(it.packageName) }+ notifyIfChanged(remaining.map { it.packageName }.toSortedSet(), remaining.size)+ } else {+ notifyIfChanged(updates.map { it.packageName }.toSortedSet(), updates.size)+ } scope.cancel() Result.success()@@ -133,6 +159,99 @@ class UpdateCheckWorker( } } + /**+ * Download and silently install a set of updates, promoting the worker to a foreground+ * service for the duration so the OS doesn't kill it mid-install.+ *+ * Passes `backgroundUpdateInstall = { true }` because [canSilentlyUpdate] has already+ * confirmed each package will install without a prompt; the caller only reaches here+ * when the user's silent-install toggle is on.+ */+ private suspend fun autoInstall(apps: List<UnifiedApp>, db: AppDatabase, play: PlayRepository) {+ runCatching { setForeground(installingForegroundInfo(apps.size)) }+ val installer = InstallCoordinator(+ context = context,+ db = db,+ play = play,+ ownSigningCertificates = { ApkCertificates.selfSigners(context) },+ backgroundUpdateInstall = { true },+ )+ var installed = 0+ for (app in apps) {+ val outcome = runCatching { installer.install(app) }.getOrNull()+ if (outcome?.started == true) installed+++ }+ if (installed > 0) notifyInstalled(installed)+ }++ /**+ * Whether an update to [packageName] would install without a system dialog.+ *+ * Only true when this store is the package's installer of record — or, on API 34+, its+ * update owner. For anything else the OS would raise a confirmation the background job+ * can't usefully answer, so those are left to the notification instead.+ */+ private fun canSilentlyUpdate(packageName: String): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false+ return runCatching {+ val info = context.packageManager.getInstallSourceInfo(packageName)+ val self = context.packageName+ val ownsUpdate = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&+ info.updateOwnerPackageName == self+ ownsUpdate || info.installingPackageName == self+ }.getOrDefault(false)+ }++ private fun installingForegroundInfo(count: Int): ForegroundInfo {+ createChannel()+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.stat_sys_download)+ .setContentTitle(+ context.resources.getQuantityString(R.plurals.updates_installing, count, count)+ )+ .setOngoing(true)+ .setPriority(NotificationCompat.PRIORITY_LOW)+ .build()+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ ForegroundInfo(+ INSTALL_NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,+ )+ } else {+ ForegroundInfo(INSTALL_NOTIFICATION_ID, notification)+ }+ }++ private fun notifyInstalled(count: Int) {+ if (!canPostNotifications()) return+ createChannel()+ val open = PendingIntent.getActivity(+ context,+ 0,+ Intent(context, MainActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.stat_sys_download_done)+ .setContentTitle(+ context.resources.getQuantityString(R.plurals.updates_installed, count, count)+ )+ .setContentIntent(open)+ .setAutoCancel(true)+ .setPriority(NotificationCompat.PRIORITY_LOW)+ .build()+ runCatching {+ NotificationManagerCompat.from(context).notify(INSTALLED_NOTIFICATION_ID, notification)+ }+ }++ private fun canPostNotifications(): Boolean =+ Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||+ ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==+ PackageManager.PERMISSION_GRANTED+ private fun createChannel() { val manager = context.getSystemService(NotificationManager::class.java) ?: return manager.createNotificationChannel(@@ -148,6 +267,8 @@ class UpdateCheckWorker( private const val TAG = "UpdateCheckWorker" private const val CHANNEL_ID = "appstore-updates" private const val NOTIFICATION_ID = 4201+ private const val INSTALL_NOTIFICATION_ID = 4202+ private const val INSTALLED_NOTIFICATION_ID = 4203 private const val PREFS = "appstore-update-check" private const val KEY_LAST_NOTIFIED = "last_notified_packages"
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 2c481c6188..502096a4dc 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt@@ -31,6 +31,7 @@ import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.SettingsDivider import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.Text import java.text.SimpleDateFormat@@ -102,12 +103,22 @@ fun SourcesPage( item { Card(Modifier.fillMaxWidth()) {- SettingsSwitchRow(- title = stringResource(R.string.setting_background_updates_title),- supportingText = stringResource(R.string.setting_background_updates_summary),- checked = backgroundUpdateInstall,- onCheckedChange = { viewModel.setBackgroundUpdateInstall(it) },- )+ Column {+ SettingsSwitchRow(+ title = stringResource(R.string.setting_background_updates_title),+ supportingText = stringResource(R.string.setting_background_updates_summary),+ checked = backgroundUpdateInstall,+ onCheckedChange = { viewModel.setBackgroundUpdateInstall(it) },+ )+ SettingsDivider()+ SettingsSwitchRow(+ title = stringResource(R.string.setting_auto_install_updates_title),+ supportingText = stringResource(R.string.setting_auto_install_updates_summary),+ checked = autoInstallUpdates && backgroundUpdateInstall,+ enabled = backgroundUpdateInstall,+ onCheckedChange = { viewModel.setAutoInstallUpdates(it) },+ )+ } } }
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 df94a64c5e..d40ed03251 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -60,6 +60,9 @@ class AppStoreViewModel( /** On-by-default: updates to store-owned apps install without a per-app prompt. */ val backgroundUpdateInstall: StateFlow<Boolean> = settings.backgroundUpdateInstall + /** Off-by-default: the periodic check may also download and install updates unattended. */+ val autoInstallUpdates: StateFlow<Boolean> = settings.autoInstallUpdates+ /** SHA-256 of this app's own signing certificate — the Modern Apps trust root. */ val ownSigningCertificates: Set<String> by lazy { ApkCertificates.selfSigners(context) } @@ -724,6 +727,11 @@ class AppStoreViewModel( viewModelScope.launch { settings.setBackgroundUpdateInstall(enabled) } } + /** Turn fully unattended (no-tap) background update installation on or off. */+ fun setAutoInstallUpdates(enabled: Boolean) {+ viewModelScope.launch { settings.setAutoInstallUpdates(enabled) }+ }+ // --- 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 9c0909e968..fa6d93b407 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -72,10 +72,20 @@ <string name="updates_channel_description">Tells you when apps you installed here have a newer version.</string> <string name="setting_background_updates_title">Install updates in the background</string> <string name="setting_background_updates_summary">Update apps this store already installed without asking each time. First-time installs still ask for confirmation.</string>+ <string name="setting_auto_install_updates_title">Automatically install updates</string>+ <string name="setting_auto_install_updates_summary">Check for and install updates on their own, with no tap. Only applies to apps this store installed and can update silently; everything else still just notifies you.</string> <plurals name="updates_count"> <item quantity="one">%1$d update available</item> <item quantity="other">%1$d updates available</item> </plurals>+ <plurals name="updates_installing">+ <item quantity="one">Installing %1$d update…</item>+ <item quantity="other">Installing %1$d updates…</item>+ </plurals>+ <plurals name="updates_installed">+ <item quantity="one">Installed %1$d update</item>+ <item quantity="other">Installed %1$d updates</item>+ </plurals> <!-- Install actions and progress. --> <string name="action_install">Install</string>