Reputation: 33
Dear android developers,
I'm trying to implement the sntpclient class in my application but it didn't work.
in my code I have the following lines:
public void onClickBtn(View v)
{
SntpClient client = new SntpClient();
if (client.requestTime("pool.ntp.org", 10)) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
Toast.makeText(this, "Offset: " + now, Toast.LENGTH_LONG).show();
}
}
I really don't know what the meaning of network timeout is in this case.
It would be great, when someone has any idea or tip for me.
Thanks in advance!
Upvotes: 3
Views: 10741
Reputation: 7033
Check that your manifest has this one:
<uses-permission android:name="android.permission.INTERNET" />
Upvotes: 1
Reputation:
You can use this Full sample:
class getCurrentNetworkTime extends AsyncTask<String, Void, Boolean> {
private Exception exception;
protected Boolean doInBackground(String... urls) {
NTPUDPClient timeClient = new NTPUDPClient();
timeClient.setDefaultTimeout(3000);
InetAddress inetAddress = null;
boolean is_locale_date = false;
try {
inetAddress = InetAddress.getByName(G.TIME_SERVER);
TimeInfo timeInfo = null;
timeInfo = timeClient.getTime(inetAddress);
long localTime = timeInfo.getReturnTime();
long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
if (new Date(localTime) != new Date(serverTime))
is_locale_date = true;
} catch (UnknownHostException e) {
e.printStackTrace();
Log.e("UnknownHostException: ", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.e("IOException: ", e.getMessage());
}
return is_locale_date;
}
protected void onPostExecute(boolean local_date) {
if(!local_date) {
Log.e("Check ", "dates not equal" + local_date);
}
}
}
How to use:
new getCurrentNetworkTime().execute();
Upvotes: 3
Reputation: 41
You should put it in AsyncTask like this :
class GetNTPAsynctask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
private SntpClient sntpClient = new SntpClient();
return sntpClient.requestTime("pool.ntp.org", 30000);
}
}
Timeout: network timeout in milliseconds. So i use 30000 mean 30 seconds.
Upvotes: 4