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
pull/1141/head^2
andrekir 2024-07-25 18:04:11 -03:00
rodzic f4016bf9ef
commit 4f5c6a5fd1
1 zmienionych plików z 11 dodań i 5 usunięć

Wyświetl plik

@ -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)