Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Get current time without dependency on device's clock

I've noticed that System.currentTimeMillis() time is device dependent. If I change the time on the device's clock, this method will return a different answer.

For example: If the real time now is 10:00, and I change the clock on my device to 9:30, then System.currentTimeMillis() will return the 9:30 time (in milliseconds..).

I've also tried this answer and some other answers, but didn't find anything useful. I should state that my app works mostly offline. Is there a way to get the real current time (device independent) without external API?

like image 264
Aviv Ben Shabat Avatar asked Nov 17 '14 09:11

Aviv Ben Shabat


People also ask

Is there a way to detect when the user has changed the clock time on their device?

Yes, there is. The ACTION_TIME_CHANGED Intent is broadcast when the device time is changed, and you can have a method which will trigger when this Intent is detected.

How does Android automatic time work?

Automatic time detection receives time suggestions from various sources, selects the best option, and then sets the system clock in Android to match.


2 Answers

If it were not for the 'offline' part, I'd have suggested to use a time server, but given that your app is offline most of the time that might not be a good solution.

If you don't need the actual time but just a time that cannot be messed with, you can use SystemClock.elapsedRealtime() which gives you the time since the device last booted.

You could also combine time server and SystemClock.elapsedRealtime(): Fetch the time from timer server once (e.g. after bootup) and from then on add elapsedRealtime() to that initial value (minus the elapsedRealtime value of when you get the timerserver value).

like image 195
Ridcully Avatar answered Sep 22 '22 13:09

Ridcully


If you use the GPS location provider, getTime() will return the UTC time derived from the GPS signal, rather than the device time. The GPS location provider can work offline - but it will be much slower to obtain a fix compared to being online when it can access the A-GPS info.

like image 26
zmarties Avatar answered Sep 21 '22 13:09

zmarties