Reputation: 43
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?
Upvotes: 3
Views: 3854
Reputation: 1996
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
Upvotes: 5
Reputation: 1398
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.
Upvotes: 1