Android BLE:将 ScanResult timestampNanos 转换为 System nanoTime

heb*_*eha 3 android timestamp bluetooth bluetooth-lowenergy

扫描低功耗蓝牙数据包时,我收到 ScanCallback 并设置了 ScanResult。我可以通过 result.getTimestampNanos() 获得“观察到扫描结果时的设备时间戳”,但这次与 Systems.nanoTime() 不一致。有没有办法从一种转换到另一种?

Gle*_*enn 5

使用以下代码通过 SystemClock.elapsedRealtime() 将 getTimestampNanos() 转换为系统毫秒:

long rxTimestampMillis = System.currentTimeMillis() - 
                         SystemClock.elapsedRealtime() +
                         scanResult.getTimestampNanos() / 1000000;
Run Code Online (Sandbox Code Playgroud)

这可以轻松转换为 Date 对象:

Date rxDate = new Date(rxTimestampMillis);
Run Code Online (Sandbox Code Playgroud)

然后你将时间作为一个字符串:

String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);
Run Code Online (Sandbox Code Playgroud)

  • tx 和 rx 是接收和传输的常用缩写。我从同时使用“tx”和“rx”时间戳的源文件中粘贴了这段代码。在这种情况下,问题是关于接收时间戳,所以我留下了 rx 前缀。 (2认同)