fix: Add foregroundServiceType/onTimeout() to prevent crash (#163)

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
This commit is contained in:
Nik Clayton 2023-10-15 13:07:35 +02:00 committed by GitHub
parent 34c53a67e0
commit 99dd15ea89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 0 deletions

View File

@ -200,6 +200,7 @@
</service>
<service android:name=".service.SendStatusService"
android:foregroundServiceType="shortService"
android:exported="false" />
<provider

View File

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