Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure long elapsed time (with reboots) on Android

I need to measure long elapsed time on Android and there may be device reboots in between.

From what I've understand, System.nanoTime() is resetted every time the device reboot, and System.currentTimeMillis() is unreliable because user can change it.

The only solution that I came up with is to listen to ACTION_SHUTDOWN and BOOT_COMPLETED, use System.currentTimeMillisec() to calculate the elapsed time (user can't change clock time while the device is off, hopefully :) ) and add it to the last System.nanoTime() I had before shutting down.

I honestly don't like this solution because it's very expensive (I need to listen to 2 broadcast events) and inaccurate, but I couldn't figure out any other way to do this.

Any ideas? Also a native solution would be good for me.

like image 626
dmarcato Avatar asked Nov 11 '22 16:11

dmarcato


1 Answers

You can get around the user changing time by using an internet time server to get the times when you check. There are a couple of ways to do this.

  • Get it via NTP server
    • How to get current time from internet in android
    • How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?
  • Get it via HTTP header
    • http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses ( see Date header )

If you simply persist this value then the user can do nothing to mess up your calculation.

like image 70
David S. Avatar answered Nov 14 '22 21:11

David S.