appstore: make background auto-installs actually install (#898)
- Commit
befac0289e6ef8d6469804f28f4a89b432ec96eb- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 05:02 UTC (1 month ago)
- Parents
4b4a39a
Background "Automatically install updates" checked for updates but never installed them: the worker committed PackageInstaller sessions that the OS always answered with a confirmation prompt, and that prompt was then silently dropped while the app was in the background. Root cause is two defects compounding into one symptom: 1. Missing UPDATE_PACKAGES_WITHOUT_USER_ACTION permission. SessionInstaller commits updates with USER_ACTION_NOT_REQUIRED, but the system only honours that flag for holders of this permission on API 33+ targets (this module targets SDK 37). Without it every background commit - even for apps this store installed and owns - degrades to STATUS_PENDING_USER_ACTION. 2. InstallStatusReceiver dropped that prompt in the background. It called startActivity(confirmIntent) from a manifest receiver; with no visible window, background-activity-launch restrictions block that launch silently - no exception, no notification - so the update stalled forever. Foreground taps worked (a visible window exempts the launch), which is why manual updates succeeded while background ones never landed. Changes: - AndroidManifest.xml: declare UPDATE_PACKAGES_WITHOUT_USER_ACTION (normal, auto-granted) so silent commits are honoured for store-owned packages. - InstallStatusReceiver: when no process of this app is in the foreground (ActivityManager check), post a high-priority notification carrying the system prompt as its content intent instead of a doomed startActivity. Foreground behaviour is unchanged. Notification IDs are per-package so concurrent prompts from an update-all run do not overwrite each other. - Kept the in-flight UpdateCheckWorker change: a 1.5 s settle delay after autoInstall before re-reading the device (PackageInstaller commits asynchronously) plus re-notifying for attempted-but-still-outstanding updates, so the run no longer reports success for installs that have not landed. Same settle value the foreground update-all path already uses. User-visible effect: with auto-install on, store-installed apps now update silently in the background; updates the OS still requires confirmation for surface a tappable "Update ready" notification instead of stalling. Verified with ./gradlew :appstore:compileDevKotlin (BUILD SUCCESSFUL). Needs on-device testing: enable auto-install, install an app via the store, await a newer version, and confirm the silent background install; also confirm the notification path for a package the OS still prompts for.
Diff
appstore/src/main/AndroidManifest.xml
diff --git a/appstore/src/main/AndroidManifest.xml b/appstore/src/main/AndroidManifest.xmlindex 126a387507..573bfdb05f 100644--- a/appstore/src/main/AndroidManifest.xml+++ b/appstore/src/main/AndroidManifest.xml@@ -7,6 +7,11 @@ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" /> <uses-permission android:name="android.permission.ENFORCE_UPDATE_OWNERSHIP" />+ <!-- Silent background updates: SessionInstaller commits with USER_ACTION_NOT_REQUIRED,+ which the system only honours for holders of this (normal, auto-granted) permission+ on API 33+ targets. Without it every background commit degrades to a confirmation+ prompt the background job cannot answer, so nothing ever installs (#898). -->+ <uses-permission android:name="android.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION" /> <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
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 3e96b6d124..20f0b0bdb1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -36,6 +36,7 @@ import com.vayunmathur.library.network.TrustBundle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay import java.util.concurrent.TimeUnit /**@@ -207,13 +208,27 @@ class UpdateCheckWorker( ) return }- val eligible = updates.filter { canSilentlyUpdate(it.packageName) }+ val (eligible, foreign) = updates.partition { canSilentlyUpdate(it.packageName) } if (eligible.isNotEmpty()) { autoInstall(eligible, env)+ // PackageInstaller commits asynchronously, so a just-committed install may+ // not have landed yet. Give it a moment before re-reading, or still-pending+ // updates read as stuck and get nagged about immediately (#898). Same wait+ // the foreground "update all" applies before its own re-read.+ delay(INSTALL_SETTLE_MS) env.installedRepo.refresh() }- // Only nag about the updates we could not apply on our own.- val remaining = updates.filterNot { canSilentlyUpdate(it.packageName) }+ // Only nag about the updates we could not apply on our own: the ones we never+ // attempted plus the ones we attempted but that are still outstanding. The OS+ // may answer a "silent" commit with a confirmation prompt the background job+ // cannot usefully answer (see InstallStatusReceiver), so an attempted update+ // whose installed copy is still behind needs its tap after all (#898).+ val installedVersions = env.installedRepo.updatable.value+ .associate { it.packageName to it.versionCode }+ val stillOutstanding = eligible.filter { update ->+ (installedVersions[update.packageName] ?: 0L) < update.versionCode+ }+ val remaining = (foreign + stillOutstanding).distinctBy { it.packageName } notifyIfChanged( remaining.map { it.packageName }.toSortedSet(), remaining.size,@@ -425,6 +440,15 @@ class UpdateCheckWorker( private const val PREFS = "appstore-update-check" private const val KEY_LAST_NOTIFIED = "last_notified_packages" + /**+ * How long to wait after committing installs before re-reading the device.+ *+ * PackageInstaller commits asynchronously — a just-committed install may not+ * have landed yet, and without the wait the re-read reports every update as+ * still outstanding. Same value as the foreground "update all" settle delay.+ */+ private const val INSTALL_SETTLE_MS = 1_500L+ /** * Twelve hours, and no immediate run. *
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.ktindex 313184858b..9def732c61 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt@@ -1,9 +1,20 @@ package com.vayunmathur.appstore.data.installer +import android.Manifest+import android.app.ActivityManager+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageInstaller+import android.content.pm.PackageManager+import android.os.Build+import android.os.Process+import androidx.core.app.ActivityCompat+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat import com.vayunmathur.library.log.Log import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.RestrictedPackages@@ -30,6 +41,7 @@ class InstallStatusReceiver : BroadcastReceiver() { const val ACTION_INSTALL_STATUS = "com.vayunmathur.appstore.INSTALL_STATUS" private const val TAG = "InstallStatusReceiver" private const val UNKNOWN_STATUS = -1+ private const val CHANNEL_ID = "appstore-installs" } override fun onReceive(context: Context, intent: Intent) {@@ -38,7 +50,7 @@ class InstallStatusReceiver : BroadcastReceiver() { val pkg = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME) when (status) {- PackageInstaller.STATUS_PENDING_USER_ACTION -> forwardUserAction(context, intent)+ PackageInstaller.STATUS_PENDING_USER_ACTION -> forwardUserAction(context, intent, pkg) PackageInstaller.STATUS_SUCCESS -> reportSuccess(context, pkg) // The user backing out of the system prompt is not a failure worth reporting back. PackageInstaller.STATUS_FAILURE_ABORTED -> reportAborted(pkg)@@ -46,26 +58,97 @@ class InstallStatusReceiver : BroadcastReceiver() { } } - private fun forwardUserAction(context: Context, intent: Intent) {+ /**+ * Surface the system's install-confirmation prompt.+ *+ * With the app in the foreground the prompt is started directly, the same as+ * before. In the background `startActivity` from a manifest receiver is blocked+ * by background-activity-launch restrictions — silently, with no exception — so+ * a background commit's prompt used to vanish without a trace and the update+ * never installed (#898). Now, when no process of this app is in the foreground,+ * a notification carrying the prompt is posted instead so the user can tap it.+ */+ private fun forwardUserAction(context: Context, intent: Intent, packageName: String?) { // Forward user action intent- val userAction = if (android.os.Build.VERSION.SDK_INT >= 33) {+ val userAction = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)- }- try {- userAction?.let {- it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- context.startActivity(it)+ } ?: return+ userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (isForeground(context)) {+ try {+ context.startActivity(userAction)+ } catch (expected: android.content.ActivityNotFoundException) {+ Log.status(TAG, "Failed to start user action: ${expected.message}")+ } catch (expected: SecurityException) {+ Log.status(TAG, "Failed to start user action: ${expected.message}") }- } catch (expected: android.content.ActivityNotFoundException) {- Log.status(TAG, "Failed to start user action: ${expected.message}")- } catch (expected: SecurityException) {- Log.status(TAG, "Failed to start user action: ${expected.message}")+ return+ }+ notifyConfirm(context, userAction, packageName)+ }++ private fun isForeground(context: Context): Boolean {+ val manager =+ context.getSystemService(ActivityManager::class.java) ?: return false+ return manager.runningAppProcesses.orEmpty().any {+ it.uid == Process.myUid() &&+ it.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND+ }+ }++ /**+ * Post the system prompt behind a tap: the confirmation intent the store cannot+ * launch itself in the background becomes the notification's content intent.+ */+ private fun notifyConfirm(context: Context, userAction: Intent, packageName: String?) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+ ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=+ PackageManager.PERMISSION_GRANTED+ ) {+ return+ }+ createChannel(context)+ val confirm = PendingIntent.getActivity(+ context,+ packageName.hashCode(),+ userAction,+ 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.getString(R.string.install_confirm_title, packageName.orEmpty())+ )+ .setContentText(context.getString(R.string.install_confirm_body))+ .setContentIntent(confirm)+ .setAutoCancel(true)+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .build()+ runCatching {+ // Per-package ID: several background prompts can pend at once (an "update+ // all" run), and a single shared ID would let each new one overwrite the last.+ NotificationManagerCompat.from(context)+ .notify(confirmNotificationId(packageName), notification) } } + private fun createChannel(context: Context) {+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_ID,+ context.getString(R.string.install_confirm_channel_name),+ NotificationManager.IMPORTANCE_HIGH,+ ).apply { description = context.getString(R.string.install_confirm_channel_description) }+ )+ }++ private fun confirmNotificationId(packageName: String?): Int =+ "install-confirm:${packageName.orEmpty()}".hashCode()+ private fun reportSuccess(context: Context, pkg: String?) { Log.status(TAG, "Install success for $pkg") pkg?.let { InstallEvents.publish(InstallResult(it, success = true)) }
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 7187bedef4..ccb2410325 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -145,6 +145,13 @@ <string name="install_failure_storage">not enough storage</string> <string name="install_failure_conflict">it conflicts with a version already installed</string> <string name="install_failure_unknown">the system rejected it</string>+ <!-- Install-confirmation notification: posted when a background install needs the+ user, because the system prompt cannot be shown while the app is in the+ background. %1$s is the package name. -->+ <string name="install_confirm_title">Update ready for %1$s</string>+ <string name="install_confirm_body">Tap to confirm the update.</string>+ <string name="install_confirm_channel_name">Install confirmations</string>+ <string name="install_confirm_channel_description">Asks you to confirm an update that arrived while the store was in the background.</string> <string name="uninstaller_unavailable">Couldn\'t open the uninstaller</string> <string name="share_app_text">%1$s — %2$s</string>