Im currently working on a android application.. I have to log the accelerometer sensor event coordinate with event time. I got the sensor event timestamp like "3497855005850" but i am not able to convert event timestamp into user readable date time format.Thanks in advance
How can i convert SensorEvent timestamp to unix timestamp?
The sensor timestamp is actually nanoseconds of uptime, not system time in nanoseconds. See SensorEvent. timestamp to absolute (utc) timestamp?. In theory, you can convert sensor timestamp to time in milliseconds using: long timeInMillis = (new Date()).
android.hardware.SensorEvent. This class represents a Sensor event and holds information such as the sensor's type, the time-stamp, accuracy and of course the sensor's data .
Sensor listener. Once you acquired a sensor, you can register a SensorEventListener object on it. This listener will get informed, if the sensor data changes. To avoid the unnecessary usage of battery power, you can register your listener in the onResume() method and de-register it in the onPause() method.
The sensor timestamp is actually nanoseconds of uptime, not system time in nanoseconds. See SensorEvent.timestamp to absolute (utc) timestamp?.
In theory, you can convert sensor timestamp to time in milliseconds using:
long timeInMillis = (new Date()).getTime() + (sensorEvent.timestamp - System.nanoTime()) / 1000000L;
You could even bracket the (new Date()).getTime()
call with two System.nanoTime()
calls and average them to get closer to the actual offset.
Then you can format the sensor time as date and time.
You can set referent time variables in your onSensorChanged(SensorEvent)
function.
Reference for current time and event time. When event arrives subtract sensor referent time from event time and you will have difference in nanoseconds. You can add that difference divided by 1,000,000 to current time reference to get event time in milliseconds.
Error with calculating this can be max 0.5 milliseconds for one event. You can minimize error by changing referent times occasionally.
private long sensorTimeReference = 0l; private long myTimeReference = 0l; public void onSensorChanged(SensorEvent event) { // set reference times if(sensorTimeReference == 0l && myTimeReference == 0l) { sensorTimeReference = event.timestamp; myTimeReference = System.currentTimeMillis(); } // set event timestamp to current time in milliseconds event.timestamp = myTimeReference + Math.round((event.timestamp - sensorTimeReference) / 1000000.0); // some code... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With