From 4f5c6a5fd1cce7839bbc5578145dd9e998fbf440 Mon Sep 17 00:00:00 2001 From: andrekir Date: Thu, 25 Jul 2024 18:04:11 -0300 Subject: [PATCH] refactor: implement `ServiceCompat.startForeground` with error handling - replaces `Service.startForeground` with `ServiceCompat.startForeground` with support for different API levels; - adds try-catch block to handle exceptions and report errors if startForeground fails. references: - https://issuetracker.google.com/issues/307329994 - https://developer.android.com/develop/background-work/services/foreground-services#start --- .../com/geeksville/mesh/service/MeshService.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/geeksville/mesh/service/MeshService.kt b/app/src/main/java/com/geeksville/mesh/service/MeshService.kt index 110b7b5a7..abfb77d3d 100644 --- a/app/src/main/java/com/geeksville/mesh/service/MeshService.kt +++ b/app/src/main/java/com/geeksville/mesh/service/MeshService.kt @@ -293,14 +293,20 @@ class MeshService : Service(), Logging { // but if we don't really need foreground we immediately stop it. val notification = serviceNotifications.createServiceStateNotification(notificationSummary) - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { - startForeground( + try { + ServiceCompat.startForeground( + this, serviceNotifications.notifyId, notification, - ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE + } else { + 0 + }, ) - } else { - startForeground(serviceNotifications.notifyId, notification) + } catch (ex: Exception) { + errormsg("startForeground failed", ex) + return START_NOT_STICKY } return if (!wantForeground) { ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)