librepods icon indicating copy to clipboard operation
librepods copied to clipboard

[Android/rewrite] Disconnecting AirPods in Android settings doesn't release them, so they come back and take audio from my Mac

Open oenderg opened this issue 2 weeks ago • 0 comments

App version: 2.0.0-alpha.4 (GitHub release) Device: OnePlus 13 (CPH2653) Android / OS version: OxygenOS 16.0.10.501 Root / hook method: KernelSU, LibrePods root module installed. VendorID hook ("act as Apple device") off. AirPods model: AirPods Pro 3 AirPods firmware: 9B47

What happened

I use my AirPods with my Mac and phone. When I disconnect them on the phone (Bluetooth settings → Disconnect), they reconnect to the phone about 40 seconds later on their own. The next notification on the phone then takes the audio, and the Mac goes silent while still thinking it has the AirPods.

None of the auto-connect options are on.

Cause

Android's Disconnect only closes A2DP and HFP. LibrePods' AACP socket stays open, so the ACL link never drops. The phone is still a connected host as far as the AirPods are concerned, so they reopen A2DP/HFP to it themselves:

22:47:52.083 BluetoothAdapterServiceBinder: disconnectAllEnabledProfiles: device=..:55:F3
22:47:52.088 A2dpService: connectionStateChanged ... 2->3
22:48:26.164 BatteryInfoPacket: ...        <- AACP still receiving
22:48:33.837 btm_sec_l2cap_access_req: is_originator:false, psm=0x0003
22:48:34.023 A2dpStateMachine: Incoming A2DP Connecting request accepted

LibrePods never sees ACL_DISCONNECTED, so it never lets go.

A related path: onDeviceConnected() (ACL_CONNECTED / UUID) and AppleDevice's init (currentState == AVAILABLE) open AACP whenever there's a link, even if the phone doesn't have the audio. That's the same thing #784 / #804 were about in the old service.

What I tried

I patched LibrePodsService.kt on top of the alpha.4 tag (patch below):

  1. On A2DP/HFP CONNECTION_STATE_CHANGED → disconnected, wait 3 s. If neither profile is connected and LibrePods didn't drop the audio itself (disconnect when not wearing), call device.disconnect().
  2. Only attach AACP in the background when A2DP or HFP is connected or connecting. Also attach when a profile connects, so a normal connect still works.

Tested on the phone above:

  • Disconnect in settings: AACP closed after 3.5 s, the ACL dropped right after, and the AirPods stayed on the Mac.
  • Connect from settings: LibrePods attached about 3 s later, as before.

I know the service is being rewritten, so take it as a pointer rather than a PR.

Patch (against rewrite-v2.0.0-alpha.4)
diff --git a/android/app/src/main/kotlin/me/kavishdevar/librepods/services/LibrePodsService.kt b/android/app/src/main/kotlin/me/kavishdevar/librepods/services/LibrePodsService.kt
index 7409d98..ab22e1f 100644
--- a/android/app/src/main/kotlin/me/kavishdevar/librepods/services/LibrePodsService.kt
+++ b/android/app/src/main/kotlin/me/kavishdevar/librepods/services/LibrePodsService.kt
@@ -8,8 +8,11 @@ import android.app.NotificationManager
 import android.app.PendingIntent
 import android.app.Service
 import android.appwidget.AppWidgetManager
+import android.bluetooth.BluetoothA2dp
 import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothHeadset
 import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
 import android.bluetooth.le.ScanSettings
 import android.content.BroadcastReceiver
 import android.content.ComponentName
@@ -41,6 +44,7 @@ import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.Job
 import kotlinx.coroutines.SupervisorJob
 import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
 import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.asStateFlow
 import kotlinx.coroutines.flow.update
@@ -79,12 +83,18 @@ import me.kavishdevar.librepods.presentation.widgets.BatteryWidget
 import me.kavishdevar.librepods.utils.MediaController
 import me.kavishdevar.librepods.utils.calculateLevel
 import java.time.ZoneOffset
+import java.util.Collections
+import java.util.concurrent.ConcurrentHashMap
 import kotlin.collections.getOrNull
 import kotlin.time.Duration
 import kotlin.time.toJavaInstant
 
 private const val TAG = "LibrePodsService"
 
+// A2DP and HFP disconnect within a few hundred ms of each other; wait this long
+// before deciding the user disconnected the device's audio.
+private const val AUDIO_RELEASE_GRACE_MS = 3_000L
+
 @SuppressLint("MissingPermission")
 class LibrePodsService: Service() {
     inner class LocalBinder : Binder() {
@@ -154,6 +164,20 @@ class LibrePodsService: Service() {
         (application as LibrePodsApplication).proximityCardWindow
     }
 
+    // Used to check whether this phone actually has a device's audio before
+    // LibrePods attaches to it in the background. While the AACP socket is open
+    // the Bluetooth link stays up, and the AirPods treat the phone as a connected
+    // host and bring A2DP/HFP back on their own.
+    @Volatile private var a2dpProxy: BluetoothA2dp? = null
+    @Volatile private var headsetProxy: BluetoothHeadset? = null
+
+    // Devices whose audio LibrePods itself dropped ("disconnect when not
+    // wearing"). Their AACP link is kept so ear detection can restore audio.
+    private val audioReleasedByLibrePods: MutableSet<MacAddress> =
+        Collections.synchronizedSet(mutableSetOf())
+
+    private val pendingAudioReleaseChecks = ConcurrentHashMap<MacAddress, Job>()
+
     @Suppress("unused")
     private fun observeCameraState() {
         CoroutineScope(Dispatchers.IO).launch {
@@ -269,6 +293,8 @@ class LibrePodsService: Service() {
 
         registerBluetoothReceivers()
 
+        registerAudioProfileProxies()
+
         loadDevices()
 
         bleManager.start()
@@ -340,6 +366,7 @@ class LibrePodsService: Service() {
 
     override fun onDestroy() {
         unregisterBluetoothReceivers()
+        closeAudioProfileProxies()
         bleManager.stop()
         serviceCoroutineScope.cancel("Service stopped")
         super.onDestroy()
@@ -360,6 +387,20 @@ class LibrePodsService: Service() {
             return
         }
 
+        // A link can come up without this phone having the audio: an SDP query,
+        // a brief page from the AirPods, or Android's own reconnect attempt.
+        // Attaching AACP then holds the link open and the AirPods move their
+        // audio here, taking it from whichever device was using them. Attach
+        // once A2DP or HFP is connected instead (see onAudioProfileStateChanged).
+        if (isAudioConnected(bluetoothDevice) != true) {
+            Log.i(
+                TAG,
+                "Not attaching to ${device.macAddress.toRedactedString()}: its audio isn't connected to this phone"
+            )
+            _devices.update { it + (device.macAddress to device) }
+            return
+        }
+
         when (device) {
             is AppleDevice -> CoroutineScope(Dispatchers.IO).launch {
                 Log.i(TAG, "Loading device ${device.macAddress.toRedactedString()} from db")
@@ -461,6 +502,108 @@ class LibrePodsService: Service() {
                     )
 
                     BluetoothDevice.ACTION_UUID -> onDeviceConnected(bluetoothDevice)
+
+                    BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED,
+                    BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> onAudioProfileStateChanged(
+                        bluetoothDevice,
+                        intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)
+                    )
+                }
+            }
+        }
+    }
+
+    private val audioProfileListener = object : BluetoothProfile.ServiceListener {
+        override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
+            when (profile) {
+                BluetoothProfile.A2DP -> a2dpProxy = proxy as BluetoothA2dp
+                BluetoothProfile.HEADSET -> headsetProxy = proxy as BluetoothHeadset
+                else -> return
+            }
+            // Devices loaded before both proxies were ready weren't attached.
+            if (a2dpProxy != null && headsetProxy != null) attachToDevicesWithAudio()
+        }
+
+        override fun onServiceDisconnected(profile: Int) {
+            when (profile) {
+                BluetoothProfile.A2DP -> a2dpProxy = null
+                BluetoothProfile.HEADSET -> headsetProxy = null
+            }
+        }
+    }
+
+    private fun registerAudioProfileProxies() {
+        val adapter = getSystemService(BluetoothManager::class.java).adapter ?: return
+        adapter.getProfileProxy(this, audioProfileListener, BluetoothProfile.A2DP)
+        adapter.getProfileProxy(this, audioProfileListener, BluetoothProfile.HEADSET)
+    }
+
+    private fun closeAudioProfileProxies() {
+        val adapter = getSystemService(BluetoothManager::class.java).adapter ?: return
+        a2dpProxy?.let { adapter.closeProfileProxy(BluetoothProfile.A2DP, it) }
+        headsetProxy?.let { adapter.closeProfileProxy(BluetoothProfile.HEADSET, it) }
+        a2dpProxy = null
+        headsetProxy = null
+    }
+
+    /**
+     * Whether A2DP or HFP to [bluetoothDevice] is connected (or connecting) on
+     * this phone, or null while the profile proxies aren't ready yet.
+     */
+    private fun isAudioConnected(bluetoothDevice: BluetoothDevice): Boolean? {
+        val a2dp = a2dpProxy ?: return null
+        val headset = headsetProxy ?: return null
+        fun BluetoothProfile.hasDevice(): Boolean = try {
+            getConnectionState(bluetoothDevice).let {
+                it == BluetoothProfile.STATE_CONNECTED || it == BluetoothProfile.STATE_CONNECTING
+            }
+        } catch (e: Exception) {
+            Log.w(TAG, "couldn't read profile state", e)
+            false
+        }
+        return a2dp.hasDevice() || headset.hasDevice()
+    }
+
+    private fun attachToDevicesWithAudio() {
+        val adapter = getSystemService(BluetoothManager::class.java).adapter ?: return
+        val aacpUuid = ParcelUuid.fromString("74ec2172-0bad-4d01-8f77-997b2be0722a")
+        adapter.bondedDevices
+            .filter { it.uuids?.contains(aacpUuid) == true && isAudioConnected(it) == true }
+            .forEach { onDeviceConnected(it) }
+    }
+
+    private fun onAudioProfileStateChanged(bluetoothDevice: BluetoothDevice, state: Int) {
+        val mac = MacAddress(bluetoothDevice.address)
+        when (state) {
+            BluetoothProfile.STATE_CONNECTED -> {
+                pendingAudioReleaseChecks.remove(mac)?.cancel()
+                if (devices.value[mac]?.connectionState?.value == ConnectionState.CONNECTED) return
+                if (bluetoothDevice.uuids == null) {
+                    bluetoothDevice.fetchUuidsWithSdp()
+                } else {
+                    onDeviceConnected(bluetoothDevice)
+                }
+            }
+
+            BluetoothProfile.STATE_DISCONNECTED -> {
+                val device = devices.value[mac] as? AppleDevice ?: return
+                pendingAudioReleaseChecks.remove(mac)?.cancel()
+                pendingAudioReleaseChecks[mac] = serviceCoroutineScope.launch {
+                    delay(AUDIO_RELEASE_GRACE_MS)
+                    pendingAudioReleaseChecks.remove(mac)
+                    if (device.connectionState.value != ConnectionState.CONNECTED) return@launch
+                    if (mac in audioReleasedByLibrePods) {
+                        Log.d(TAG, "Audio for ${mac.toRedactedString()} was released by LibrePods; keeping AACP for ear detection")
+                        return@launch
+                    }
+                    if (isAudioConnected(bluetoothDevice) != false) return@launch
+                    // The user (or another app) disconnected the device on this
+                    // phone. Close AACP too, or the link stays up and the AirPods
+                    // reconnect their audio here, taking it from the device that
+                    // is using them.
+                    Log.i(TAG, "Audio for ${mac.toRedactedString()} was disconnected outside LibrePods; closing AACP to release the link")
+                    device.disconnect()
+                    updateDeviceNotification(device = device)
                 }
             }
         }
@@ -471,6 +614,8 @@ class LibrePodsService: Service() {
             addAction("android.bluetooth.device.action.ACL_CONNECTED")
             addAction("android.bluetooth.device.action.ACL_DISCONNECTED")
             addAction("android.bluetooth.device.action.UUID")
+            addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)
+            addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
         }
 
         registerReceiver(bluetoothReceiver, intentFilter, RECEIVER_EXPORTED)
@@ -499,7 +644,13 @@ class LibrePodsService: Service() {
                     context = this,
                     bluetoothAdapter = bluetoothAdapter,
                     bluetoothDevice = bluetoothDevice,
-                    currentState = if (isConnectedMethod.invoke(bluetoothDevice) as Boolean) ConnectionState.AVAILABLE else ConnectionState.DISCONNECTED
+                    // AVAILABLE makes AppleDevice attach AACP right away, so
+                    // also require this phone to have the device's audio (see
+                    // onDeviceConnected).
+                    currentState = if (
+                        isConnectedMethod.invoke(bluetoothDevice) as Boolean &&
+                        isAudioConnected(bluetoothDevice) == true
+                    ) ConnectionState.AVAILABLE else ConnectionState.DISCONNECTED
                 )
             }
 
@@ -1313,6 +1464,7 @@ class LibrePodsService: Service() {
                     TAG,
                     "User put in at least one component, enabling audio for device ${device.macAddress.toRedactedString()}"
                 )
+                audioReleasedByLibrePods.remove(device.macAddress)
                 device.enableAudio()
                 device.connectA2dp()
                 justEnabledA2dp = true
@@ -1338,6 +1490,7 @@ class LibrePodsService: Service() {
                         TAG,
                         "Disconnecting audio for device ${device.macAddress.toRedactedString()} because user took out all components and disconnectWhenNotWearing is true"
                     )
+                    audioReleasedByLibrePods.add(device.macAddress)
                     device.disableAudio()
                     device.disconnectAudio()
                 }

oenderg avatar Nov 14 '26 22:11 oenderg