Search code examples
androidtimestampdelayandroid-sensorssensormanager

How do I get subsequent timestamps accurate upto 5 micro seconds in android


Below is sample code I am using:

 private final SensorManager mSensorManager;
 private final Sensor mAccelerometer;
 private long prevTime=0;

 public SensorActivity() {
   mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
   mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
   mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
 }

I require the difference of subsequent system time-stamp values in OnSensorChanged(SensorEvent event) function after the sensor started.

 public void onSensorChanged(SensorEvent event) {
    long systemTimeStamp= SystemClock.elapsedRealtimeNanos();
    long timeDifference = (systemTimeStamp - prevTime) / 1000000;    //msec        
    Log.e("PROBLEM",timeDifference);
    prevTime=systemTimeStamp;
 }

Above difference becomes 0 many times at SENSOR_DELAY_FASTEST //Why??

The difference of subsequent time-stamps reports 0,but according to the definition it should report time in nano sec ,so at 5 micro second the difference should not be Zero. How can I get a non-zero difference or is there any other way to get system time-stamp difference at 5 micro sec accuracy.

Note that,event.timestamp reports timestamps of sensor, but I need timestamps of system in the OnSensorChanged(SensorEvent event) to measure how accurate the sensor timestamps are by comparing with the actual system timestamps.


Solution

  • Based on the comments you might be asking for this:

    public void onSensorChanged(SensorEvent event) {
      long systemTimeStamp= SystemClock.elapsedRealtimeNanos();
      double timeDifference = ((double) (systemTimeStamp - prevTime)) / 1000000d;    //msec        
      Log.e("No PROBLEM",timeDifference);
      prevTime=systemTimeStamp;
    }