Skip to content

Commit

Permalink
refactor: catch exception when starting service in the background
Browse files Browse the repository at this point in the history
  • Loading branch information
andrekir committed Oct 19, 2023
1 parent f3e57c0 commit b87257a
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions app/src/main/java/com/geeksville/mesh/service/MeshServiceStarter.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.geeksville.mesh.service

import android.content.ComponentName
import android.app.ForegroundServiceStartNotAllowedException
import android.content.Context
import android.os.Build
import androidx.work.*
import androidx.work.BackoffPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.geeksville.mesh.BuildConfig
import java.util.concurrent.TimeUnit

Expand All @@ -26,15 +30,6 @@ class ServiceStarter(
}
}

private fun Context.startMeshService(): ComponentName? {
val intent = MeshService.createIntent()
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}

/**
* Just after boot the android OS is super busy, so if we call startForegroundService then, our
* thread might be stalled long enough to expose this Google/Samsung bug:
Expand Down Expand Up @@ -63,5 +58,19 @@ fun MeshService.Companion.startService(context: Context) {
// listening for the bluetooth packets arriving from the radio. And when they arrive forward them
// to Signal or whatever.
info("Trying to start service debug=${BuildConfig.DEBUG}")
requireNotNull(context.startMeshService()) { "Failed to start service" }

val intent = createIntent()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
try {
context.startForegroundService(intent)
} catch (ex: ForegroundServiceStartNotAllowedException) {
errormsg("Unable to start service: ${ex.message}")
}
} else {
context.startForegroundService(intent)
}
} else {
context.startService(intent)
}
}

0 comments on commit b87257a

Please sign in to comment.