I want to display the time which the first step was detected. But the app always shows Jan 01 1970. Would some one check what is wrong and how to change it? Here is my code:
public void run() {
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
mSensorManager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
long timeStamp = sensorEvent.timestamp / 1000000;
textView_moveTime.setText(DateUtils.getRelativeTimeSpanString(timeStamp));
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}, mSensor, mSensorManager.SENSOR_DELAY_FASTEST);
}
SensorEvent reports time in nanoseconds since system boot (including sleep time). To convert it to absolute time in nanos, use following formula:
(DateTime.now().getMillis() - SystemClock.elapsedRealtime()) * 1000000
+ sensorEvent.timestamp
SensorEvent.timestamp
is when the event happened, but it is an elapsed time since boot. It is not absolute time. We want to convert it into absolute time.
Reference: https://developer.android.com/reference/android/hardware/SensorEvent#timestamp
Millis
here.System.currentTimeMillis()
b) SystemClock.elapsedRealtime()
and c) SensorEvent.timestamp
SystemClock.elapsedRealtimeNanos()
, then we need to convert it into Millis
as below:val systemCurrentTimeMillis = System.currentTimeMillis()
val systemClockElapsedRealtimeMillis = TimeUnit.NANOSECONDS.toMillis(SystemClock.elapsedRealtimeNanos())
val sensorEventTimeStampMillis = TimeUnit.NANOSECONDS.toMillis(sensorEvent.timestamp)
systemCurrentTimeMillis
, and systemClockElapsedRealtimeMillis
as below:val currentMinusElapsedRealtimeMillis = systemCurrentTimeMillis - systemClockElapsedRealtimeMillis
sensorEventTimeStampMillis
to it as below:val actualEventTimeMillis = currentMinusElapsedRealtimeMillis + sensorEventTimeStampMillis
Joda Time
):val actualEventTimeUtc = DateTime(actualEventTimeMillis, DateTimeZone.UTC)
The actualEventTimeUtc
is the absolute time when the event happened.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.