Improve BT ICS binding/unbinding timing.

Separately bind and unbind bluetooth InCallService to improve call audio
via bluetooth devices.

Bug: b/306395598
Test: CallsManagerTest, InCallControllerTest
Change-Id: I68ee98eed46fccbb8b8d4674a0d8d44bc8dd1122
diff --git a/flags/telecom_incallservice_flags.aconfig b/flags/telecom_incallservice_flags.aconfig
index e1a652b..1110ca4 100644
--- a/flags/telecom_incallservice_flags.aconfig
+++ b/flags/telecom_incallservice_flags.aconfig
@@ -12,4 +12,11 @@
   namespace: "telecom"
   description: "Ensure that users are able to return to call from keyguard UI for ECC"
   bug: "306582821"
-}
\ No newline at end of file
+}
+
+flag {
+  name: "separately_bind_to_bt_incall_service"
+  namespace: "telecom"
+  description: "Binding/Unbinding to BluetoothInCallServices in proper time to improve call audio"
+  bug: "306395598"
+}
diff --git a/res/values/config.xml b/res/values/config.xml
index c38a6ec..bf30720 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -79,4 +79,7 @@
     <!-- When true, the options in the call blocking settings to block unavailable and unknown
      callers are combined into a single toggle. -->
     <bool name="combine_options_to_block_unavailable_and_unknown_callers">true</bool>
+
+    <!-- System bluetooth stack package name -->
+    <string name="system_bluetooth_stack">com.android.bluetooth</string>
 </resources>
diff --git a/src/com/android/server/telecom/Call.java b/src/com/android/server/telecom/Call.java
index 341d77e..624399b 100644
--- a/src/com/android/server/telecom/Call.java
+++ b/src/com/android/server/telecom/Call.java
@@ -27,13 +27,11 @@
 import android.graphics.Bitmap;
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
-import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.OutcomeReceiver;
 import android.os.ParcelFileDescriptor;
-import android.os.Parcelable;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.Trace;
@@ -73,7 +71,6 @@
 import com.android.internal.telecom.IVideoProvider;
 import com.android.internal.util.Preconditions;
 import com.android.server.telecom.flags.FeatureFlags;
-import com.android.server.telecom.flags.Flags;
 import com.android.server.telecom.stats.CallFailureCause;
 import com.android.server.telecom.stats.CallStateChangedAtomWriter;
 import com.android.server.telecom.ui.ToastFactory;
@@ -95,6 +92,7 @@
 import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
@@ -796,6 +794,13 @@
      */
     private CompletableFuture<Boolean> mDisconnectFuture;
 
+    /**
+     * {@link CompletableFuture} used to delay audio routing change for a ringing call until the
+     * corresponding bluetooth {@link android.telecom.InCallService} is successfully bound or timed
+     * out.
+     */
+    private CompletableFuture<Boolean> mBtIcsFuture;
+
     private FeatureFlags mFlags;
 
     /**
@@ -4693,6 +4698,30 @@
     }
 
     /**
+     * Set the bluetooth {@link android.telecom.InCallService} binding completion or timeout future
+     * which is used to delay the audio routing change after the bluetooth stack get notified about
+     * the ringing calls.
+     * @param btIcsFuture the {@link CompletableFuture}
+     */
+    public void setBtIcsFuture(CompletableFuture<Boolean> btIcsFuture) {
+        mBtIcsFuture = btIcsFuture;
+    }
+
+    /**
+     * Wait for bluetooth {@link android.telecom.InCallService} binding completion or timeout. Used
+     * for audio routing operations for a ringing call.
+     */
+    public void waitForBtIcs() {
+        if (mBtIcsFuture != null) {
+            try {
+                mBtIcsFuture.get();
+            } catch (InterruptedException | ExecutionException e) {
+                // ignore
+            }
+        }
+    }
+
+    /**
      * @return {@code true} if the connection has been created by the underlying
      * {@link ConnectionService}, {@code false} otherwise.
      */
diff --git a/src/com/android/server/telecom/CallAudioManager.java b/src/com/android/server/telecom/CallAudioManager.java
index 96bf2c6..e5678a0 100644
--- a/src/com/android/server/telecom/CallAudioManager.java
+++ b/src/com/android/server/telecom/CallAudioManager.java
@@ -750,6 +750,10 @@
 
     private void onCallEnteringRinging() {
         if (mRingingCalls.size() == 1) {
+            // Wait until the BT ICS binding completed to request further audio route change
+            for (Call ringingCall: mRingingCalls) {
+                ringingCall.waitForBtIcs();
+            }
             mCallAudioModeStateMachine.sendMessageWithArgs(
                     CallAudioModeStateMachine.NEW_RINGING_CALL,
                     makeArgsForModeStateMachine());
diff --git a/src/com/android/server/telecom/CallsManager.java b/src/com/android/server/telecom/CallsManager.java
index a3b423a..79e47f8 100644
--- a/src/com/android/server/telecom/CallsManager.java
+++ b/src/com/android/server/telecom/CallsManager.java
@@ -164,6 +164,7 @@
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Executor;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
@@ -962,8 +963,10 @@
 
         if (incomingCall.getState() != CallState.DISCONNECTED &&
                 incomingCall.getState() != CallState.DISCONNECTING) {
-            setCallState(incomingCall, CallState.RINGING,
-                    result.shouldAllowCall ? "successful incoming call" : "blocking call");
+            if (!mFeatureFlags.separatelyBindToBtIncallService()) {
+                setCallState(incomingCall, CallState.RINGING,
+                        result.shouldAllowCall ? "successful incoming call" : "blocking call");
+            }
         } else {
             Log.i(this, "onCallFilteringCompleted: call already disconnected.");
             return;
@@ -1008,6 +1011,10 @@
         }
 
         if (result.shouldAllowCall) {
+            if (mFeatureFlags.separatelyBindToBtIncallService()) {
+                incomingCall.setBtIcsFuture(mInCallController.bindToBTService(incomingCall));
+                setCallState(incomingCall, CallState.RINGING, "successful incoming call");
+            }
             incomingCall.setPostCallPackageName(
                     getRoleManagerAdapter().getDefaultCallScreeningApp(
                             incomingCall.getAssociatedUser()
@@ -1022,7 +1029,6 @@
                             "Exceeds maximum number of ringing calls.");
                     incomingCall.setMissedReason(AUTO_MISSED_MAXIMUM_RINGING);
                     autoMissCallAndLog(incomingCall, result);
-                    return;
                 }
             } else if (hasMaximumManagedDialingCalls(incomingCall)) {
                 if (shouldSilenceInsteadOfReject(incomingCall)) {
@@ -1032,7 +1038,6 @@
                             "dialing calls.");
                     incomingCall.setMissedReason(AUTO_MISSED_MAXIMUM_DIALING);
                     autoMissCallAndLog(incomingCall, result);
-                    return;
                 }
             } else if (result.shouldScreenViaAudio) {
                 Log.i(this, "onCallFilteringCompleted: starting background audio processing");
@@ -1051,6 +1056,9 @@
         } else {
             if (result.shouldReject) {
                 Log.i(this, "onCallFilteringCompleted: blocked call, rejecting.");
+                if (mFeatureFlags.separatelyBindToBtIncallService()) {
+                    setCallState(incomingCall, CallState.RINGING, "blocking call");
+                }
                 incomingCall.reject(false, null);
             }
             if (result.shouldAddToCallLog) {
diff --git a/src/com/android/server/telecom/DefaultDialerCache.java b/src/com/android/server/telecom/DefaultDialerCache.java
index dc79715..d819780 100644
--- a/src/com/android/server/telecom/DefaultDialerCache.java
+++ b/src/com/android/server/telecom/DefaultDialerCache.java
@@ -142,9 +142,9 @@
     private ComponentName mOverrideSystemDialerComponentName;
 
     public DefaultDialerCache(Context context,
-            DefaultDialerManagerAdapter defaultDialerManagerAdapter,
-            RoleManagerAdapter roleManagerAdapter,
-            TelecomSystem.SyncRoot lock) {
+                              DefaultDialerManagerAdapter defaultDialerManagerAdapter,
+                              RoleManagerAdapter roleManagerAdapter,
+                              TelecomSystem.SyncRoot lock) {
         mContext = context;
         mDefaultDialerManagerAdapter = defaultDialerManagerAdapter;
         mRoleManagerAdapter = roleManagerAdapter;
@@ -176,6 +176,10 @@
                         UserHandle.USER_ALL);
     }
 
+    public String getBTInCallServicePackage() {
+        return mRoleManagerAdapter.getBTInCallService();
+    }
+
     public String getDefaultDialerApplication(int userId) {
         if (userId == UserHandle.USER_CURRENT) {
             userId = ActivityManager.getCurrentUser();
diff --git a/src/com/android/server/telecom/InCallController.java b/src/com/android/server/telecom/InCallController.java
index 1946f71..55f48e3 100644
--- a/src/com/android/server/telecom/InCallController.java
+++ b/src/com/android/server/telecom/InCallController.java
@@ -22,7 +22,6 @@
 import android.Manifest;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.app.ActivityManager;
 import android.app.AppOpsManager;
 import android.app.KeyguardManager;
 import android.app.Notification;
@@ -60,6 +59,7 @@
 import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.ArraySet;
+import android.util.Pair;
 
 import com.android.internal.annotations.VisibleForTesting;
 // TODO: Needed for move to system service: import com.android.internal.R;
@@ -73,6 +73,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -329,8 +330,14 @@
                     addCall(call);
 
                     // Notify this new added call
-                    sendCallToService(call, mInCallServiceInfo,
-                            mInCallServices.get(userFromCall).get(mInCallServiceInfo));
+                    if (mFeatureFlags.separatelyBindToBtIncallService()
+                            && mInCallServiceInfo.getType() == IN_CALL_SERVICE_TYPE_BLUETOOTH) {
+                        sendCallToService(call, mInCallServiceInfo, mBTInCallServices
+                                .get(userFromCall).second);
+                    } else {
+                        sendCallToService(call, mInCallServiceInfo,
+                                mInCallServices.get(userFromCall).get(mInCallServiceInfo));
+                    }
                 }
                 return CONNECTION_SUCCEEDED;
             }
@@ -1178,6 +1185,7 @@
     private static final int IN_CALL_SERVICE_TYPE_CAR_MODE_UI = 3;
     private static final int IN_CALL_SERVICE_TYPE_NON_UI = 4;
     private static final int IN_CALL_SERVICE_TYPE_COMPANION = 5;
+    private static final int IN_CALL_SERVICE_TYPE_BLUETOOTH = 6;
 
     private static final int[] LIVE_CALL_STATES = { CallState.ACTIVE, CallState.PULLING,
             CallState.DISCONNECTING };
@@ -1185,8 +1193,13 @@
     /** The in-call app implementations, see {@link IInCallService}. */
     private final Map<UserHandle, Map<InCallServiceInfo, IInCallService>>
             mInCallServices = new ArrayMap<>();
+    private final Map<UserHandle, Pair<InCallServiceInfo, IInCallService>> mBTInCallServices =
+            new ArrayMap<>();
+    private final Map<UserHandle, Map<InCallServiceInfo, IInCallService>>
+            mCombinedInCallServiceMap = new ArrayMap<>();
 
     private final CallIdMapper mCallIdMapper = new CallIdMapper(Call::getId);
+    private final Collection<Call> mPendingEndToneCall = new ArraySet<>();
 
     private final Context mContext;
     private final AppOpsManager mAppOpsManager;
@@ -1202,8 +1215,11 @@
             mInCallServiceConnections = new ArrayMap<>();
     private final Map<UserHandle, NonUIInCallServiceConnectionCollection>
             mNonUIInCallServiceConnections = new ArrayMap<>();
+    private final Map<UserHandle, InCallServiceConnection> mBTInCallServiceConnections =
+            new ArrayMap<>();
     private final ClockProxy mClockProxy;
     private final IBinder mToken = new Binder();
+    private final FeatureFlags mFeatureFlags;
 
     // A set of known non-UI in call services on the device, including those that are disabled.
     // We track this so that we can efficiently bind to them when we're notified that a new
@@ -1214,6 +1230,12 @@
     // The future will complete with true if binding succeeds, false if it timed out.
     private CompletableFuture<Boolean> mBindingFuture = CompletableFuture.completedFuture(true);
 
+    // Future that's in a completed state unless we're in the middle of a binding to a bluetooth
+    // in-call service.
+    // The future will complete with true if bluetooth in-call service succeeds, false if it timed
+    // out.
+    private CompletableFuture<Boolean> mBtBindingFuture = CompletableFuture.completedFuture(true);
+
     private final CarModeTracker mCarModeTracker;
 
     /**
@@ -1242,7 +1264,6 @@
 
     private ArraySet<String> mAllCarrierPrivilegedApps = new ArraySet<>();
     private ArraySet<String> mActiveCarrierPrivilegedApps = new ArraySet<>();
-    private FeatureFlags mFeatureFlags;
 
     public InCallController(Context context, TelecomSystem.SyncRoot lock, CallsManager callsManager,
             SystemStateHelper systemStateHelper, DefaultDialerCache defaultDialerCache,
@@ -1360,65 +1381,89 @@
         // Track the call if we don't already know about it.
         addCall(call);
 
-        if (!isBoundAndConnectedToServices(userFromCall)) {
-            Log.i(this, "onCallAdded: %s; not bound or connected.", call);
-            // We are not bound, or we're not connected.
-            bindToServices(call);
+        if (mFeatureFlags.separatelyBindToBtIncallService()) {
+            boolean bindBTService = false;
+            boolean bindOtherServices = false;
+            if (!isBoundAndConnectedToBTService(userFromCall)) {
+                Log.i(this, "onCallAdded: %s; not bound or connected to BT ICS.", call);
+                bindBTService = true;
+                bindToBTService(call);
+            }
+            if (!isBoundAndConnectedToServices(userFromCall)) {
+                Log.i(this, "onCallAdded: %s; not bound or connected to other ICS.", call);
+                // We are not bound, or we're not connected.
+                bindOtherServices = true;
+                bindToOtherServices(call);
+            }
+            if (!bindBTService || !bindOtherServices) {
+                addCallToConnectedServices(call, userFromCall);
+            }
         } else {
-            InCallServiceConnection inCallServiceConnection =
-                    mInCallServiceConnections.get(userFromCall);
-
-            // We are bound, and we are connected.
-            adjustServiceBindingsForEmergency(userFromCall);
-
-            // This is in case an emergency call is added while there is an existing call.
-            mEmergencyCallHelper.maybeGrantTemporaryLocationPermission(call,
-                    userFromCall);
-
-            if (inCallServiceConnection != null) {
-                Log.i(this, "mInCallServiceConnection isConnected=%b",
-                        inCallServiceConnection.isConnected());
+            if (!isBoundAndConnectedToServices(userFromCall)) {
+                Log.i(this, "onCallAdded: %s; not bound or connected.", call);
+                // We are not bound, or we're not connected.
+                bindToServices(call, false);
+            } else {
+                addCallToConnectedServices(call, userFromCall);
             }
+        }
+    }
 
-            List<ComponentName> componentsUpdated = new ArrayList<>();
-            if (mInCallServices.containsKey(userFromCall)) {
-                for (Map.Entry<InCallServiceInfo, IInCallService> entry : mInCallServices.
-                        get(userFromCall).entrySet()) {
-                    InCallServiceInfo info = entry.getKey();
+    private void addCallToConnectedServices(Call call, UserHandle userFromCall) {
+        InCallServiceConnection inCallServiceConnection =
+                mInCallServiceConnections.get(userFromCall);
 
-                    if (call.isExternalCall() && !info.isExternalCallsSupported()) {
-                        continue;
-                    }
+        // We are bound, and we are connected.
+        adjustServiceBindingsForEmergency(userFromCall);
 
-                    if (call.isSelfManaged() && (!call.visibleToInCallService()
-                            || !info.isSelfManagedCallsSupported())) {
-                        continue;
-                    }
+        // This is in case an emergency call is added while there is an existing call.
+        mEmergencyCallHelper.maybeGrantTemporaryLocationPermission(call, userFromCall);
 
-                    // Only send the RTT call if it's a UI in-call service
-                    boolean includeRttCall = false;
-                    if (inCallServiceConnection != null) {
-                        includeRttCall = info.equals(inCallServiceConnection.getInfo());
-                    }
+        if (inCallServiceConnection != null) {
+            Log.i(this, "mInCallServiceConnection isConnected=%b",
+                    inCallServiceConnection.isConnected());
+        }
 
-                    componentsUpdated.add(info.getComponentName());
-                    IInCallService inCallService = entry.getValue();
+        List<ComponentName> componentsUpdated = new ArrayList<>();
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            for (Map.Entry<InCallServiceInfo, IInCallService> entry :
+                    serviceMap.get(userFromCall).entrySet()) {
+                InCallServiceInfo info = entry.getKey();
 
-                    ParcelableCall parcelableCall = ParcelableCallUtils.toParcelableCall(call,
-                            true /* includeVideoProvider */,
-                            mCallsManager.getPhoneAccountRegistrar(),
-                            info.isExternalCallsSupported(), includeRttCall,
-                            info.getType() == IN_CALL_SERVICE_TYPE_SYSTEM_UI ||
-                                    info.getType() == IN_CALL_SERVICE_TYPE_NON_UI);
-                    try {
-                        inCallService.addCall(
-                                sanitizeParcelableCallForService(info, parcelableCall));
-                        updateCallTracking(call, info, true /* isAdd */);
-                    } catch (RemoteException ignored) {
-                    }
+                if (call.isExternalCall() && !info.isExternalCallsSupported()) {
+                    continue;
                 }
-                Log.i(this, "Call added to components: %s", componentsUpdated);
+
+                if (call.isSelfManaged() && (!call.visibleToInCallService()
+                        || !info.isSelfManagedCallsSupported())) {
+                    continue;
+                }
+
+                // Only send the RTT call if it's a UI in-call service
+                boolean includeRttCall = false;
+                if (inCallServiceConnection != null) {
+                    includeRttCall = info.equals(inCallServiceConnection.getInfo());
+                }
+
+                componentsUpdated.add(info.getComponentName());
+                IInCallService inCallService = entry.getValue();
+
+                ParcelableCall parcelableCall = ParcelableCallUtils.toParcelableCall(call,
+                        true /* includeVideoProvider */,
+                        mCallsManager.getPhoneAccountRegistrar(),
+                        info.isExternalCallsSupported(), includeRttCall,
+                        info.getType() == IN_CALL_SERVICE_TYPE_SYSTEM_UI ||
+                                info.getType() == IN_CALL_SERVICE_TYPE_NON_UI);
+                try {
+                    inCallService.addCall(
+                            sanitizeParcelableCallForService(info, parcelableCall));
+                    updateCallTracking(call, info, true /* isAdd */);
+                } catch (RemoteException ignored) {
+                }
             }
+            Log.i(this, "Call added to ICS: %s", componentsUpdated);
         }
     }
 
@@ -1467,15 +1512,36 @@
     }
 
     @Override
+    public void onDisconnectedTonePlaying(Call call, boolean isTonePlaying) {
+        Log.i(this, "onDisconnectedTonePlaying: %s -> %b", call, isTonePlaying);
+
+        if (mFeatureFlags.separatelyBindToBtIncallService()) {
+            synchronized (mLock) {
+                mPendingEndToneCall.remove(call);
+                if (!mPendingEndToneCall.isEmpty()) {
+                    return;
+                }
+                UserHandle userHandle = getUserFromCall(call);
+                if (mBTInCallServiceConnections.containsKey(userHandle)) {
+                    mBTInCallServiceConnections.get(userHandle).disconnect();
+                    mBTInCallServiceConnections.remove(userHandle);
+                }
+            }
+        }
+    }
+
+    @Override
     public void onExternalCallChanged(Call call, boolean isExternalCall) {
         Log.i(this, "onExternalCallChanged: %s -> %b", call, isExternalCall);
 
         List<ComponentName> componentsUpdated = new ArrayList<>();
         UserHandle userFromCall = getUserFromCall(call);
-        if (!isExternalCall && mInCallServices.containsKey(userFromCall)) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!isExternalCall && serviceMap.containsKey(userFromCall)) {
             // The call was external but it is no longer external.  We must now add it to any
             // InCallServices which do not support external calls.
-            for (Map.Entry<InCallServiceInfo, IInCallService> entry : mInCallServices.
+            for (Map.Entry<InCallServiceInfo, IInCallService> entry : serviceMap.
                     get(userFromCall).entrySet()) {
                 InCallServiceInfo info = entry.getKey();
 
@@ -1514,9 +1580,9 @@
             // InCallServices which do not support external calls.
             // Remove the call by sending a call update indicating the call was disconnected.
             Log.i(this, "Removing external call %s", call);
-            if (mInCallServices.containsKey(userFromCall)) {
-                for (Map.Entry<InCallServiceInfo, IInCallService> entry : mInCallServices.
-                        get(userFromCall).entrySet()) {
+            if (serviceMap.containsKey(userFromCall)) {
+                for (Map.Entry<InCallServiceInfo, IInCallService> entry :
+                        serviceMap.get(userFromCall).entrySet()) {
                     InCallServiceInfo info = entry.getKey();
                     if (info.isExternalCallsSupported()) {
                         // For InCallServices which support external calls, we do not need to remove
@@ -1552,6 +1618,8 @@
 
     @Override
     public void onCallStateChanged(Call call, int oldState, int newState) {
+        Log.i(this, "onCallStateChanged: Call state changed for TC@%s: %s -> %s", call.getId(),
+                CallState.toString(oldState), CallState.toString(newState));
         maybeTrackMicrophoneUse(isMuted());
         updateCall(call);
     }
@@ -1567,11 +1635,13 @@
     @Override
     public void onCallAudioStateChanged(CallAudioState oldCallAudioState,
             CallAudioState newCallAudioState) {
-        if (!mInCallServices.isEmpty()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!serviceMap.isEmpty()) {
             Log.i(this, "Calling onAudioStateChanged, audioState: %s -> %s", oldCallAudioState,
                     newCallAudioState);
             maybeTrackMicrophoneUse(newCallAudioState.isMuted());
-            mInCallServices.values().forEach(inCallServices -> {
+            serviceMap.values().forEach(inCallServices -> {
                 for (IInCallService inCallService : inCallServices.values()) {
                     try {
                         inCallService.onCallAudioStateChanged(newCallAudioState);
@@ -1584,9 +1654,11 @@
 
     @Override
     public void onCallEndpointChanged(CallEndpoint callEndpoint) {
-        if (!mInCallServices.isEmpty()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!serviceMap.isEmpty()) {
             Log.i(this, "Calling onCallEndpointChanged");
-            mInCallServices.values().forEach(inCallServices -> {
+            serviceMap.values().forEach(inCallServices -> {
                 for (IInCallService inCallService : inCallServices.values()) {
                     try {
                         inCallService.onCallEndpointChanged(callEndpoint);
@@ -1600,10 +1672,12 @@
 
     @Override
     public void onAvailableCallEndpointsChanged(Set<CallEndpoint> availableCallEndpoints) {
-        if (!mInCallServices.isEmpty()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!serviceMap.isEmpty()) {
             Log.i(this, "Calling onAvailableCallEndpointsChanged");
             List<CallEndpoint> availableEndpoints = new ArrayList<>(availableCallEndpoints);
-            mInCallServices.values().forEach(inCallServices -> {
+            serviceMap.values().forEach(inCallServices -> {
                 for (IInCallService inCallService : inCallServices.values()) {
                     try {
                         inCallService.onAvailableCallEndpointsChanged(availableEndpoints);
@@ -1617,9 +1691,11 @@
 
     @Override
     public void onMuteStateChanged(boolean isMuted) {
-        if (!mInCallServices.isEmpty()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!serviceMap.isEmpty()) {
             Log.i(this, "Calling onMuteStateChanged");
-            mInCallServices.values().forEach(inCallServices -> {
+            serviceMap.values().forEach(inCallServices -> {
                 for (IInCallService inCallService : inCallServices.values()) {
                     try {
                         inCallService.onMuteStateChanged(isMuted);
@@ -1633,9 +1709,11 @@
 
     @Override
     public void onCanAddCallChanged(boolean canAddCall) {
-        if (!mInCallServices.isEmpty()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (!serviceMap.isEmpty()) {
             Log.i(this, "onCanAddCallChanged : %b", canAddCall);
-            mInCallServices.values().forEach(inCallServices -> {
+            serviceMap.values().forEach(inCallServices -> {
                 for (IInCallService inCallService : inCallServices.values()) {
                     try {
                         inCallService.onCanAddCallChanged(canAddCall);
@@ -1648,9 +1726,11 @@
 
     void onPostDialWait(Call call, String remaining) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
             Log.i(this, "Calling onPostDialWait, remaining = %s", remaining);
-            for (IInCallService inCallService : mInCallServices.get(userFromCall).values()) {
+            for (IInCallService inCallService: serviceMap.get(userFromCall).values()) {
                 try {
                     inCallService.setPostDialWait(mCallIdMapper.getCallId(call), remaining);
                 } catch (RemoteException ignored) {
@@ -1731,12 +1811,14 @@
         boolean isLockscreenRestricted = keyguardManager != null
                 && keyguardManager.isKeyguardLocked();
         UserHandle currentUser = mCallsManager.getCurrentUserHandle();
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
         // Handle cases when calls are placed from the keyguard UI screen, which operates under
         // the admin user. This needs to account for emergency calls placed from secondary/guest
         // users as well as the work profile. Once the screen is locked, the user should be able to
         // return to the call (from the keyguard UI).
         if (mFeatureFlags.eccKeyguard() && mCallsManager.isInEmergencyCall()
-                && isLockscreenRestricted && !mInCallServices.containsKey(callingUser)) {
+                && isLockscreenRestricted && !serviceMap.containsKey(callingUser)) {
             // If screen is locked and the current user is the system, query calls for the work
             // profile user, if available. Otherwise, the user is in the secondary/guest profile,
             // so we can default to the system user.
@@ -1750,8 +1832,8 @@
                 callingUser = currentUser;
             }
         }
-        if (mInCallServices.containsKey(callingUser)) {
-            for (IInCallService inCallService : mInCallServices.get(callingUser).values()) {
+        if (serviceMap.containsKey(callingUser)) {
+            for (IInCallService inCallService : serviceMap.get(callingUser).values()) {
                 try {
                     inCallService.bringToForeground(showDialpad);
                 } catch (RemoteException ignored) {
@@ -1764,7 +1846,7 @@
 
     @VisibleForTesting
     public Map<UserHandle, Map<InCallServiceInfo, IInCallService>> getInCallServices() {
-        return mInCallServices;
+        return getCombinedInCallServiceMap();
     }
 
     @VisibleForTesting
@@ -1773,9 +1855,11 @@
     }
 
     void silenceRinger(Set<UserHandle> userHandles) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
         userHandles.forEach(userHandle -> {
-            if (mInCallServices.containsKey(userHandle)) {
-                for (IInCallService inCallService : mInCallServices.get(userHandle).values()) {
+            if (serviceMap.containsKey(userHandle)) {
+                for (IInCallService inCallService : serviceMap.get(userHandle).values()) {
                     try {
                         inCallService.silenceRinger();
                     } catch (RemoteException ignored) {
@@ -1787,8 +1871,10 @@
 
     private void notifyConnectionEvent(Call call, String event, Bundle extras) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
-            for (IInCallService inCallService : mInCallServices.get(userFromCall).values()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            for (IInCallService inCallService : serviceMap.get(userFromCall).values()) {
                 try {
                     Log.i(this, "notifyConnectionEvent {Call: %s, Event: %s, Extras:[%s]}",
                             (call != null ? call.toString() : "null"),
@@ -1803,8 +1889,10 @@
 
     private void notifyRttInitiationFailure(Call call, int reason) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
-            mInCallServices.get(userFromCall).entrySet().stream()
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            serviceMap.get(userFromCall).entrySet().stream()
                     .filter((entry) -> entry.getKey().equals(mInCallServiceConnections.
                             get(userFromCall).getInfo()))
                     .forEach((entry) -> {
@@ -1821,8 +1909,10 @@
 
     private void notifyRemoteRttRequest(Call call, int requestId) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
-            mInCallServices.get(userFromCall).entrySet().stream()
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            serviceMap.get(userFromCall).entrySet().stream()
                     .filter((entry) -> entry.getKey().equals(mInCallServiceConnections.
                             get(userFromCall).getInfo()))
                     .forEach((entry) -> {
@@ -1839,8 +1929,10 @@
 
     private void notifyHandoverFailed(Call call, int error) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
-            for (IInCallService inCallService : mInCallServices.get(userFromCall).values()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            for (IInCallService inCallService : serviceMap.get(userFromCall).values()) {
                 try {
                     inCallService.onHandoverFailed(mCallIdMapper.getCallId(call), error);
                 } catch (RemoteException ignored) {
@@ -1851,8 +1943,10 @@
 
     private void notifyHandoverComplete(Call call) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
-            for (IInCallService inCallService : mInCallServices.get(userFromCall).values()) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
+            for (IInCallService inCallService : serviceMap.get(userFromCall).values()) {
                 try {
                     inCallService.onHandoverComplete(mCallIdMapper.getCallId(call));
                 } catch (RemoteException ignored) {
@@ -1880,18 +1974,60 @@
             mNonUIInCallServiceConnections.get(userHandle).disconnect();
             mNonUIInCallServiceConnections.remove(userHandle);
         }
-        mInCallServices.remove(userHandle);
+        getCombinedInCallServiceMap().remove(userHandle);
+        if (mFeatureFlags.separatelyBindToBtIncallService()) {
+            updateCombinedInCallServiceMap(userHandle);
+        }
+    }
+
+    /**
+     * Binds to Bluetooth InCallServices. Method-invoker must check
+     * {@link #isBoundAndConnectedToBTService(UserHandle)} before invoking.
+     *
+     * @param call The newly added call that triggered the binding to the in-call services.
+     */
+    public CompletableFuture<Boolean> bindToBTService(Call call) {
+        // Track the call if we don't already know about it.
+        addCall(call);
+        UserHandle userFromCall = getUserFromCall(call);
+
+        List<InCallServiceInfo> infos = getInCallServiceComponents(userFromCall,
+                IN_CALL_SERVICE_TYPE_BLUETOOTH);
+        if (infos.size() == 0 || infos.get(0) == null) {
+            Log.w(this, "No available BT service");
+            mBtBindingFuture = CompletableFuture.completedFuture(false);
+            return mBtBindingFuture;
+        }
+        mBtBindingFuture = new CompletableFuture<Boolean>().completeOnTimeout(false,
+                mTimeoutsAdapter.getCallBindBluetoothInCallServicesDelay(
+                        mContext.getContentResolver()), TimeUnit.MILLISECONDS);
+        new InCallServiceBindingConnection(infos.get(0)).connect(call);
+        return mBtBindingFuture;
     }
 
     /**
      * Binds to all the UI-providing InCallService as well as system-implemented non-UI
-     * InCallServices. Method-invoker must check {@link #isBoundAndConnectedToServices()}
-     * before invoking.
+     * InCallServices except BT InCallServices. Method-invoker must check
+     * {@link #isBoundAndConnectedToServices(UserHandle)} before invoking.
      *
      * @param call The newly added call that triggered the binding to the in-call services.
      */
+    public void bindToOtherServices(Call call) {
+        bindToServices(call, true);
+    }
+
+    /**
+     * Binds to all the UI-providing InCallService as well as system-implemented non-UI
+     * InCallServices. Method-invoker must check {@link #isBoundAndConnectedToServices(UserHandle)}
+     * before invoking.
+     *
+     * @param call           The newly added call that triggered the binding to the in-call
+     *                      services.
+     * @param skipBTServices Boolean variable to specify if the binding to BT InCallService should
+     *                      be skipped
+     */
     @VisibleForTesting
-    public void bindToServices(Call call) {
+    public void bindToServices(Call call, boolean skipBTServices) {
         UserHandle userFromCall = getUserFromCall(call);
         UserManager um = mContext.getSystemService(UserManager.class);
         UserHandle parentUser = mTelephonyFeatureFlags.workProfileApiSplit()
@@ -1956,7 +2092,7 @@
             // Only connect to the non-ui InCallServices if we actually connected to the main UI
             // one, or if the call is self-managed (in which case we'd still want to keep Wear, BT,
             // etc. informed.
-            connectToNonUiInCallServices(call);
+            connectToNonUiInCallServices(call, skipBTServices);
             mBindingFuture = new CompletableFuture<Boolean>().completeOnTimeout(false,
                     mTimeoutsAdapter.getCallRemoveUnbindInCallServicesDelay(
                             mContext.getContentResolver()),
@@ -1971,7 +2107,7 @@
                 packageChangedFilter, null, null);
     }
 
-    private void updateNonUiInCallServices(Call call) {
+    private void updateNonUiInCallServices(Call call, boolean skipBTService) {
         UserHandle userFromCall = getUserFromCall(call);
 
         UserManager um = mContext.getSystemService(UserManager.class);
@@ -2026,10 +2162,10 @@
                 nonUIInCalls));
     }
 
-    private void connectToNonUiInCallServices(Call call) {
+    private void connectToNonUiInCallServices(Call call, boolean skipBTService) {
         UserHandle userFromCall = getUserFromCall(call);
         if (!mNonUIInCallServiceConnections.containsKey(userFromCall)) {
-            updateNonUiInCallServices(call);
+            updateNonUiInCallServices(call, skipBTService);
         }
         mNonUIInCallServiceConnections.get(userFromCall).connect(call);
     }
@@ -2298,6 +2434,12 @@
             return IN_CALL_SERVICE_TYPE_DEFAULT_DIALER_UI;
         }
 
+        String bluetoothPackage = mDefaultDialerCache.getBTInCallServicePackage();
+        if (serviceInfo.packageName != null && serviceInfo.packageName.equals(bluetoothPackage)
+                && (hasControlInCallPermission || hasAppOpsPermittedManageOngoingCalls)) {
+            return IN_CALL_SERVICE_TYPE_BLUETOOTH;
+        }
+
         // Also allow any in-call service that has the control-experience permission (to ensure
         // that it is a system app) and doesn't claim to show any UI.
         if (!isUIService && !isCarModeUIService && (hasControlInCallPermission ||
@@ -2338,9 +2480,24 @@
             trackCallingUserInterfaceStarted(info);
         }
         IInCallService inCallService = IInCallService.Stub.asInterface(service);
-        mInCallServices.putIfAbsent(userHandle,
-                new ArrayMap<InCallController.InCallServiceInfo, IInCallService>());
-        mInCallServices.get(userHandle).put(info, inCallService);
+        if (mFeatureFlags.separatelyBindToBtIncallService()
+                && info.getType() == IN_CALL_SERVICE_TYPE_BLUETOOTH) {
+            if (mBtBindingFuture.isDone()) {
+                // Binding completed after the timeout. Clean up this binding
+                return false;
+            } else {
+                mBtBindingFuture.complete(true);
+            }
+            mBTInCallServices.put(userHandle, new Pair<>(info, inCallService));
+        } else {
+            mInCallServices.putIfAbsent(userHandle, new ArrayMap<>());
+            mInCallServices.get(userHandle).put(info, inCallService);
+        }
+
+        if (mFeatureFlags.separatelyBindToBtIncallService()) {
+            updateCombinedInCallServiceMap(userHandle);
+        }
+
         try {
             inCallService.setInCallAdapter(
                     new InCallAdapter(
@@ -2429,6 +2586,11 @@
         if (mInCallServices.containsKey(userHandle)) {
             mInCallServices.get(userHandle).remove(disconnectedInfo);
         }
+        if (mFeatureFlags.separatelyBindToBtIncallService()
+                && disconnectedInfo.getType() == IN_CALL_SERVICE_TYPE_BLUETOOTH) {
+            mBTInCallServices.remove(userHandle);
+            updateCombinedInCallServiceMap(userHandle);
+        }
     }
 
     /**
@@ -2449,17 +2611,19 @@
      * @param rttInfoChanged       {@code true} if any information about the RTT session changed,
      *                             {@code false} otherwise.
      * @param exceptPackageName    When specified, this package name will not get a call update.
-     *                             Used ONLY from {@link Call#putConnectionServiceExtras(int, Bundle, String)} to
+     *                             Used ONLY from {@link Call#putConnectionServiceExtras(Bundle)} to
      *                             ensure we can propagate extras changes between InCallServices but
      *                             not inform the requestor of their own change.
      */
     private void updateCall(Call call, boolean videoProviderChanged, boolean rttInfoChanged,
             String exceptPackageName) {
         UserHandle userFromCall = getUserFromCall(call);
-        if (mInCallServices.containsKey(userFromCall)) {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        if (serviceMap.containsKey(userFromCall)) {
             Log.i(this, "Sending updateCall %s", call);
             List<ComponentName> componentsUpdated = new ArrayList<>();
-            for (Map.Entry<InCallServiceInfo, IInCallService> entry : mInCallServices.
+            for (Map.Entry<InCallServiceInfo, IInCallService> entry : serviceMap.
                     get(userFromCall).entrySet()) {
                 InCallServiceInfo info = entry.getKey();
                 ComponentName componentName = info.getComponentName();
@@ -2527,6 +2691,9 @@
         }
 
         maybeTrackMicrophoneUse(isMuted());
+        if (mFeatureFlags.separatelyBindToBtIncallService()) {
+            mPendingEndToneCall.add(call);
+        }
     }
 
     /**
@@ -2539,6 +2706,14 @@
         return mInCallServiceConnections.get(userHandle).isConnected();
     }
 
+    @VisibleForTesting
+    public boolean isBoundAndConnectedToBTService(UserHandle userHandle) {
+        if (!mBTInCallServiceConnections.containsKey(userHandle)) {
+            return false;
+        }
+        return mBTInCallServiceConnections.get(userHandle).isConnected();
+    }
+
     /**
      * @return A future that is pending whenever we are in the middle of binding to an
      *         incall service.
@@ -2553,9 +2728,11 @@
      * @param pw The {@code IndentingPrintWriter} to write the state to.
      */
     public void dump(IndentingPrintWriter pw) {
-        pw.println("mInCallServices (InCalls registered):");
+        pw.println("combinedInCallServiceMap (InCalls registered):");
         pw.increaseIndent();
-        mInCallServices.values().forEach(inCallServices -> {
+        Map<UserHandle, Map<InCallController.InCallServiceInfo, IInCallService>> serviceMap =
+                getCombinedInCallServiceMap();
+        serviceMap.values().forEach(inCallServices -> {
             for (InCallServiceInfo info : inCallServices.keySet()) {
                 pw.println(info);
             }
@@ -2980,4 +3157,36 @@
         }
         return false;
     }
+
+    private void updateCombinedInCallServiceMap(UserHandle user) {
+        synchronized (mLock) {
+            Map<InCallServiceInfo, IInCallService> serviceMap;
+            if (mInCallServices.containsKey(user)) {
+                serviceMap = mInCallServices.get(user);
+            } else {
+                serviceMap = new HashMap<>();
+            }
+            if (mFeatureFlags.separatelyBindToBtIncallService()
+                    && mBTInCallServices.containsKey(user)) {
+                Pair<InCallServiceInfo, IInCallService> btServicePair = mBTInCallServices.get(user);
+                serviceMap.put(btServicePair.first, btServicePair.second);
+            }
+            if (!serviceMap.isEmpty()) {
+                mCombinedInCallServiceMap.put(user, serviceMap);
+            } else {
+                mCombinedInCallServiceMap.remove(user);
+            }
+        }
+    }
+
+    private Map<UserHandle,
+            Map<InCallController.InCallServiceInfo, IInCallService>> getCombinedInCallServiceMap() {
+        synchronized (mLock) {
+            if (mFeatureFlags.separatelyBindToBtIncallService()) {
+                return mCombinedInCallServiceMap;
+            } else {
+                return mInCallServices;
+            }
+        }
+    }
 }
diff --git a/src/com/android/server/telecom/RoleManagerAdapter.java b/src/com/android/server/telecom/RoleManagerAdapter.java
index 8fdfb11..9f515e6 100644
--- a/src/com/android/server/telecom/RoleManagerAdapter.java
+++ b/src/com/android/server/telecom/RoleManagerAdapter.java
@@ -54,7 +54,7 @@
     /**
      * Returns the package name of the app which fills the {@link android.app.role.RoleManager} call
      * screening role.
-     * @return the package name of the app filling the role, {@code null} otherwise}.
+     * @return the package name of the app filling the role, {@code null} otherwise.
      */
     String getDefaultCallScreeningApp(UserHandle userHandle);
 
@@ -67,9 +67,25 @@
     void setTestDefaultCallScreeningApp(String packageName);
 
     /**
+     * Returns the package name of the package which fills the {@link android.app.role.RoleManager}
+     * bt in-call service role.
+     * @return the package name of the package filling the role, {@code null} otherwise.
+     */
+    String getBTInCallService();
+
+    /**
+     * Override the {@link android.app.role.RoleManager} bt in-call service package with another
+     * value.
+     * Used for testing purposes only.
+     * @param packageName Package name of the package to fill the bt in-call service role. Where
+     *                    {@code null}, the override is removed.
+     */
+    void setTestBTInCallService(String packageName);
+
+    /**
      * Returns the package name of the app which fills the {@link android.app.role.RoleManager}
      * {@link android.app.role.RoleManager#ROLE_DIALER} role.
-     * @return the package name of the app filling the role, {@code null} otherwise}.
+     * @return the package name of the app filling the role, {@code null} otherwise.
      */
     String getDefaultDialerApp(int user);
 
diff --git a/src/com/android/server/telecom/RoleManagerAdapterImpl.java b/src/com/android/server/telecom/RoleManagerAdapterImpl.java
index ac35b3d..33ec466 100644
--- a/src/com/android/server/telecom/RoleManagerAdapterImpl.java
+++ b/src/com/android/server/telecom/RoleManagerAdapterImpl.java
@@ -41,6 +41,7 @@
     private String mOverrideDefaultCallScreeningApp = null;
     private String mOverrideDefaultDialerApp = null;
     private List<String> mOverrideCallCompanionApps = new ArrayList<>();
+    private String mOverrideBTInCallService = null;
     private Context mContext;
     private RoleManager mRoleManager;
     private UserHandle mCurrentUserHandle;
@@ -77,6 +78,20 @@
     }
 
     @Override
+    public String getBTInCallService() {
+        if (mOverrideBTInCallService != null) {
+            return mOverrideBTInCallService;
+        }
+        return getBluetoothInCallServicePackageName();
+    }
+
+    @Override
+    public void setTestBTInCallService(String packageName) {
+        mOverrideBTInCallService = packageName;
+    }
+
+
+    @Override
     public String getDefaultDialerApp(int user) {
         if (mOverrideDefaultDialerApp != null) {
             return mOverrideDefaultDialerApp;
@@ -151,6 +166,10 @@
         return roleHolders.get(0);
     }
 
+    private String getBluetoothInCallServicePackageName() {
+        return mContext.getResources().getString(R.string.system_bluetooth_stack);
+    }
+
     /**
      * Returns the application label that corresponds to the given package name
      *
diff --git a/src/com/android/server/telecom/TelecomServiceImpl.java b/src/com/android/server/telecom/TelecomServiceImpl.java
index b954588..6006687 100644
--- a/src/com/android/server/telecom/TelecomServiceImpl.java
+++ b/src/com/android/server/telecom/TelecomServiceImpl.java
@@ -1599,7 +1599,7 @@
                                         && accountExtra != null && accountExtra.getBoolean(
                                         PhoneAccount.EXTRA_SKIP_CALL_FILTERING,
                                         false)) {
-                                    mCallsManager.getInCallController().bindToServices(null);
+                                    mCallsManager.getInCallController().bindToServices(null, false);
                                 }
                             }
                         } finally {
diff --git a/src/com/android/server/telecom/Timeouts.java b/src/com/android/server/telecom/Timeouts.java
index c5fdd4c..abc7ff6 100644
--- a/src/com/android/server/telecom/Timeouts.java
+++ b/src/com/android/server/telecom/Timeouts.java
@@ -41,6 +41,10 @@
             return Timeouts.getCallScreeningTimeoutMillis(cr);
         }
 
+        public long getCallBindBluetoothInCallServicesDelay(ContentResolver cr) {
+            return Timeouts.getCallBindBluetoothInCallServicesDelay(cr);
+        }
+
         public long getCallRemoveUnbindInCallServicesDelay(ContentResolver cr) {
             return Timeouts.getCallRemoveUnbindInCallServicesDelay(cr);
         }
@@ -270,6 +274,11 @@
                 60000L /* 1 minute */);
     }
 
+    public static long getCallBindBluetoothInCallServicesDelay(ContentResolver contentResolver) {
+        return get(contentResolver, "call_bind_bluetooth_in_call_services_delay",
+                2000L /* 2 seconds */);
+    }
+
     /**
      * Returns the amount of delay before unbinding the in-call services after all the calls
      * are removed.
diff --git a/tests/src/com/android/server/telecom/tests/CallsManagerTest.java b/tests/src/com/android/server/telecom/tests/CallsManagerTest.java
index be00125..f814d3e 100644
--- a/tests/src/com/android/server/telecom/tests/CallsManagerTest.java
+++ b/tests/src/com/android/server/telecom/tests/CallsManagerTest.java
@@ -36,6 +36,7 @@
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.reset;
@@ -102,6 +103,7 @@
 import com.android.server.telecom.ConnectionServiceFocusManager;
 import com.android.server.telecom.ConnectionServiceFocusManager.ConnectionServiceFocusManagerFactory;
 import com.android.server.telecom.ConnectionServiceWrapper;
+import com.android.server.telecom.CreateConnectionResponse;
 import com.android.server.telecom.DefaultDialerCache;
 import com.android.server.telecom.EmergencyCallDiagnosticLogger;
 import com.android.server.telecom.EmergencyCallHelper;
@@ -110,6 +112,7 @@
 import com.android.server.telecom.HeadsetMediaButtonFactory;
 import com.android.server.telecom.InCallController;
 import com.android.server.telecom.InCallControllerFactory;
+import com.android.server.telecom.DefaultDialerCache;
 import com.android.server.telecom.InCallTonePlayer;
 import com.android.server.telecom.InCallWakeLockController;
 import com.android.server.telecom.InCallWakeLockControllerFactory;
@@ -143,6 +146,8 @@
 import org.junit.runners.JUnit4;
 import org.mockito.ArgumentCaptor;
 import org.mockito.ArgumentMatchers;
+import org.mockito.InOrder;
+import org.mockito.Matchers;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
@@ -374,6 +379,7 @@
                 eq(WORK_HANDLE), any())).thenReturn(WORK_ACCOUNT);
         when(mToastFactory.makeText(any(), anyInt(), anyInt())).thenReturn(mToast);
         when(mToastFactory.makeText(any(), any(), anyInt())).thenReturn(mToast);
+        when(mFeatureFlags.separatelyBindToBtIncallService()).thenReturn(false);
     }
 
     @Override
@@ -3308,6 +3314,28 @@
         assertTrue(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));
     }
 
+    @SmallTest
+    @Test
+    public void testBindToBtServiceSeparately() {
+        when(mFeatureFlags.separatelyBindToBtIncallService()).thenReturn(true);
+        Call call = addSpyCall(CallState.NEW);
+        CallFilteringResult result = new CallFilteringResult.Builder()
+                .setShouldAllowCall(true)
+                .setShouldReject(false)
+                .build();
+        when(mInCallController.bindToBTService(eq(call))).thenReturn(
+                CompletableFuture.completedFuture(true));
+        when(mInCallController.isBoundAndConnectedToBTService(any(UserHandle.class)))
+                .thenReturn(false);
+
+        mCallsManager.onCallFilteringComplete(call, result, false);
+
+        InOrder inOrder = inOrder(mInCallController, call, mInCallController);
+
+        inOrder.verify(mInCallController).bindToBTService(eq(call));
+        inOrder.verify(call).setState(eq(CallState.RINGING), anyString());
+    }
+
 
     private Call addSpyCall() {
         return addSpyCall(SIM_2_HANDLE, CallState.ACTIVE);
diff --git a/tests/src/com/android/server/telecom/tests/InCallControllerTests.java b/tests/src/com/android/server/telecom/tests/InCallControllerTests.java
index bd0e97f..24b14de 100644
--- a/tests/src/com/android/server/telecom/tests/InCallControllerTests.java
+++ b/tests/src/com/android/server/telecom/tests/InCallControllerTests.java
@@ -19,7 +19,6 @@
 import static com.android.server.telecom.InCallController.IN_CALL_SERVICE_NOTIFICATION_ID;
 import static com.android.server.telecom.InCallController.NOTIFICATION_TAG;
 import static com.android.server.telecom.tests.TelecomSystemTest.TEST_TIMEOUT;
-
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -185,6 +184,9 @@
     private static final String APPOP_NONUI_PKG = "appop_nonui_pkg";
     private static final String APPOP_NONUI_CLASS = "appop_nonui_cls";
     private static final int APPOP_NONUI_UID = 7;
+    private static final String BT_PKG = "btpkg";
+    private static final String BT_CLS = "btcls";
+    private static final int BT_UID = 900974;
 
     private static final PhoneAccountHandle PA_HANDLE =
             new PhoneAccountHandle(new ComponentName("pa_pkg", "pa_cls"),
@@ -225,6 +227,7 @@
         when(mDefaultDialerCache.getSystemDialerApplication()).thenReturn(SYS_PKG);
         when(mDefaultDialerCache.getSystemDialerComponent()).thenReturn(
                 new ComponentName(SYS_PKG, SYS_CLASS));
+        when(mDefaultDialerCache.getBTInCallServicePackage()).thenReturn(BT_PKG);
         mEmergencyCallHelper = new EmergencyCallHelper(mMockContext, mDefaultDialerCache,
                 mTimeoutsAdapter);
         when(mMockCallsManager.getRoleManagerAdapter()).thenReturn(mMockRoleManagerAdapter);
@@ -271,6 +274,8 @@
                     return new String[] { NONUI_PKG };
                 case APPOP_NONUI_UID:
                     return new String[] { APPOP_NONUI_PKG };
+                case BT_UID:
+                    return new String[] { BT_PKG };
             }
             return null;
         }).when(mMockPackageManager).getPackagesForUid(anyInt());
@@ -313,6 +318,7 @@
         // Mock user info to allow binding on user stored in the phone account (mUserHandle).
         when(mMockUserManager.getUserInfo(anyInt())).thenReturn(mMockUserInfo);
         when(mMockUserInfo.isManagedProfile()).thenReturn(true);
+        when(mFeatureFlags.separatelyBindToBtIncallService()).thenReturn(false);
     }
 
     @Override
@@ -402,7 +408,7 @@
                 .thenReturn(300_000L);
 
         setupMockPackageManager(false /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext).bindServiceAsUser(
@@ -437,7 +443,7 @@
 
         Intent queryIntent = new Intent(InCallService.SERVICE_INTERFACE);
         setupMockPackageManager(false /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext).bindServiceAsUser(
@@ -476,7 +482,7 @@
                 anyInt(), eq(mUserHandle))).thenReturn(true);
 
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Query for the different InCallServices
         ArgumentCaptor<Intent> queryIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -538,7 +544,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Query for the different InCallServices
         ArgumentCaptor<Intent> queryIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -599,7 +605,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext, times(1)).bindServiceAsUser(
@@ -629,7 +635,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext, times(1)).bindServiceAsUser(
@@ -661,7 +667,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext, times(1)).bindServiceAsUser(
@@ -689,7 +695,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mMockContext, times(1)).bindServiceAsUser(
@@ -738,7 +744,7 @@
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
         setupMockPackageManagerLocationPermission(SYS_PKG, false /* granted */);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Query for the different InCallServices
         ArgumentCaptor<Intent> queryIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -820,7 +826,7 @@
                 .thenReturn(true);
 
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Query for the different InCallServices
         ArgumentCaptor<Intent> queryIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -901,7 +907,7 @@
         when(mDefaultDialerCache.getDefaultDialerApplication(CURRENT_USER_ID)).thenReturn(DEF_PKG);
 
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         ArgumentCaptor<ServiceConnection> serviceConnectionCaptor =
@@ -948,7 +954,7 @@
         mInCallController.handleCarModeChange(UiModeManager.DEFAULT_PRIORITY, CAR_PKG, true);
 
         // Now bind; we should only bind to one app.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1030,7 +1036,7 @@
                 .thenReturn(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
 
         mInCallController.addCall(mMockCall);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // There will be 4 calls for the various types of ICS.
         verify(mMockPackageManager, times(4)).queryIntentServicesAsUser(
@@ -1198,7 +1204,7 @@
     public void testBindToService_IncludeExternal() throws Exception {
         setupMocks(true /* isExternalCall */);
         setupMockPackageManager(true /* default */, true /* system */, true /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Query for the different InCallServices
         ArgumentCaptor<Intent> queryIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1249,7 +1255,7 @@
 
         when(mMockCallsManager.getCalls()).thenReturn(Collections.singletonList(mMockCall));
         setupMockPackageManager(true /* default */, true /* system */, false /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         ArgumentCaptor<ServiceConnection> serviceConnectionCaptor =
@@ -1298,7 +1304,7 @@
         mInCallController.handleCarModeChange(UiModeManager.DEFAULT_PRIORITY, CAR_PKG, true);
 
         // Now bind; we should only bind to one app.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1317,7 +1323,7 @@
     public void testNoBindToInvalidService_CarModeUI() throws Exception {
         setupMocks(true /* isExternalCall */);
         setupMockPackageManager(true /* default */, true /* system */, true /* external calls */);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         when(mMockPackageManager.checkPermission(
                 matches(Manifest.permission.CONTROL_INCALL_EXPERIENCE),
@@ -1369,7 +1375,7 @@
                             anyInt(), any(AttributionSource.class), nullable(String.class)));
 
             // Now bind; we should bind to the system dialer and app op non ui app.
-            mInCallController.bindToServices(mMockCall);
+            mInCallController.bindToServices(mMockCall, false);
 
             // Bind InCallServices
             ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1413,7 +1419,7 @@
         when(mDefaultDialerCache.getDefaultDialerApplication(CURRENT_USER_ID)).thenReturn(null);
 
         // we should bind to only the non ui app.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1446,7 +1452,7 @@
                 matches(DEF_PKG))).thenReturn(PackageManager.PERMISSION_DENIED);
         when(mMockCall.getName()).thenReturn("evil");
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1483,7 +1489,7 @@
         setupMocks(true /* isExternalCall */);
         setupMockPackageManager(true /* default */, true /* system */, true /* external calls */);
         // Bind to default dialer.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Uninstall an unrelated app.
         mSystemStateListener.onPackageUninstalled("com.joe.stuff");
@@ -1507,7 +1513,7 @@
         setupMocks(true /* isExternalCall */);
         setupMockPackageManager(true /* default */, true /* system */, true /* external calls */);
         // Bind to default dialer.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Enable car mode and enter car mode at default priority.
         when(mMockSystemStateHelper.isCarModeOrProjectionActive()).thenReturn(true);
@@ -1575,7 +1581,7 @@
         setupMockPackageManager(true /* default */, true /* nonui */, false /* appop_nonui */ ,
                 true /* system */, false /* external calls */,
                 false /* self mgd in default*/, false /* self mgd in car*/);
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
         ArgumentCaptor<ServiceConnection> serviceConnectionCaptor =
@@ -1644,7 +1650,7 @@
 
         // Bind; we should not bind to anything right now; the dialer does not support self
         // managed calls.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices; make sure no binding took place.  InCallController handles not
         // binding initially, but the rebind (see next test case) will always happen.
@@ -1683,7 +1689,7 @@
 
         // Bind; we should not bind to anything right now; the dialer does not support self
         // managed calls.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallServices; make sure no binding took place.
         verify(mMockContext, never()).bindServiceAsUser(
@@ -1785,7 +1791,7 @@
         assertFalse(mUserHandle.equals(UserHandle.USER_CURRENT));
         when(mMockUserInfo.isManagedProfile()).thenReturn(false);
 
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
 
         // Bind InCallService on UserHandle.CURRENT and not the user from the call (mUserHandle)
         ArgumentCaptor<Intent> bindIntentCaptor = ArgumentCaptor.forClass(Intent.class);
@@ -1806,7 +1812,7 @@
         when(mMockCall.getAssociatedUser()).thenReturn(testUser);
 
         // Bind to ICS. The mapping should've been inserted with the testUser as the key.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
         assertTrue(mInCallController.getInCallServiceConnections().containsKey(testUser));
 
         // Set the target phone account. Simulates the flow when the user has chosen which sim to
@@ -1834,7 +1840,7 @@
         when(mMockCall.isIncoming()).thenReturn(true);
 
         // Bind to ICS. The mapping should've been inserted with the testUser as the key.
-        mInCallController.bindToServices(mMockCall);
+        mInCallController.bindToServices(mMockCall, false);
         assertTrue(mInCallController.getInCallServiceConnections().containsKey(testUser));
 
         // Remove the call. This invokes getUserFromCall to remove the ICS mapping.
@@ -1950,8 +1956,7 @@
                 true /*includeSelfManagedCallsInNonUi*/);
 
         //pass in call by child/profile user
-        mInCallController.bindToServices(mMockChildUserCall);
-
+        mInCallController.bindToServices(mMockChildUserCall, false);
         // Verify that queryIntentServicesAsUser is also called with parent handle
         // Query for the different InCallServices
         ArgumentCaptor<Integer> userIdCaptor = ArgumentCaptor.forClass(Integer.class);
@@ -1969,6 +1974,32 @@
                 userIds.contains(mParentUserHandle.getIdentifier()));
     }
 
+    @Test
+    public void testSeparatelyBluetoothService() {
+        Intent expectedIntent = new Intent(InCallService.SERVICE_INTERFACE);
+        expectedIntent.setPackage(mDefaultDialerCache.getBTInCallServicePackage());
+        LinkedList<ResolveInfo> resolveInfo = new LinkedList<ResolveInfo>();
+        resolveInfo.add(getBluetoothResolveinfo());
+        when(mFeatureFlags.separatelyBindToBtIncallService()).thenReturn(true);
+        when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
+        doAnswer(invocation -> {
+            Object[] args = invocation.getArguments();
+            LinkedList<ResolveInfo> resolveInfo1 = new LinkedList<ResolveInfo>();
+            Intent intent = (Intent) args[0];
+            if (intent.getAction().equals(InCallService.SERVICE_INTERFACE)) {
+                resolveInfo1.add(getBluetoothResolveinfo());
+            }
+            return resolveInfo1;
+        }).when(mMockPackageManager).queryIntentServicesAsUser(any(Intent.class), anyInt(),
+                anyInt());
+
+        mInCallController.bindToBTService(mMockCall);
+
+        ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
+        verify(mMockContext).bindServiceAsUser(captor.capture(), any(ServiceConnection.class),
+                anyInt(), any(UserHandle.class));
+    }
+
     private void setupMocks(boolean isExternalCall) {
         setupMocks(isExternalCall, false /* isSelfManagedCall */);
     }
@@ -2093,6 +2124,18 @@
         }};
     }
 
+    private ResolveInfo getBluetoothResolveinfo() {
+        return new ResolveInfo() {{
+            serviceInfo = new ServiceInfo();
+            serviceInfo.packageName = BT_PKG;
+            serviceInfo.name = BT_CLS;
+            serviceInfo.applicationInfo = new ApplicationInfo();
+            serviceInfo.applicationInfo.uid = BT_UID;
+            serviceInfo.enabled = true;
+            serviceInfo.permission = Manifest.permission.BIND_INCALL_SERVICE;
+        }};
+    }
+
     private void setupMockPackageManager(final boolean useDefaultDialer,
             final boolean useSystemDialer, final boolean includeExternalCalls) {
         setupMockPackageManager(useDefaultDialer, false, false, useSystemDialer, includeExternalCalls,
diff --git a/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java b/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
index 24b23af..a36e8ea 100644
--- a/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
+++ b/tests/src/com/android/server/telecom/tests/TelecomServiceImplTest.java
@@ -1167,7 +1167,7 @@
 
         verify(mFakePhoneAccountRegistrar).getPhoneAccount(
                 TEL_PA_HANDLE_16, TEL_PA_HANDLE_16.getUserHandle());
-        verify(mInCallController, never()).bindToServices(any());
+        verify(mInCallController, never()).bindToServices(any(), anyBoolean());
         addCallTestHelper(TelecomManager.ACTION_INCOMING_CALL,
                 CallIntentProcessor.KEY_IS_INCOMING_CALL, extras,
                 TEL_PA_HANDLE_16, false);
@@ -1189,7 +1189,7 @@
 
         mTSIBinder.addNewIncomingCall(TEL_PA_HANDLE_16, extras, CALLING_PACKAGE);
 
-        verify(mInCallController, never()).bindToServices(null);
+        verify(mInCallController, never()).bindToServices(eq(null), anyBoolean());
     }
 
     @SmallTest
@@ -1207,7 +1207,7 @@
 
         mTSIBinder.addNewIncomingCall(TEL_PA_HANDLE_16, extras, CALLING_PACKAGE);
 
-        verify(mInCallController).bindToServices(null);
+        verify(mInCallController).bindToServices(eq(null), anyBoolean());
     }
 
     @SmallTest
@@ -1225,7 +1225,7 @@
 
         mTSIBinder.addNewIncomingCall(TEL_PA_HANDLE_16, extras, CALLING_PACKAGE);
 
-        verify(mInCallController, never()).bindToServices(null);
+        verify(mInCallController, never()).bindToServices(eq(null), anyBoolean());
     }
 
     @SmallTest
@@ -1244,7 +1244,7 @@
 
         mTSIBinder.addNewIncomingCall(TEL_PA_HANDLE_16, extras, CALLING_PACKAGE);
 
-        verify(mInCallController, never()).bindToServices(null);
+        verify(mInCallController, never()).bindToServices(eq(null), anyBoolean());
     }