简体   繁体   中英

How to display the exactly time from sensorevent.timestamp for Android?

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

  1. We need all the entities in a similar unit. We are taking Millis here.
  2. We have three entities to use. a) System.currentTimeMillis() b) SystemClock.elapsedRealtime() and c) SensorEvent.timestamp

在此处输入图像描述

  1. If we use 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)
  1. We need to find the difference between the systemCurrentTimeMillis , and systemClockElapsedRealtimeMillis as below:

在此处输入图像描述

val currentMinusElapsedRealtimeMillis = systemCurrentTimeMillis - systemClockElapsedRealtimeMillis
  1. Once we find the difference, we need to add sensorEventTimeStampMillis to it as below:

在此处输入图像描述 OR在此处输入图像描述

val actualEventTimeMillis = currentMinusElapsedRealtimeMillis + sensorEventTimeStampMillis
  1. Then, we need to convert the result into UTC as below (I am using 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM