// TODO: move to background thread to fix strict mode warnings
  private void handleBtStateChange(Intent intent, int startId) {
    int btState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
    synchronized (this) {
      if (DEBUG) Log.d(TAG, "BtState = " + btState + " mPendingDevice = " + mPendingDevice);
      if (btState == BluetoothAdapter.STATE_ON) {
        handleBluetoothStateOn(startId);
      } else if (btState == BluetoothAdapter.STATE_TURNING_OFF) {
        // Remove the flag to disable BT if someone is turning off bt.
        // The rational is that:
        // a) if BT is off at undock time, no work needs to be done
        // b) if BT is on at undock time, the user wants it on.
        getPrefs().edit().remove(KEY_DISABLE_BT_WHEN_UNDOCKED).apply();
        DockEventReceiver.finishStartingService(this, startId);
      } else if (btState == BluetoothAdapter.STATE_OFF) {
        // Bluetooth was turning off as we were trying to turn it on.
        // Let's try again
        if (DEBUG) Log.d(TAG, "Bluetooth = OFF mPendingDevice = " + mPendingDevice);

        if (mPendingTurnOffStartId != INVALID_STARTID) {
          DockEventReceiver.finishStartingService(this, mPendingTurnOffStartId);
          getPrefs().edit().remove(KEY_DISABLE_BT).apply();
          mPendingTurnOffStartId = INVALID_STARTID;
        }

        if (mPendingDevice != null) {
          mLocalAdapter.enable();
          mPendingTurnOnStartId = startId;
        } else {
          DockEventReceiver.finishStartingService(this, startId);
        }
      }
    }
  }
  private void handleBluetoothStateOn(int startId) {
    if (mPendingDevice != null) {
      if (mPendingDevice.equals(mDevice)) {
        if (DEBUG) {
          Log.d(TAG, "applying settings");
        }
        applyBtSettings(mPendingDevice, mPendingStartId);
      } else if (DEBUG) {
        Log.d(TAG, "mPendingDevice  (" + mPendingDevice + ") != mDevice (" + mDevice + ')');
      }

      mPendingDevice = null;
      DockEventReceiver.finishStartingService(this, mPendingStartId);
    } else {
      final SharedPreferences prefs = getPrefs();
      if (DEBUG) {
        Log.d(
            TAG,
            "A DISABLE_BT_WHEN_UNDOCKED = "
                + prefs.getBoolean(KEY_DISABLE_BT_WHEN_UNDOCKED, false));
      }
      // Reconnect if docked and bluetooth was enabled by user.
      Intent i = registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT));
      if (i != null) {
        int state = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED);
        if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
          BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          if (device != null) {
            connectIfEnabled(device);
          }
        } else if (prefs.getBoolean(KEY_DISABLE_BT, false) && mLocalAdapter.disable()) {
          mPendingTurnOffStartId = startId;
          prefs.edit().remove(KEY_DISABLE_BT).apply();
          return;
        }
      }
    }

    if (mPendingTurnOnStartId != INVALID_STARTID) {
      DockEventReceiver.finishStartingService(this, mPendingTurnOnStartId);
      mPendingTurnOnStartId = INVALID_STARTID;
    }

    DockEventReceiver.finishStartingService(this, startId);
  }
 private boolean msgTypeDisableBluetooth(int startId) {
   if (DEBUG) {
     Log.d(TAG, "BT DISABLE");
   }
   final SharedPreferences prefs = getPrefs();
   if (mLocalAdapter.disable()) {
     prefs.edit().remove(KEY_DISABLE_BT_WHEN_UNDOCKED).apply();
     return false;
   } else {
     // disable() returned an error. Persist a flag to disable BT later
     prefs.edit().putBoolean(KEY_DISABLE_BT, true).apply();
     mPendingTurnOffStartId = startId;
     if (DEBUG) {
       Log.d(TAG, "disable failed. try again later " + startId);
     }
     return true;
   }
 }
  synchronized boolean hasOtherConnectedDevices(BluetoothDevice dock) {
    Collection<CachedBluetoothDevice> cachedDevices = mDeviceManager.getCachedDevicesCopy();
    Set<BluetoothDevice> btDevices = mLocalAdapter.getBondedDevices();
    if (btDevices == null || cachedDevices == null || btDevices.isEmpty()) {
      return false;
    }
    if (DEBUG) {
      Log.d(TAG, "btDevices = " + btDevices.size());
      Log.d(TAG, "cachedDeviceUIs = " + cachedDevices.size());
    }

    for (CachedBluetoothDevice deviceUI : cachedDevices) {
      BluetoothDevice btDevice = deviceUI.getDevice();
      if (!btDevice.equals(dock) && btDevices.contains(btDevice) && deviceUI.isConnected()) {
        if (DEBUG) Log.d(TAG, "connected deviceUI = " + deviceUI.getName());
        return true;
      }
    }
    return false;
  }
  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);
    }
  }