Don't use Context#startForegroundService() because we may get killed

If the foreground service doesn't have anything to do and terminates quickly, the system will kill us, even though the service had called startForeground(). To prevent this, we don't promise that our service will be a foreground service. We can still be a foreground service, but escape the punishment if we are too quick.
This commit is contained in:
Torsten Grote 2024-08-22 17:36:26 -03:00
parent 639947b87e
commit d266c36c91
No known key found for this signature in database
GPG key ID: 3E5F77D92CF891FF
4 changed files with 6 additions and 4 deletions

View file

@ -123,7 +123,8 @@ internal class AppDataRestoreManager(
RestoreBackupResult(context.getString(R.string.restore_set_error))
)
} else {
context.startForegroundService(foregroundServiceIntent)
// don't use startForeground(), because we may stop it sooner than the system likes
context.startService(foregroundServiceIntent)
}
}

View file

@ -90,7 +90,8 @@ internal class ApkRestore(
val i = Intent(context, RestoreService::class.java)
val autoRestore = backupStateManager.isAutoRestoreEnabled
try {
context.startForegroundService(i)
// don't use startForeground(), because we may stop it sooner than the system likes
context.startService(i)
// disable auto-restore before installing apps, if it was enabled before
if (autoRestore) backupManager.setAutoRestore(false)
reInstallApps(backup, packages.asIterable().reversed())

View file

@ -131,7 +131,7 @@ internal class ApkBackupRestoreTest : TransportTest() {
// related to starting/stopping service
every { strictContext.packageName } returns "org.foo.bar"
every {
strictContext.startForegroundService(any())
strictContext.startService(any())
} returns ComponentName(strictContext, "org.foo.bar.Class")
every { strictContext.stopService(any()) } returns true

View file

@ -112,7 +112,7 @@ internal class ApkRestoreTest : TransportTest() {
// related to starting/stopping service
every { strictContext.packageName } returns "org.foo.bar"
every {
strictContext.startForegroundService(any())
strictContext.startService(any())
} returns ComponentName(strictContext, "org.foo.bar.Class")
every { strictContext.stopService(any()) } returns true
}