Do not route audio to speaker if Bluetooth audio is connected

In some devices a magnetic charging port doubles as a dock connector
and if user is charging phone and the charge port is identified as a
dock the voice audio will be routed through the phone speaker even if
Bluetooth audio is connected.

Priorities Bluetooth over dock and route audio to Bluetooth if
connected.

Bug: 28914501
Author: Mathias Jeppsson <mathias.jeppsson@sonymobile.com>
Change-Id: Ib09fa96f8d78a8a8f202fca69c92ee88cb181f7a
diff --git a/src/com/android/server/telecom/CallsManager.java b/src/com/android/server/telecom/CallsManager.java
index 6913fcf..86689f0 100644
--- a/src/com/android/server/telecom/CallsManager.java
+++ b/src/com/android/server/telecom/CallsManager.java
@@ -923,18 +923,18 @@
 
         final boolean useSpeakerWhenDocked = mContext.getResources().getBoolean(
                 R.bool.use_speaker_when_docked);
-        final boolean isDocked = mDockManager.isDocked();
+        final boolean useSpeakerForDock = isSpeakerphoneEnabledForDock();
         final boolean useSpeakerForVideoCall = isSpeakerphoneAutoEnabled(videoState);
 
         // Auto-enable speakerphone if the originating intent specified to do so, if the call
         // is a video call, of if using speaker when docked
         call.setStartWithSpeakerphoneOn(speakerphoneOn || useSpeakerForVideoCall
-                || (useSpeakerWhenDocked && isDocked));
+                || (useSpeakerWhenDocked && useSpeakerForDock));
         call.setVideoState(videoState);
 
         if (speakerphoneOn) {
             Log.i(this, "%s Starting with speakerphone as requested", call);
-        } else if (useSpeakerWhenDocked && useSpeakerWhenDocked) {
+        } else if (useSpeakerWhenDocked && useSpeakerForDock) {
             Log.i(this, "%s Starting with speakerphone because car is docked.", call);
         } else if (useSpeakerForVideoCall) {
             Log.i(this, "%s Starting with speakerphone because its a video call.", call);
@@ -1045,6 +1045,19 @@
     }
 
     /**
+     * Determines if the speakerphone should be enabled for when docked.  Speakerphone
+     * should be enabled if the device is docked and bluetooth or the wired headset are
+     * not in use.
+     *
+     * @return {@code true} if the speakerphone should be enabled for the dock.
+     */
+    private boolean isSpeakerphoneEnabledForDock() {
+        return mDockManager.isDocked() &&
+            !mWiredHeadsetManager.isPluggedIn() &&
+            !mBluetoothManager.isBluetoothAvailable();
+    }
+
+    /**
      * Determines if the speakerphone should be automatically enabled for video calls.
      *
      * @return {@code true} if the speakerphone should automatically be enabled.