public void handleMessage(Message msg) {
          FLog.i(TAG, "Connect Handler get message:" + msg.what);

          switch (msg.what) {
            case Constants.HANDLER_MESSAGE:
              {
                if (msg.obj != null) {}

                break;
              }

            case Constants.HANDLER_WS_DISCONNECTED:
              {
                StateManager.getInstance().pushState(new State(State.STATE_DISCONNECTED));
                if (mQRcode != null && !"".equals(mQRcode)) {
                  FLog.i(TAG, "Web socket disconnected. Reconnect...");
                  mConnectHandler.postDelayed(runnable, Constants.WS_RECONNECT_INTERVAL);
                }

                break;
              }

            case Constants.HANDLER_WS_CONNECTED:
              {
                StateManager.getInstance().pushState(new State(State.STATE_CONNECTED));
                mWSManager.sendHiToServer();
                FLog.i(TAG, "Send pair request to PC!");
                break;
              }

            case Constants.HANDLER_PAIR_SUCCESS:
              {
                if (mWSManager != null) {
                  mWSManager.setPCConnectState(true);
                }

                break;
              }

            case Constants.HANDLER_PC_DISCONNECT:
              {
                StateManager.getInstance().pushState(new State(State.STATE_PC_DISCONNECT));
                if (mWSManager != null) {
                  mWSManager.setPCConnectState(false);
                }
                break;
              }

            case Constants.HANDLER_RECEIVED_MSG:
              {
                break;
              }

            default:
              break;
          }

          super.handleMessage(msg);
        }
  @Override
  public void onCreate() {
    FLog.init(this, "Service_debug.log");
    FLog.i(TAG, "onCreate start.");

    try {
      mEngine = Engine.getEngine();
      mEngine.init(this);
      NetworkManager.getInstance().setContext(this);
      NetworkManager.getInstance().start();
      FLog.i(TAG, "NetworkManager.getInstance().start() success.");

      FacebookChatProxyService.getInstance().setContext(this);
      FLog.i(TAG, "FacebookChatProxyService.getInstance() success.");

      IntentFilter filter = new IntentFilter();
      filter.addAction(Constants.MAINSERVER_NLSERVICERECEIVER_ACTION);
      nlservicereciver = new NLServiceReceiver();
      registerReceiver(nlservicereciver, filter);

      new AsyncTask<Void, Void, Integer>() {
        @Override
        protected Integer doInBackground(Void... params) {
          mEngine.start();

          return null;
        }
      }.execute();

      HandlerThread handThread = new HandlerThread("MessageObtain");
      handThread.start();

      mMessenger = new Messenger(new IncomingHandler(Looper.getMainLooper()));

      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(Constants.ACTION_STOP_SERVICE);
      intentFilter.addAction(Constants.ACTION_GET_LOG_FROM_SERVICE);
      registerReceiver(mReceiver, intentFilter);

      StateManager.getInstance().pushState(new State(State.STATE_DISCONNECTED));

      Intent sendIntent = new Intent();
      sendIntent.setAction(Constants.NOTIFICATIONDAEMONSERVICE_NLSERVICERECEIVER_ACTION);
      sendIntent.putExtra(Constants.NOTIFICATION_COMMAND, Constants.COMMAND_SERVICE_STATE);
      sendBroadcast(sendIntent);
    } catch (Exception e) {
      e.printStackTrace();
    }

    FLog.i(TAG, "onCreate finished.");
  }
 private void reconnectServer() {
   FLog.i(TAG, "reconnectServer");
   closeSwClient();
   createNewSwClient();
   if ((mWSManager != null) && !mWSManager.isConnectedServer()) {
     FLog.i(TAG, "Try to connect to http server, QRCode:" + mQRcode);
     mWSManager.setQRcode(mQRcode);
     StateManager.getInstance().pushState(new State(State.STATE_RECONNECTING));
     try {
       mWSManager.connect();
     } catch (Exception e) {
       FLog.e(TAG, "Web socket reconnect server exception.");
     }
   }
 }
 private void sendStateToUI(State state) {
   try {
     Message msgBack = Message.obtain(null, Constants.MSG_SERVICE_STATE);
     if (msgBack != null) {
       msgBack.arg1 = state.getState();
       msgBack.arg2 = connectType;
       mFrontMessenger.send(msgBack);
       FLog.i(TAG, "sendStateToUI:" + state.toString());
     }
   } catch (RemoteException e) {
     e.printStackTrace();
   }
 }
    // Handler of incoming messages from clients.
    @Override
    public void handleMessage(Message msg) {
      FLog.i(TAG, "Get message: " + msg.what);
      switch (msg.what) {
        case Constants.MSG_REGISTER_CLIENT_REQ:
          {
            if (msg.replyTo != null) {
              mFrontMessenger = msg.replyTo;
              MessengerUtil.setMessenger(mFrontMessenger);
              StateManager.getInstance().registerListener(stateChange);
              FLog.i(TAG, "Client register.");
            } else {
              FLog.i(TAG, "Client register. But front messenger is null.");
            }

            break;
          }
        case Constants.MSG_SET_QCODE_REQ:
          {
            if ((msg != null) && (msg.getData() != null)) {
              String sQCode = msg.getData().getString("QCode");
              FLog.i(TAG, "Set QCode, QCode=" + sQCode);
              mQRcode = sQCode;
              connectType = msg.arg1;
              connectServer();
            }

            break;
          }
        case Constants.MSG_WEBSOCKET_STATE:
          {
            if (null != msg.replyTo) {
              stateChange.onChange(StateManager.getInstance().getCurrentState());
            }
            break;
          }

        case Constants.MSG_DISCONNECT_PC:
          {
            if (connectType == msg.arg1) {
              FLog.i(TAG, "Disconnect PC.");
              closeSwClient();
              mQRcode = "";
              connectType = -1;
              StateManager.getInstance().pushState(new State(State.STATE_PC_DISCONNECT));
            }
            break;
          }

        case Constants.MSG_UNREGISTER_CLIENT:
          {
            FLog.i(TAG, "Unregister client!");
            mFrontMessenger = null;
            MessengerUtil.setMessenger(null);
            StateManager.getInstance().unRegisterListener(stateChange);
            break;
          }
      }
    }
  @Override
  public void onDestroy() {
    FLog.i(TAG, "onDestroy");
    NetworkManager.getInstance().stop();
    this.unregisterReceiver(mReceiver);
    unregisterReceiver(nlservicereciver);

    mEngine.stop();

    closeSwClient();
    mWSManager = null;
    StateManager.getInstance().clearState();
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
      Intent sendIntent = new Intent();
      sendIntent.setAction(Constants.MAINACTIVITY_NLSERVICERECEIVER_ACTION);
      sendIntent.putExtra("data", notificationServiceState);
      sendBroadcast(sendIntent);
    } else {
      FLog.w(TAG, "LINKit can't get the notification message");
    }

    return START_STICKY;
  }
        @Override
        public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();

          if (action.equals(Constants.ACTION_STOP_SERVICE)) {
            FLog.i(TAG, "Stop service myself!");

            MainService.this.stopSelf();
          } else if (action.equals(Constants.ACTION_GET_LOG_FROM_SERVICE)) {
            String logmsg = FLog.getHtmlLogByLevel(Constants.LOG_LEVEL_VERBOSE);
            if ((logmsg != null) && (logmsg.trim().length() > 0)) {
              Bundle bundle = new Bundle();
              bundle.putString("log", logmsg);

              Intent sendbackIntent = new Intent();
              sendbackIntent.setAction(Constants.ACTION_SEND_LOG_FROM_SERVICE);
              sendbackIntent.putExtras(bundle);

              sendBroadcast(sendbackIntent);
            }
          }
        }
  private void createNewSwClient() {
    try {
      String serverIp = UserSetting.getWebSocketAddress(getApplicationContext());
      String server = "ws://" + serverIp;
      if (!serverIp.contains(":")) {
        server += ":" + Constants.WEB_SOCKET_PORT;
      }
      if (Constants.WS_NETWORK_MGR_COUCHBASE == mNetworkMgrMethod) {
        mWSManager =
            new CBRestManager /* CBLManager */(
                getBaseContext(), new URI(UserSetting.getSyncUrl()), mConnectHandler);

        FacebookChatProxyService.getInstance().setManager(mWSManager);
      } else if (Constants.WS_NETWORK_MGR_WEB_SOCKET == mNetworkMgrMethod) {
        mWSManager = new WebSocketManager(getBaseContext(), new URI(server), mConnectHandler);
        FacebookChatProxyService.getInstance().setManager(mWSManager);
      }

      FLog.i(TAG, "createNewSwClient finish, WS address: " + server);

    } catch (Exception e) {
      FLog.w(TAG, "Error on createNewSwClient");
    }
  }
 @Override
 public void onRebind(Intent intent) {
   FLog.i(TAG, "onRebind");
   mFrontMessenger = null;
   super.onRebind(intent);
 }
 @Override
 public IBinder onBind(final Intent intent) {
   FLog.i(TAG, "onBind");
   mFrontMessenger = null;
   return mMessenger.getBinder();
 }
 private void closeSwClient() {
   if ((mWSManager != null) && mWSManager.isConnectedServer()) {
     FLog.i(TAG, "closeSwClient");
     mWSManager.close();
   }
 }