@@ -21,6 +21,8 @@ import kotlinx.coroutines.CoroutineScope
21
21
import kotlinx.coroutines.Dispatchers
22
22
import kotlinx.coroutines.delay
23
23
import kotlinx.coroutines.launch
24
+ import kotlinx.coroutines.sync.Mutex
25
+ import kotlinx.coroutines.sync.withLock
24
26
import kotlinx.serialization.Serializable
25
27
import kotlinx.serialization.Transient
26
28
import kotlinx.serialization.json.Json
@@ -84,6 +86,11 @@ class WebViewAudioManager(
84
86
?.newWakeLock(PowerManager .PROXIMITY_SCREEN_OFF_WAKE_LOCK , " ${webView.context.packageName} :ProximitySensorCallWakeLock" )
85
87
}
86
88
89
+ /* *
90
+ * Used to ensure that only one coroutine can access the proximity sensor wake lock at a time, preventing re-acquiring or re-releasing it.
91
+ */
92
+ private val proximitySensorMutex = Mutex ()
93
+
87
94
/* *
88
95
* This listener tracks the current communication device and updates the WebView when it changes.
89
96
*/
@@ -208,8 +215,12 @@ class WebViewAudioManager(
208
215
return
209
216
}
210
217
211
- if (proximitySensorWakeLock?.isHeld == true ) {
212
- proximitySensorWakeLock?.release()
218
+ coroutineScope.launch {
219
+ proximitySensorMutex.withLock {
220
+ if (proximitySensorWakeLock?.isHeld == true ) {
221
+ proximitySensorWakeLock?.release()
222
+ }
223
+ }
213
224
}
214
225
215
226
audioManager.mode = AudioManager .MODE_NORMAL
@@ -397,13 +408,17 @@ class WebViewAudioManager(
397
408
398
409
expectedNewCommunicationDeviceId = null
399
410
400
- @Suppress(" WakeLock" , " WakeLockTimeout" )
401
- if (device?.type == AudioDeviceInfo .TYPE_BUILTIN_EARPIECE && proximitySensorWakeLock?.isHeld == false ) {
402
- // If the device is the built-in earpiece, we need to acquire the proximity sensor wake lock
403
- proximitySensorWakeLock?.acquire()
404
- } else if (proximitySensorWakeLock?.isHeld == true ) {
405
- // If the device is no longer the earpiece, we need to release the wake lock
406
- proximitySensorWakeLock?.release()
411
+ coroutineScope.launch {
412
+ proximitySensorMutex.withLock {
413
+ @Suppress(" WakeLock" , " WakeLockTimeout" )
414
+ if (device?.type == AudioDeviceInfo .TYPE_BUILTIN_EARPIECE && proximitySensorWakeLock?.isHeld == false ) {
415
+ // If the device is the built-in earpiece, we need to acquire the proximity sensor wake lock
416
+ proximitySensorWakeLock?.acquire()
417
+ } else if (proximitySensorWakeLock?.isHeld == true ) {
418
+ // If the device is no longer the earpiece, we need to release the wake lock
419
+ proximitySensorWakeLock?.release()
420
+ }
421
+ }
407
422
}
408
423
}
409
424
0 commit comments