且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在原生 Android 代码中获取当前时间?

更新时间:2023-01-27 14:31:58

对于微秒级分辨率,您可以使用 gettimeofday().这使用挂钟时间",当设备处于睡眠状态时会继续前进,但如果网络更新设备的时钟,则会突然向前或向后移动.

For microsecond resolution you can use gettimeofday(). This uses "wall clock time", which continues to advance when the device is asleep, but is subject to sudden shifts forward or backward if the network updates the device's clock.

您也可以使用 clock_gettime(CLOCK_MONOTONIC).这使用了单调时钟,它从不向前或向后跳跃,而是在设备休眠时停止计数.

You can also use clock_gettime(CLOCK_MONOTONIC). This uses the monotonic clock, which never leaps forward or backward, but stops counting when the device sleeps.

计时器的实际分辨率取决于设备.

The actual resolution of the timers is device-dependent.

这两个都是 POSIX API,不是 Android 特定的.

Both of these are POSIX APIs, not Android-specific.