private synchronized void connectIfEnabled(BluetoothDevice device) {
   CachedBluetoothDevice cachedDevice = getCachedBluetoothDevice(device);
   List<LocalBluetoothProfile> profiles = cachedDevice.getConnectableProfiles();
   for (LocalBluetoothProfile profile : profiles) {
     if (profile.getPreferred(device) == BluetoothProfile.PRIORITY_AUTO_CONNECT) {
       cachedDevice.connect(false);
       return;
     }
   }
 }
  private synchronized void applyBtSettings(BluetoothDevice device, int startId) {
    if (device == null || mProfiles == null || mCheckedItems == null || mLocalAdapter == null) {
      return;
    }

    // Turn on BT if something is enabled
    for (boolean enable : mCheckedItems) {
      if (enable) {
        int btState = mLocalAdapter.getBluetoothState();
        if (DEBUG) {
          Log.d(TAG, "BtState = " + btState);
        }
        // May have race condition as the phone comes in and out and in the dock.
        // Always turn on BT
        mLocalAdapter.enable();

        // if adapter was previously OFF, TURNING_OFF, or TURNING_ON
        if (btState != BluetoothAdapter.STATE_ON) {
          if (mPendingDevice != null && mPendingDevice.equals(mDevice)) {
            return;
          }

          mPendingDevice = device;
          mPendingStartId = startId;
          if (btState != BluetoothAdapter.STATE_TURNING_ON) {
            getPrefs().edit().putBoolean(KEY_DISABLE_BT_WHEN_UNDOCKED, true).apply();
          }
          return;
        }
      }
    }

    mPendingDevice = null;

    boolean callConnect = false;
    CachedBluetoothDevice cachedDevice = getCachedBluetoothDevice(device);
    for (int i = 0; i < mProfiles.length; i++) {
      LocalBluetoothProfile profile = mProfiles[i];
      if (DEBUG) Log.d(TAG, profile.toString() + " = " + mCheckedItems[i]);

      if (mCheckedItems[i]) {
        // Checked but not connected
        callConnect = true;
      } else if (!mCheckedItems[i]) {
        // Unchecked, may or may not be connected.
        int status = profile.getConnectionStatus(cachedDevice.getDevice());
        if (status == BluetoothProfile.STATE_CONNECTED) {
          if (DEBUG) Log.d(TAG, "applyBtSettings - Disconnecting");
          cachedDevice.disconnect(mProfiles[i]);
        }
      }
      profile.setPreferred(device, mCheckedItems[i]);
      if (DEBUG) {
        if (mCheckedItems[i] != profile.isPreferred(device)) {
          Log.e(TAG, "Can't save preferred value");
        }
      }
    }

    if (callConnect) {
      if (DEBUG) Log.d(TAG, "applyBtSettings - Connecting");
      cachedDevice.connect(false);
    }
  }