Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the most accurate time with Android?

I really don't think this question is a duplicate.
Most answers to similar questions say to use System.currentTimeMillis() as the most accurate time, but I've noticed that two Android devices side-by-side may be off up to 5 seconds or more from each other or (more importantly) the real time, and I believe currentTimeMillis() will reflect that difference.

So what I'm really looking for is a comprehensive solution to get the most accurate time possible in a given moment.
For example, it would start with the GPS and, if that's not available or there's no signal, fall back to SNTP, or if that doesn't work ask Android to refresh its wall clock with via its own SNTP or carrier NITZ.

My goal is accuracy within .1 seconds.
Is that possible?
Thanks.

like image 757
ScottyB Avatar asked Feb 13 '14 16:02

ScottyB


1 Answers

Is that possible?

That depends upon your definition of "that".

So, let's examine the rest of your material first...

it would start with the GPS

GPS times are not especially accurate depending on hardware. I think you'd also need to use an NmeaListener to try to parse the time data out of the NMEA sentences directly, as AFAIK getTime() on Location is the system time, not some GPS time. Also, bear in mind that GPS access is not universal (user may have disabled it specifically, user might have put device in airplane mode, user may be in a large building with no available GPS signals).

fall back to SNTP

There are plenty of SNTP client code bits out there that you can try. Bear in mind that Internet connectivity is not universal (device may be WiFi-only outside of any known access point, user might have put device in airplane mode, device may be mobile-data-capable but have no signal strength in current location).

if that doesn't work ask Android to refresh its wall clock with via its own SNTP or carrier NITZ

It's conceivable that a rooted device might be able to do this, somehow, but there's nothing in the Android SDK for ordinary apps to force such a refresh. Bear in mind that connectivity is not universal (see roster in previous paragraph).

So, going back to:

Is that possible?

If "that" is a solution that is guaranteed to work in all cases, then no, it is not possible, as you are not guaranteed any ability to communicate with any time source.

If "that" is a solution that is guaranteed to work if the device has Internet connectivity, then you'd need to ask your SNTP client library implementers if they can achieve 100ms accuracy. SNTP is the only one of your strategies that is completely under your control, other than the connectivity issue, as GPS may not be accurate and NITZ isn't something you manage yourself.

like image 195
CommonsWare Avatar answered Sep 28 '22 15:09

CommonsWare