Fix call audio switch issue for BT LE to speaker and back to BT switch

Currenty when call audio is switched from BT LE headset to speaker,
first audio communication device is set as speaker and then BT audio
is disconnected. Hence onAudioLost() is not invoked when
clearLeAudioCommunicationDevice() is called. This causes
BluetoothRouteManager to wrongly assume that the BT LE headset
is in AudioConnected state. Hence when audio is switched back to BT,
BluetoothRouteManager doesn't try to connect BT audio and switch
fails. Fix this by making sure that onAudioLost() is always
invoked when clearLeAudioCommunicationDevice() is called.

Change-Id: Ic1568339979fcae055f7e41343ca244b25807e29
Bug: 241221189
diff --git a/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java b/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
index 58c74fc..fb637a9 100644
--- a/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
+++ b/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
@@ -186,6 +186,7 @@
     private boolean mLeAudioCallbackRegistered = false;
     private BluetoothLeAudio mBluetoothLeAudioService;
     private boolean mLeAudioSetAsCommunicationDevice = false;
+    private String mLeAudioDevice;
     private boolean mHearingAidSetAsCommunicationDevice = false;
     private BluetoothDevice mBluetoothHearingAidActiveDeviceCache;
     private BluetoothAdapter mBluetoothAdapter;
@@ -417,10 +418,17 @@
     }
 
     public void clearLeAudioCommunicationDevice() {
+        Log.i(this, "clearLeAudioCommunicationDevice: mLeAudioSetAsCommunicationDevice = " +
+                mLeAudioSetAsCommunicationDevice + " device = " + mLeAudioDevice);
         if (!mLeAudioSetAsCommunicationDevice) {
             return;
         }
         mLeAudioSetAsCommunicationDevice = false;
+        if (mLeAudioDevice != null) {
+            mBluetoothRouteManager.onAudioLost(mLeAudioDevice);
+            mLeAudioDevice = null;
+        }
+
         if (mAudioManager == null) {
             Log.i(this, "clearLeAudioCommunicationDevice: mAudioManager is null");
             return;
@@ -428,7 +436,6 @@
         if (mAudioManager.getCommunicationDevice() != null
                 && mAudioManager.getCommunicationDevice().getType()
                 == AudioDeviceInfo.TYPE_BLE_HEADSET) {
-            mBluetoothRouteManager.onAudioLost(mAudioManager.getCommunicationDevice().getAddress());
             mAudioManager.clearCommunicationDevice();
         }
     }
@@ -493,6 +500,7 @@
             Log.i(this, " bleHeadset device set");
             mBluetoothRouteManager.onAudioOn(bleHeadset.getAddress());
             mLeAudioSetAsCommunicationDevice = true;
+            mLeAudioDevice = bleHeadset.getAddress();
         }
         return result;
     }