简体   繁体   English

android - System.currentTimeMillis()无法按预期工作

[英]android - System.currentTimeMillis() does not work as expected

I use System.currentTimeMillis() to save the time a user starts an activity. 我使用System.currentTimeMillis()来节省用户启动活动的时间。

public class TimeStamp {
protected long _startTimeMillis = System.currentTimeMillis();

public String getStartTime() {
    return new Time(_startTimeMillis).toString();
}

the class is instantiated when activity is started and getStartTime() returns the correct time. 在活动开始时实例化类,getStartTime()返回正确的时间。 I also try to get the time that has passed after the activity has been started. 我也试着获得活动开始后经过的时间。

public String getElapsedTime() {
    return new Time(System.currentTimeMillis() - _startTimeMillis).toString();
}

This works perfectly fine using an emulated android device (android 4.0.3). 这使用模拟的Android设备(android 4.0.3)完美地工作。 But when I deploy the application on my real android device (android 4.0.3) getElapsedTime() starts with one additional hour and then counts up normally. 但是当我在真正的Android设备(android 4.0.3)上部署应用程序时,getElapsedTime()会再开始一小时,然后正常计数。 So on my real device getElapsedTime() will return "01:00:01" after the activity was started, but it should return "00:00:01". 因此,在我的真实设备上,getElapsedTime()将在活动开始后返回“01:00:01”,但它应返回“00:00:01”。

Do you have any ideas why this happens? 你知道为什么会这样吗?

You should use SystemClock.uptimeMillis() . 您应该使用SystemClock.uptimeMillis()

uptimeMillis() is counted in milliseconds since the system was booted and is guaranteed to be monotonic whereas System.currentTimeMillis() isn't because the user or an application can change it at any time. uptimeMillis()以系统启动后的毫秒数计算,并保证是单调的,而System.currentTimeMillis()则不是因为用户或应用程序可以随时更改它。 Also, usually automatic time synchronization is enabled which can change the time at any time. 此外,通常启用自动时间同步,可以随时更改时间。

You can't use Time to represent a difference between 2 instants. 您不能使用时间来表示2个时刻之间的差异。 In your code, getElapsedTime() returns a time close to 0, which is interpreted as 1970, January 1st. 在您的代码中,getElapsedTime()返回接近0的时间,该时间被解释为1970年1月1日。 I think that the reason why you have a problem is because you don't have the same time zone on your device, hence the origin of time is not midnight. 我认为您遇到问题的原因是因为您的设备上没有相同的时区,因此时间的起源不是午夜。

System.currentTimeMillis() returns milliseconds passed between the device's clock time and the epoch date. System.currentTimeMillis()返回设备的时钟时间和纪元日期之间传递的毫秒数。 That's why it can vary from device to device. 这就是为什么它可能因设备而异。

http://developer.android.com/reference/java/lang/System.html#currentTimeMillis () http://developer.android.com/reference/java/lang/System.html#currentTimeMillis ()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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