@Override
    public void handleMessage(final Message msg) {
      final ApplicationService appService = ApiMethodsImpl.this.appService;
      if (appService == null) {
        return;
      } // we are destroyed

      if (msg.what == MSG_FINISH) {
        workingFlag.set(false);
        appService.checkForStop();
        return;
      }
      workingFlag.set(true);

      final Application app = appService.getApp();
      final RequestMethodHelper h = app.getRequestMethodHelper();

      final RequestDescription description = (RequestDescription) msg.obj;

      final ParserContext pContext = h.createParserContext(description);
      pContext.setSystemContext(appService);
      final int opCode = description.getOperationCode();
      if (DEBUG) {
        Log.d(TAG, "Current context: " + pContext + ", op " + opCode);
      }
      final int token = description.getToken();

      before(description, pContext, appService);

      pending.set(NULL_OPERATION_DATA);
      pending.set(opCode, token);
      try {
        // execute request method
        final RequestMethod rm = h.createRequestMethod(description);
        rm.setup(app);
        rm.start(appService, description, pContext);
        rm.stop(app);

        // process results
        final ResponseData response = pContext.processResults();

        // report results
        if (pContext.isSuccessful()) {
          reportApiSuccess(token, opCode, response);
        } else {
          Log.e(TAG, "Server error: " + response.getErrorCode() + ", " + response.getMessage());
          reportError(token, opCode, response);
        }

      } catch (final RequestMethodException e) {
        Log.e(TAG, "Request method error", e);
        pContext.defineResponse(e);
        reportError(token, opCode, pContext.processResults());
      } finally {
        after(description, pContext, appService);
        dumpLastOperation(lastOperation);
        pending.set(NULL_OPERATION_DATA);
        pContext.destroy();
      }
    }
  public ApiMethodsImpl(final ApplicationService appService) {
    this.appService = appService;

    this.lastOperationDump =
        appService.getSharedPreferences("last-operation", Context.MODE_PRIVATE);
    loadLastOperation();

    defaultErrorMessage = appService.getString(R.string.error_server_default);
    mainWorker = new HandlerThread("api-thread");
    mainWorker.start();
    mainHandler = new ApiMethodsHandler(mainWorker.getLooper());
    if (DEBUG) {
      Log.d(TAG, "Worker thread is now alive " + this);
    }
  }