您可以使用此完整示例:
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);
}
}
}
如何使用:
new getCurrentNetworkTime().execute();