@Override
  public void onDestroy() {
    currentState = STATE_DISCONNECTING;

    if (sensorsManager != null) {
      sensorsManager.disconnectFromSensors();
      sensorsManager.removeRecordDataListener(this);
    }
    if (wakeLock != null
        && wakeLock
            .isHeld()) { // True if the wakeLock has been instantiated and is currently being used
      wakeLock.release();
      Log.d(TAG, "WakeLock released");
    }

    // Set the static variables back to their fail-safe defaults, as they will persist
    useWakeLock = false;
    currentState = STATE_NOT_CONNECTED;
    if (uiMessageHandler != null) {
      uiMessageHandler.sendEmptyMessage(
          SensorsManager
              .MESSAGE_TYPE_DISCONNECTION_COMPLETE); // Inform the handler that disconnection is
      // complete
      // Do this here as the child service may have already removed the event listener
    }
    super.onDestroy();
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    currentState = STATE_CONNECTING;

    if (useWakeLock) {
      powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
      wakeLock =
          powerManager.newWakeLock(
              PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
      wakeLock.acquire();
      Log.d(TAG, "WakeLock acquired");
    }

    if (sensorsManager != null) {
      // sensorsManager.requestAllDataTypes();			//And all data types
      sensorsManager.connectToAvailableSensors(); // Connect to the sensors
      sensorsManager.addRecordDataListener(this);
    } else {
      Log.e(TAG, "CRITICAL ERROR, SENSORS MANAGER NOT SET");
      currentState = STATE_NOT_CONNECTED;
      stopSelf(); // We cannot continue without a SensorsManager
    }

    // We don't want the OS to restart this service on its own
    return START_NOT_STICKY;
  }
 /**
  * Signals to the {@link SensorsManager} that it should stop recording sensor data. This will not
  * disconnect from the sensors, that is done when the service is destroyed.
  */
 public static void stopRecordingFromSensors() {
   if (currentState == STATE_RECORDING && sensorsManager != null) {
     sensorsManager.stopRecordingFromSensors();
     currentState = STATE_CONNECTED;
   }
 }
 public static void startRecordingFromSensors(File dataLoggingDirectory) {
   if (currentState == STATE_CONNECTED && sensorsManager != null) {
     sensorsManager.startRecordingFromSensors(dataLoggingDirectory);
     currentState = STATE_RECORDING;
   }
 }