Android BLE:将 ScanResult timestampNanos 转换为系统 nanoTime
Android BLE: Convert ScanResult timestampNanos to System nanoTime
扫描低功耗蓝牙数据包时,我收到 ScanCallback 并设置了 ScanResult。我可以用 result.getTimestampNanos() 得到 "Device timestamp when the scan result was observed" 但这次与 Systems.nanoTime() 不一致。有没有办法从一种转换成另一种?
使用以下代码通过使用 SystemClock.elapsedRealtime() 将 getTimestampNanos() 转换为系统毫秒:
long rxTimestampMillis = System.currentTimeMillis() -
SystemClock.elapsedRealtime() +
scanResult.getTimestampNanos() / 1000000;
这可以很容易地转换为 Date 对象:
Date rxDate = new Date(rxTimestampMillis);
然后您将时间作为字符串获取:
String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);
更优雅的方式
long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```
扫描低功耗蓝牙数据包时,我收到 ScanCallback 并设置了 ScanResult。我可以用 result.getTimestampNanos() 得到 "Device timestamp when the scan result was observed" 但这次与 Systems.nanoTime() 不一致。有没有办法从一种转换成另一种?
使用以下代码通过使用 SystemClock.elapsedRealtime() 将 getTimestampNanos() 转换为系统毫秒:
long rxTimestampMillis = System.currentTimeMillis() -
SystemClock.elapsedRealtime() +
scanResult.getTimestampNanos() / 1000000;
这可以很容易地转换为 Date 对象:
Date rxDate = new Date(rxTimestampMillis);
然后您将时间作为字符串获取:
String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);
更优雅的方式
long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```