Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

I use System.currentTimeMillis() to save the time a user starts an activity.

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. 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). 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. So on my real device getElapsedTime() will return "01:00:01" after the activity was started, but it should return "00:00:01".

Do you have any ideas why this happens?

like image 304
Jens Ehrlich Avatar asked Aug 14 '12 14:08

Jens Ehrlich


1 Answers

You should use 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. Also, usually automatic time synchronization is enabled which can change the time at any time.

like image 194
tolgap Avatar answered Oct 03 '22 04:10

tolgap