简体   繁体   中英

Android BLE: Convert ScanResult timestampNanos to System nanoTime

When scanning for Bluetooth Low Energy packets I receive ScanCallback with ScanResult being set. I can get "Device timestamp when the scan result was observed" with result.getTimestampNanos() but this time is not aligned with the Systems.nanoTime(). Is there a way to convert from one to the other?

Use the following code to convert the getTimestampNanos() to system millis by using SystemClock.elapsedRealtime():

long rxTimestampMillis = System.currentTimeMillis() - 
                         SystemClock.elapsedRealtime() +
                         scanResult.getTimestampNanos() / 1000000;

This can be converted easily to a Date object:

Date rxDate = new Date(rxTimestampMillis);

Then you then get the time as a string:

String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);

更优雅的方式来做到这一点

long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```

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