Skip to content

Commit

Permalink
fix: Add foregroundServiceType/onTimeout() to prevent crash (#163)
Browse files Browse the repository at this point in the history
Android 14 (SDK 34) requires a `foregroundServiceType` and `onTimeout()`
implementation for foreground services, otherwise creating the service
will crash.

Do this. If `SendStatusService` does timeout then any pending statuses
are marked as failed, saved to drafts, and the user is informed.

Fixes #162
  • Loading branch information
nikclayton authored Oct 15, 2023
1 parent 34c53a6 commit 99dd15e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@
</service>

<service android:name=".service.SendStatusService"
android:foregroundServiceType="shortService"
android:exported="false" />

<provider
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/app/pachli/service/SendStatusService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import android.os.Build
import android.os.IBinder
import android.os.Parcelable
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
Expand Down Expand Up @@ -43,6 +44,7 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.parcelize.Parcelize
import retrofit2.HttpException
import java.util.concurrent.ConcurrentHashMap
Expand Down Expand Up @@ -291,6 +293,17 @@ class SendStatusService : Service() {
}
}

@RequiresApi(Build.VERSION_CODES.N)
override fun onTimeout(startId: Int) {
// Android wants the service to shut down. Fail any statuses that still need to be sent
// and shut down. See https://developer.android.com/about/versions/14/changes/fgs-types-required
runBlocking {
statusesToSend.forEach { (i, _) ->
failSending(i) // Will stop the service when there are no more statuses
}
}
}

private suspend fun failSending(statusId: Int) {
val failedStatus = statusesToSend.remove(statusId)
if (failedStatus != null) {
Expand Down

0 comments on commit 99dd15e

Please sign in to comment.