Handle ForegroundServiceStartNotAllowedException when starting the VM
When the activity is in the background for a while(more than 5s), and
startForegroundService(VmLauncherService) is called, it causes the
error.
This fix remedies the error: Instead of causing the crash, gracefully
finishing the activity. I think it's mostly okay because the app is
already in the background. And a user might not be aware that it is
re-started.
Bug: 401869633
Test: add sleep or postDelay before startVm to test it..
Change-Id: I7abde24dde5d7f2aa4394870bf4faf820d212dea
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index 35c5570..7502415 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -361,8 +361,10 @@
.build()
)
.build()
-
- run(this, this, notification, getDisplayInfo())
+ run(this, this, notification, getDisplayInfo()).onFailure {
+ Log.e(TAG, "Failed to start VM.", it)
+ finish()
+ }
}
@VisibleForTesting
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index 2d7468d..c49b7cd 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
@@ -15,6 +15,7 @@
*/
package com.android.virtualization.terminal
+import android.app.ForegroundServiceStartNotAllowedException
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
@@ -506,7 +507,7 @@
callback: VmLauncherServiceCallback?,
notification: Notification?,
displayInfo: DisplayInfo,
- ) {
+ ): Result<Unit> {
val i = getMyIntent(context)
val resultReceiver: ResultReceiver =
object : ResultReceiver(Handler(Looper.myLooper()!!)) {
@@ -529,7 +530,12 @@
i.putExtra(Intent.EXTRA_RESULT_RECEIVER, getResultReceiverForIntent(resultReceiver))
i.putExtra(EXTRA_NOTIFICATION, notification)
i.putExtra(EXTRA_DISPLAY_INFO, displayInfo)
- context.startForegroundService(i)
+ return try {
+ context.startForegroundService(i)
+ Result.success(Unit)
+ } catch (e: ForegroundServiceStartNotAllowedException) {
+ Result.failure<Unit>(e)
+ }
}
private fun getResultReceiverForIntent(r: ResultReceiver): ResultReceiver {