How To Get Time From Network In Android
In my app I want to use the Network Time and not the time of device. It is the requirement of my app that time should be correct. I'm trying to get the time from NTS server but lo
Solution 1:
This solution is working for me:
Import in your module gradle this dependency (maybe you already have it):
compile'commons-net:commons-net:3.3'
Here you are a sample getting the local/net time. As you know, you should run it in an Async task as you did with your solution.
publicstaticfinalStringTIME_SERVER="time-a.nist.gov";
publicstaticvoidprintTimes()throws IOException {
NTPUDPClienttimeClient=newNTPUDPClient();
InetAddressinetAddress= InetAddress.getByName(TIME_SERVER);
TimeInfotimeInfo= timeClient.getTime(inetAddress);
//long returnTime = timeInfo.getReturnTime(); //local device timelongreturnTime= timeInfo.getMessage().getTransmitTimeStamp().getTime(); //server timeDatetime=newDate(returnTime);
Log.e("getCurrentNetworkTime", "Time from " + TIME_SERVER + ": " + time);
Log.e("Local time", "Local time");
Log.e("Local time", "Current time: " + newDate(System.currentTimeMillis()));
Log.e("Local time", "Time info: " + newDate(timeInfo.getReturnTime()));
Log.e("Local time", "GetOriginateTimeStamp: " + newDate(timeInfo.getMessage().getOriginateTimeStamp().getTime()));
Log.e("NTP time", "Time from " + TIME_SERVER + ": " + time);
Log.e("Local time", "Time info: " + newDate(timeInfo.getMessage().getReceiveTimeStamp().getTime()));
Log.e("Local time", "GetOriginateTimeStamp: " + newDate(timeInfo.getMessage().getTransmitTimeStamp().getTime()));
}
Summary getting only your net time:
publicstaticlonggetNetworkTime()throws IOException {
NTPUDPClienttimeClient=newNTPUDPClient();
InetAddressinetAddress= InetAddress.getByName(TIME_SERVER);
TimeInfotimeInfo= timeClient.getTime(inetAddress);
return timeInfo.getMessage().getReceiveTimeStamp().getTime();
}
I hope this helps!!
Post a Comment for "How To Get Time From Network In Android"