public static void setState(ActivityRecognitionResult result) {
    DetectedActivity da = result.getMostProbableActivity();

    int state = da.getType();

    log.debug(
        "DetectedActivity: "
            + DateTimes.timeFormat().format(result.getTime())
            + " - "
            + getStateText(state)
            + ", "
            + da.getConfidence()
            + ", "
            + DateTimes.timeFormat().format(result.getElapsedRealtimeMillis()));

    if (Collections.isEmpty(states)) {
      states.put(state, 0L);
      lastState = state;
      lastStart = System.currentTimeMillis();
      return;
    }

    Long ltime = states.get(lastState);
    if (ltime != null) {
      ltime += (System.currentTimeMillis() - lastStart);
      states.put(lastState, ltime);
    }

    lastState = state;
    lastStart = System.currentTimeMillis();

    if (!states.containsKey(state)) {
      states.put(state, 0L);
    }
  }
  private static int getBestState() {
    if (Collections.isEmpty(states)) {
      return DetectedActivity.UNKNOWN;
    }

    long max = 0;
    for (Long time : states.values()) {
      if (time > max) {
        max = time;
      }
    }

    int state = DetectedActivity.UNKNOWN;
    for (Entry<Integer, Long> en : states.entrySet()) {
      if (max == en.getValue()) {
        state = en.getKey();
        break;
      }
    }

    states.clear();

    states.put(lastState, 0L);
    lastStart = System.currentTimeMillis();

    return state;
  }