private boolean changeState(State newState, Runnable callback) {
   if (isTransitionLegal(currentState, newState)) {
     if (Debug.isDebugConnection()) {
       Log.d(LOG_TAG, "Changing state: " + currentState + " -> " + newState);
     }
     currentState = newState;
     if (callback != null) {
       callback.run();
     }
     sendNotification();
     return true;
   }
   if (Debug.isDebugConnection()) {
     Log.d(LOG_TAG, "Illegal transition: " + currentState + " -> " + newState);
   }
   return false;
 }
    private void sendNotification() {
      if (connectionListener == null) {
        pendingNotification = true;
        if (Debug.isDebugConnection()) {
          Log.d(LOG_TAG, "Pending notification: " + currentState);
        }
        return;
      }
      pendingNotification = false;
      if (Debug.isDebugConnection()) {
        Log.d(LOG_TAG, "Sending notification: " + currentState + " to " + connectionListener);
      }
      switch (currentState) {
        case IDLE:
          break;

        case CONNECTING:
          connectionListener.onConnecting();
          break;

        case CONNECTED:
          connectionListener.onConnectionSuccessful(
              Debug.isDebugConnectionLess() ? new DummySender() : anymoteSender);
          break;

        case DISCONNECTING:
          connectionListener.onDisconnected();
          break;

        case DEVICE_FINDER:
          connectionListener.onShowDeviceFinder();
          break;

        case PAIRING:
          if (target != null) {
            connectionListener.onNeedsPairing(target);
          } else {
            connectionListener.onShowDeviceFinder();
          }
          break;

        default:
          throw new IllegalStateException("Unsupported state: " + currentState);
      }
    }
 private void handleSetKeepConnected(boolean keepConnected) {
   keepConnectedRefcount += keepConnected ? 1 : -1;
   if (Debug.isDebugConnection()) {
     Log.d(LOG_TAG, "KeepConnectedRefcount: " + keepConnectedRefcount);
   }
   if (keepConnectedRefcount < 0) {
     throw new IllegalStateException("KeepConnectedRefCount < 0");
   }
   if (connectionListener == null) {
     disconnect(false);
   }
 }
 private void connect() {
   if (Debug.isDebugConnection()) {
     Log.d(LOG_TAG, "Connecting to: " + target);
   }
   if (sendSocket != null) {
     throw new IllegalStateException("Already connected");
   }
   if (target == null) {
     changeState(State.DEVICE_FINDER);
     return;
   }
   startConnectionTask(target);
 }
 private boolean isConnected() {
   return Debug.isDebugConnectionLess() || sendSocket != null;
 }