[Audiosharing] Set earlist connected device active in sharing.

Flagged with enable_le_audio_sharing

Bug: 305620450
Test: Manual
Change-Id: I8e0132f3d982fe2723581cd2aafd3cb9a9ed409c
diff --git a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingDevicePreferenceController.java b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingDevicePreferenceController.java
index 1855667..7a2f26f 100644
--- a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingDevicePreferenceController.java
+++ b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingDevicePreferenceController.java
@@ -160,6 +160,7 @@
                                     + ", reason = "
                                     + reason);
                     mBluetoothDeviceUpdater.forceUpdate();
+                    AudioSharingUtils.updateActiveDeviceIfNeeded(mLocalBtManager);
                 }
 
                 @Override
@@ -204,6 +205,7 @@
                                     + ", reason = "
                                     + reason);
                     mBluetoothDeviceUpdater.forceUpdate();
+                    AudioSharingUtils.updateActiveDeviceIfNeeded(mLocalBtManager);
                 }
 
                 @Override
@@ -299,7 +301,7 @@
         mPreferenceGroup.setVisible(false);
         mAudioSharingSettingsPreference.setVisible(false);
 
-        if (isAvailable() && mBluetoothDeviceUpdater != null) {
+        if (isAvailable()) {
             mBluetoothDeviceUpdater.setPrefContext(screen.getContext());
             mBluetoothDeviceUpdater.forceUpdate();
         }
@@ -309,6 +311,7 @@
     public int getAvailabilityStatus() {
         return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)
                         && Flags.enableLeAudioSharing()
+                        && mBluetoothDeviceUpdater != null
                 ? AVAILABLE_UNSEARCHABLE
                 : UNSUPPORTED_ON_DEVICE;
     }
diff --git a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingSwitchBarController.java b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingSwitchBarController.java
index 58ff322..be02519 100644
--- a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingSwitchBarController.java
+++ b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingSwitchBarController.java
@@ -192,6 +192,7 @@
                                     + sourceId
                                     + ", reason = "
                                     + reason);
+                    AudioSharingUtils.updateActiveDeviceIfNeeded(mBtManager);
                 }
 
                 @Override
diff --git a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingUtils.java b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingUtils.java
index 53e095b..9210074 100644
--- a/src/com/android/settings/connecteddevice/audiosharing/AudioSharingUtils.java
+++ b/src/com/android/settings/connecteddevice/audiosharing/AudioSharingUtils.java
@@ -16,6 +16,7 @@
 
 package com.android.settings.connecteddevice.audiosharing;
 
+import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothCsipSetCoordinator;
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothLeBroadcastReceiveState;
@@ -89,11 +90,11 @@
      * @return A list of ordered connected devices eligible for the audio sharing. The active device
      *     is placed in the first place if it exists.
      */
-    public static ArrayList<CachedBluetoothDevice> buildOrderedConnectedLeadDevices(
+    public static List<CachedBluetoothDevice> buildOrderedConnectedLeadDevices(
             LocalBluetoothManager localBtManager,
             Map<Integer, List<CachedBluetoothDevice>> groupedConnectedDevices,
             boolean filterByInSharing) {
-        ArrayList<CachedBluetoothDevice> orderedDevices = new ArrayList<>();
+        List<CachedBluetoothDevice> orderedDevices = new ArrayList<>();
         LocalBluetoothLeBroadcastAssistant assistant =
                 localBtManager.getProfileManager().getLeAudioBroadcastAssistantProfile();
         if (assistant == null) return orderedDevices;
@@ -234,4 +235,32 @@
         ThreadUtils.postOnMainThread(
                 () -> Toast.makeText(context, message, Toast.LENGTH_LONG).show());
     }
+
+    /** Automatically update active device if needed. */
+    public static void updateActiveDeviceIfNeeded(LocalBluetoothManager localBtManager) {
+        if (localBtManager == null) return;
+        Map<Integer, List<CachedBluetoothDevice>> groupedConnectedDevices =
+                fetchConnectedDevicesByGroupId(localBtManager);
+        List<CachedBluetoothDevice> devicesInSharing =
+                buildOrderedConnectedLeadDevices(
+                        localBtManager, groupedConnectedDevices, /* filterByInSharing= */ true);
+        if (devicesInSharing.isEmpty()) return;
+        List<BluetoothDevice> devices =
+                BluetoothAdapter.getDefaultAdapter().getMostRecentlyConnectedDevices();
+        CachedBluetoothDevice targetDevice = null;
+        int targetDeviceIdx = -1;
+        for (CachedBluetoothDevice device : devicesInSharing) {
+            if (devices.contains(device.getDevice())) {
+                int idx = devices.indexOf(device.getDevice());
+                if (idx > targetDeviceIdx) {
+                    targetDeviceIdx = idx;
+                    targetDevice = device;
+                }
+            }
+        }
+        if (targetDevice != null && !isActiveLeAudioDevice(targetDevice)) {
+            Log.d(TAG, "Set active device: " + targetDevice.getDevice().getAnonymizedAddress());
+            targetDevice.setActive();
+        }
+    }
 }