@@ -246,9 +246,21 @@ class VectorCallActivity :
246246 == PackageManager .PERMISSION_GRANTED ) {
247247 // Only start the service if the app is in the foreground
248248 if (isAppInForeground()) {
249- Timber .tag(loggerTag.value).v(" Starting microphone foreground service" )
250- val intent = Intent (this , MicrophoneAccessService ::class .java)
251- ContextCompat .startForegroundService(this , intent)
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 && callState != null ) {
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+ }
263+ }
252264 } else {
253265 Timber .tag(loggerTag.value).v(" App is not in foreground; cannot start microphone service" )
254266 }
@@ -269,6 +281,9 @@ class VectorCallActivity :
269281
270282 override fun onPause () {
271283 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
272287 startMicrophoneService()
273288 }
274289
0 commit comments