Reputation: 10619
I'm using NTP from common-net library to synchronize time for my Android app. I'm try to get the delay using this code:
public static final String TIME_SERVER = "time-a.nist.gov";
public static long getCurrentNetworkTime() throws IOException {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); // server time
Log.d("TAG", "delay: " + timeInfo.getDelay() + " time:" + returnTime
+ " local time:" + System.currentTimeMillis());
return returnTime;
}
But I get null
for timeInfo.getDelay()
. Based on the documentation of this method, it may not available:
/**
* Get round-trip network delay. If null then could not compute the delay.
*
* @return Long or null if delay not available.
*/
public Long getDelay()
{
return _delay;
}
Why could it not compute the delay?
Upvotes: 1
Views: 175
Reputation: 10619
My problem solved by overriding NTPUDPClient, Copy code of this class and change parameter for details in TimeInfo
:
TimeInfo info = new TimeInfo(recMessage, returnTime, true);
This is MyNTPUDPClient
class, use it instead of NTPUDPClient
:
public final class MyNTPUDPClient extends DatagramSocketClient {
public static final int DEFAULT_PORT = 123;
private int _version = NtpV3Packet.VERSION_3;
public TimeInfo getTime(InetAddress host, int port) throws IOException {
// if not connected then open to next available UDP port
if (!isOpen()) {
open();
}
NtpV3Packet message = new NtpV3Impl();
message.setMode(NtpV3Packet.MODE_CLIENT);
message.setVersion(_version);
DatagramPacket sendPacket = message.getDatagramPacket();
sendPacket.setAddress(host);
sendPacket.setPort(port);
NtpV3Packet recMessage = new NtpV3Impl();
DatagramPacket receivePacket = recMessage.getDatagramPacket();
TimeStamp now = TimeStamp.getCurrentTime();
message.setTransmitTime(now);
_socket_.send(sendPacket);
_socket_.receive(receivePacket);
long returnTime = System.currentTimeMillis();
TimeInfo info = new TimeInfo(recMessage, returnTime, true);
return info;
}
public TimeInfo getTime(InetAddress host) throws IOException {
return getTime(host, NtpV3Packet.NTP_PORT);
}
public int getVersion() {
return _version;
}
public void setVersion(int version) {
_version = version;
}
}
Upvotes: 1