I have an Android application sending via TCP sockets to another Android phone or PC, I want to synch the clock of sender and receiver clocks. I have tried SystemClock.setCurrentTimeMillis on android but it's not working even using the permission android.permission.SET_TIME. is there another way?
2 Answers
Unfortunately you can't change the time of your android phone from code,as you don't have the privilege of setting android.permission.SET_TIME.You could do it only on a rooted phone.
So why not let your both application update from a trusted source like internet time. Maybe use android sntp client
//Sample usage:
SntpClient client = new SntpClient();
if (client.requestTime("time.nist.gov")) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
}
OR what you can do is: send the current time on your phone to the pc and set the time of your pc,via what program you are using to recieve data. Also take a look here: set mobile time and date
-
Thanks sokie for your response, the return value of client.requestTime("time.foo.com",30000) is false? do you think that i should use another server or what is the issue here? – user1426149 Oct 10 '12 at 15:33
-
time.foo.com was an example,nonexistant website,i apologize if that was misleading.You should find a list of convenient servers [here](http://tf.nist.gov/tf-cgi/servers.cgi) or using directly time.nist.gov that distributes the load across the server based on your location and ip – sokie Oct 10 '12 at 15:47
-
2Great.Thanks sokie, now it works!! The problem was that the Sntpclient class do the networking on the main thread so i was getting exception since i have android 4.0.3. I have change the class and put the time request throw UDP socket in a separate thread to get red of the exception! – user1426149 Oct 10 '12 at 16:17
I don't know your application but, to synchronize clocks like that seems to be a little bit of a patch. I would suggest that you use NTP (network time protocol) to do so. Android as well as Windows, MAC and Linux machine can do that. Your android machine will do that from the cell tower or from the WIFI. I ported a cell modem for Android lately and I looked extensively at the logs and I can tell you that the time synchronisation happen very often, every time the network connects and several times a day. It's pretty accurate even when switching network source (cell or wifi). It's simple and you will not have to write any code, just configure it to enable it.
The result is the PC and Android time set from an official network source.

- 1,378
- 6
- 18
- 29