Measure long elapsed time (with reboots) on Android
Asked Answered
B

1

6

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.

Buoy answered 10/12, 2013 at 20:0 Comment(3)
I don't think there's a better way. At a minimum you will have to listen to two system broadcasts, BOOT_COMPLETED and ACTION_SHUTDOWN. You could optimize the remaining stuff around these two. But this is the minimum you have to do, i believe.Manpower
#3523942 that should be the time behind those two. Android devices will self-adjust the System.currentTimeMillisec() based on external time sources (possibly NTP, GSM, GPS, ?) - no user intervention required and probably at boot (i.e. before BOOT_COMPLETED). You could use an external time service as well but that needs network access.Phila
A user who is willing to override the platform clocks to defeat you is quite likely a user who can just intercept/patch whatever system calls you are using to read them anyway.Dishcloth
F
1

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.

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

Forked answered 10/12, 2013 at 20:19 Comment(2)
Your idea is for sure correct, but I was searching for something that doesn't add any overhead, so using NTP is not a suitable solution for me.Buoy
As far as I am aware, there's no solution on-phone that is guaranteed to be the correct time unless you can somehow get a timestamp from the carrier. As far as I see, that's not exposed. As you may know the radio is basically a separate operating system.Forked

© 2022 - 2024 — McMap. All rights reserved.