@@ -246,15 +246,20 @@ class VectorCallActivity :
246
246
== PackageManager .PERMISSION_GRANTED ) {
247
247
// Only start the service if the app is in the foreground
248
248
if (isAppInForeground()) {
249
- // Starting in Android 14, you can't create a microphone foreground service while your app is in
250
- // the background. If we call startForegroundService the app will crash.
251
- // https://github.com/element-hq/element-android/issues/8964
252
- if (Build .VERSION .SDK_INT < Build .VERSION_CODES .UPSIDE_DOWN_CAKE ) {
253
- Timber .tag(loggerTag.value).v(" Starting microphone foreground service" )
254
- val intent = Intent (this , MicrophoneAccessService ::class .java)
255
- ContextCompat .startForegroundService(this , intent)
256
- } else {
257
- Timber .tag(loggerTag.value).v(" App is in running Android 14+; cannot start microphone service" )
249
+ withState(callViewModel) {
250
+ // Starting in Android 14, you can't create a microphone foreground service while your app is in
251
+ // the background. If we call startForegroundService while the call state is ringing (i.e. the
252
+ // user has not interacted with the device at all) the app will crash. Make sure the call has
253
+ // already been answered before starting the MicrophoneAccessService
254
+ // https://github.com/element-hq/element-android/issues/8964
255
+ val callState = it.callState.invoke()
256
+ if (callState !is CallState .LocalRinging && callState !is CallState .Ended ) {
257
+ Timber .tag(loggerTag.value).v(" Starting microphone foreground service" )
258
+ val intent = Intent (this , MicrophoneAccessService ::class .java)
259
+ ContextCompat .startForegroundService(this , intent)
260
+ } else {
261
+ Timber .tag(loggerTag.value).v(" Call is in ringing or ended state; cannot start microphone service. callState: $callState " )
262
+ }
258
263
}
259
264
} else {
260
265
Timber .tag(loggerTag.value).v(" App is not in foreground; cannot start microphone service" )
@@ -276,6 +281,9 @@ class VectorCallActivity :
276
281
277
282
override fun onPause () {
278
283
super .onPause()
284
+
285
+ // Start the microphone service to keep access to the microphone when the call is in the background
286
+ // https://github.com/element-hq/element-android/issues/8881
279
287
startMicrophoneService()
280
288
}
281
289
0 commit comments