1616
1717package im.vector.app.features.call
1818
19+ import android.Manifest
1920import android.app.Activity
2021import android.app.KeyguardManager
2122import android.app.PictureInPictureParams
@@ -41,6 +42,8 @@ import androidx.core.content.getSystemService
4142import androidx.core.util.Consumer
4243import androidx.core.view.isInvisible
4344import androidx.core.view.isVisible
45+ import androidx.lifecycle.Lifecycle
46+ import androidx.lifecycle.ProcessLifecycleOwner
4447import com.airbnb.mvrx.Fail
4548import com.airbnb.mvrx.Mavericks
4649import com.airbnb.mvrx.viewModel
@@ -248,16 +251,26 @@ class VectorCallActivity :
248251 }
249252
250253 private fun startMicrophoneService () {
251- if (ContextCompat .checkSelfPermission(this , android.Manifest .permission.RECORD_AUDIO ) == PackageManager .PERMISSION_GRANTED &&
252- ContextCompat .checkSelfPermission(this , android.Manifest .permission.FOREGROUND_SERVICE_MICROPHONE ) == PackageManager .PERMISSION_GRANTED ) {
253- Timber .tag(loggerTag.value).d(" Starting MicrophoneAccessService." )
254- val intent = Intent (this , MicrophoneAccessService ::class .java)
255- ContextCompat .startForegroundService(this , intent)
254+ if (ContextCompat .checkSelfPermission(this , Manifest .permission.RECORD_AUDIO )
255+ == PackageManager .PERMISSION_GRANTED ) {
256+
257+ // Only start the service if the app is in the foreground
258+ if (isAppInForeground()) {
259+ Timber .tag(loggerTag.value).v(" Starting microphone foreground service" )
260+ val intent = Intent (this , MicrophoneAccessService ::class .java)
261+ ContextCompat .startForegroundService(this , intent)
262+ } else {
263+ Timber .tag(loggerTag.value).v(" App is not in foreground; cannot start microphone service" )
264+ }
256265 } else {
257- Timber .tag(loggerTag.value).w( " Permissions not granted. Cannot start MicrophoneAccessService. " )
266+ Timber .tag(loggerTag.value).v( " Microphone permission not granted; cannot start service " )
258267 }
259268 }
260269
270+ private fun isAppInForeground (): Boolean {
271+ val appProcess = ProcessLifecycleOwner .get().lifecycle.currentState.isAtLeast(Lifecycle .State .STARTED )
272+ return appProcess
273+ }
261274 private fun stopMicrophoneService () {
262275 Timber .tag(loggerTag.value).d(" Stopping MicrophoneAccessService (if needed)." )
263276 val intent = Intent (this , MicrophoneAccessService ::class .java)
0 commit comments