/**
   * Implementation of the functionality related to connecting our app to the AllJoyn bus. We expect
   * that this method will only be called in the context of the AllJoyn bus handler thread; and
   * while we are in the DISCONNECTED state.
   */
  private void doConnect() {
    Log.i(TAG, "doConnect()");
    org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
    assert (mBusAttachmentState == BusAttachmentState.DISCONNECTED);
    mBus.useOSLogging(true);
    mBus.setDebugLevel("ALLJOYN_JAVA", 7);
    mBus.registerBusListener(mBusListener);
    mBus.registerAboutListener(mTestListener);

    /*
     * To make a service available to other AllJoyn peers, first
     * register a BusObject with the BusAttachment at a specific
     * object path.  Our service is implemented by the ChatService
     * BusObject found at the "/chatService" object path.
     */
    // Status status = mBus.registerBusObject(mChatService, OBJECT_PATH);
    // if (Status.OK != status) {
    //   mChatApplication.alljoynError(ChatApplication.Module.HOST, "Unable to register the chat bus
    // object: (" + status + ")");
    //    return;
    // }

    Status status = mBus.connect();
    if (status != Status.OK) {
      mActivity.alljoynError(
          MainActivity.Module.GENERAL, "Unable to connect to the bus: (" + status + ")");
      return;
    }

    status = mBus.registerSignalHandlers(this);
    if (status != Status.OK) {
      mActivity.alljoynError(
          MainActivity.Module.GENERAL, "Unable to register signal handlers: (" + status + ")");
      return;
    }

    mBusAttachmentState = BusAttachmentState.CONNECTED;
  }
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case (CONNECT):
          {
            org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
            mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive);

            mBus.registerBusListener(
                new BusListener() {
                  @Override
                  public void foundAdvertisedName(String name, short transport, String namePrefix) {
                    logInfo(
                        String.format(
                            "MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)",
                            name, transport, namePrefix));
                    /*
                     * This client will only join the first service that it sees advertising
                     * the indicated well-known name.  If the program is already a member of
                     * a session (i.e. connected to a service) we will not attempt to join
                     * another session.
                     * It is possible to join multiple session however joining multiple
                     * sessions is not shown in this sample.
                     */
                    if (!mIsConnected) {
                      Message msg = obtainMessage(JOIN_SESSION, name);
                      sendMessage(msg);
                    }
                  }
                });

            // Connect the BusAttachment with the bus.
            Status status = mBus.connect();
            logStatus("BusAttachment.connect()", status);
            if (Status.OK != status) {
              finish();
              return;
            }

            status = mBus.findAdvertisedName(SERVICE_NAME);
            logStatus("BusAttachement.findAdvertisedName()", status);
            if (Status.OK != status) {
              finish();
              return;
            }
            break;
          }
        case (JOIN_SESSION):
          {
            /*
             * If discovery is currently being stopped don't join to any other sessions.
             */
            if (mIsStoppingDiscovery) {
              break;
            }

            /*
             * In order to join the session, we need to provide the well-known
             * contact port.  This is pre-arranged between both sides as part
             * of the definition of the chat service.  As a result of joining
             * the session, we get a session identifier which we must use to
             * identify the created session communication channel whenever we
             * talk to the remote side.
             */
            short contactPort = CONTACT_PORT;
            SessionOpts sessionOpts = new SessionOpts();
            Mutable.IntegerValue sessionId = new Mutable.IntegerValue();

            Status status =
                mBus.joinSession(
                    (String) msg.obj,
                    contactPort,
                    sessionId,
                    sessionOpts,
                    new SessionListener() {
                      @Override
                      public void sessionLost(int sessionId, int reason) {
                        mIsConnected = false;
                        logInfo(
                            String.format(
                                "MyBusListener.sessionLost(sessionId = %d, reason = %d)",
                                sessionId, reason));
                        mHandler.sendEmptyMessage(MESSAGE_START_PROGRESS_DIALOG);
                      }
                    });
            logStatus("BusAttachment.joinSession()", status);
            if (status == Status.OK) {
              mProxyObj =
                  mBus.getProxyBusObject(
                      SERVICE_NAME,
                      "/testProperties",
                      sessionId.value,
                      new Class<?>[] {PropertiesInterface.class});

              mPropertiesInterface = mProxyObj.getInterface(PropertiesInterface.class);
              mSessionId = sessionId.value;
              mIsConnected = true;
              mHandler.sendEmptyMessage(MESSAGE_STOP_PROGRESS_DIALOG);
            }
            break;
          }
        case (DISCONNECT):
          {
            mIsStoppingDiscovery = true;
            if (mIsConnected) {
              Status status = mBus.leaveSession(mSessionId);
              logStatus("BusAttachment.leaveSession()", status);
            }
            mBus.disconnect();
            getLooper().quit();
            break;
          }
        case (GET_BACKGROUND_COLOR_PROPERTY):
          {
            if (!mIsConnected) {
              break;
            }
            try {
              String backgroundColor = mPropertiesInterface.getBackGroundColor();
              mHandler.sendMessage(
                  mHandler.obtainMessage(MESSAGE_UPDATE_BACKGROUND_COLOR, backgroundColor));
            } catch (BusException e) {
            }
            break;
          }
        case (SET_BACKGROUND_COLOR_PROPERTY):
          {
            if (!mIsConnected) {
              break;
            }
            try {
              mPropertiesInterface.setBackGroundColor((String) msg.obj);
              mHandler.sendMessage(
                  mHandler.obtainMessage(MESSAGE_UPDATE_BACKGROUND_COLOR, (String) msg.obj));
            } catch (BusException e) {
              logException(getString(R.string.get_properties_error), e);
            }
            break;
          }
        case (GET_TEXT_SIZE_PROPERTY):
          {
            if (!mIsConnected) {
              break;
            }
            try {
              int textSize = mPropertiesInterface.getTextSize();
              Message textMsg = mHandler.obtainMessage(MESSAGE_UPDATE_TEXT_SIZE);
              textMsg.arg1 = textSize;
              mHandler.sendMessage(textMsg);
            } catch (BusException e) {
              logException(getString(R.string.get_properties_error), e);
            }
            break;
          }
        case (SET_TEXT_SIZE_PROPERTY):
          {
            if (!mIsConnected) {
              break;
            }
            try {
              mPropertiesInterface.setTextSize(msg.arg1);
              Message textMsg = mHandler.obtainMessage(MESSAGE_UPDATE_TEXT_SIZE);
              textMsg.arg1 = msg.arg1;
              mHandler.sendMessage(textMsg);
            } catch (BusException e) {
              logException(getString(R.string.get_properties_error), e);
            }
            break;
          }
        default:
          break;
      }
    }
      @Override
      public void handleMessage(Message msg) {
        switch (msg.what) {
            /* Connect to a remote instance of an object implementing the BasicInterface. */
          case CONNECT:
            {
              org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
              /*
               * All communication through AllJoyn begins with a BusAttachment.
               *
               * A BusAttachment needs a name. The actual name is unimportant except for internal
               * security. As a default we use the class name as the name.
               *
               * By default AllJoyn does not allow communication between devices (i.e. bus to bus
               * communication). The second argument must be set to Receive to allow communication
               * between devices.
               */
              mBus = new BusAttachment(getPackageName(), BusAttachment.RemoteMessage.Receive);

              /*
               * Create a bus listener class
               */
              mBus.registerBusListener(
                  new BusListener() {
                    @Override
                    public void foundAdvertisedName(
                        String name, short transport, String namePrefix) {
                      logInfo(
                          String.format(
                              "MyBusListener.foundAdvertisedName(%s, 0x%04x, %s)",
                              name, transport, namePrefix));
                      /*
                       * This client will only join the first service that it sees advertising
                       * the indicated well-known name.  If the program is already a member of
                       * a session (i.e. connected to a service) we will not attempt to join
                       * another session.
                       * It is possible to join multiple session however joining multiple
                       * sessions is not shown in this sample.
                       */
                      if (!mIsConnected) {
                        Message msg = obtainMessage(JOIN_SESSION);
                        msg.arg1 = transport;
                        msg.obj = name;
                        sendMessage(msg);
                      }
                    }
                  });

              /* To communicate with AllJoyn objects, we must connect the BusAttachment to the bus. */
              Status status = mBus.connect();
              logStatus("BusAttachment.connect()", status);
              if (Status.OK != status) {
                finish();
                return;
              }

              /*
               * Now find an instance of the AllJoyn object we want to call.  We start by looking for
               * a name, then connecting to the device that is advertising that name.
               *
               * In this case, we are looking for the well-known SERVICE_NAME.
               */
              status = mBus.findAdvertisedName(SERVICE_NAME);
              logStatus(
                  String.format("BusAttachement.findAdvertisedName(%s)", SERVICE_NAME), status);
              if (Status.OK != status) {
                finish();
                return;
              }

              break;
            }
          case (JOIN_SESSION):
            {
              /*
               * If discovery is currently being stopped don't join to any other sessions.
               */
              if (mIsStoppingDiscovery) {
                break;
              }

              /*
               * In order to join the session, we need to provide the well-known
               * contact port.  This is pre-arranged between both sides as part
               * of the definition of the chat service.  As a result of joining
               * the session, we get a session identifier which we must use to
               * identify the created session communication channel whenever we
               * talk to the remote side.
               */
              short contactPort = CONTACT_PORT;
              SessionOpts sessionOpts = new SessionOpts();
              sessionOpts.transports = (short) msg.arg1;
              Mutable.IntegerValue sessionId = new Mutable.IntegerValue();

              Status status =
                  mBus.joinSession(
                      (String) msg.obj,
                      contactPort,
                      sessionId,
                      sessionOpts,
                      new SessionListener() {
                        @Override
                        public void sessionLost(int sessionId, int reason) {
                          mIsConnected = false;
                          logInfo(
                              String.format(
                                  "MyBusListener.sessionLost(sessionId = %d, reason = %d)",
                                  sessionId, reason));
                          mHandler.sendEmptyMessage(MESSAGE_ALLJOYN_START_PROGRESS_DIALOG);
                        }
                      });
              logStatus("BusAttachment.joinSession() - sessionId: " + sessionId.value, status);

              if (status == Status.OK) {
                /*
                 * To communicate with an AllJoyn object, we create a ProxyBusObject.
                 * A ProxyBusObject is composed of a name, path, sessionID and interfaces.
                 *
                 * This ProxyBusObject is located at the well-known SERVICE_NAME, under path
                 * "/sample", uses sessionID of CONTACT_PORT, and implements the BasicInterface.
                 */
                mProxyObj =
                    mBus.getProxyBusObject(
                        SERVICE_NAME,
                        OBJ_PATH,
                        sessionId.value,
                        new Class<?>[] {BasicInterface.class});

                /* We make calls to the methods of the AllJoyn object through one of its interfaces. */
                mBasicInterface = mProxyObj.getInterface(BasicInterface.class);

                mSessionId = sessionId.value;
                mIsConnected = true;
                mHandler.sendEmptyMessage(MESSAGE_ALLJOYN_STOP_PROGRESS_DIALOG);
              }
              break;
            }

            /* Release all resources acquired in the connect. */
          case DISCONNECT:
            {
              mIsStoppingDiscovery = true;
              if (mIsConnected) {
                Status status = mBus.leaveSession(mSessionId);
                logStatus("BusAttachment.leaveSession()", status);
              }
              mBus.disconnect();
              getLooper().quit();
              break;
            }

            /*
             * Call the service's Cat method through the ProxyBusObject.
             *
             * This will also print the String that was sent to the service and the String that was
             * received from the service to the user interface.
             */
          case GET_TOPIC:
            {
              try {
                if (mBasicInterface != null) {
                  // sendUiMessage(MESSAGE_PING, msg.obj + " and " + msg.obj);
                  // String reply = mBasicInterface.cat((String) msg.obj, (String) msg.obj);
                  String reply = mBasicInterface.get_topic((String) msg.obj);
                  sendUiMessage(MESSAGE_ALLJOYN_GETTOPIC_REPLY, reply);
                }
              } catch (BusException ex) {
                logException("BasicInterface.cat()", ex);
              }
              break;
            }
          default:
            break;
        }
      }