我想从Google NTP服务器获得当前的GMT时间。如何使用asynctask修改代码?NTP服务器是否给出零值?
我知道以下代码中存在一些问题。
SntpClient client = new SntpClient();
if (client.requestTime("time.google.com")) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime() -
client.getNtpTimeReference();
Date current = new Date(now);
Log.i("NTP tag", current.toString());
}
我正在使用此代码从Google那里获得时间,您应该尝试一下。
我的代码要做的是,它转到google.com
页面并检索时间,之后我将时间在 "EEE, d MMM yyyy HH:mm:ss z"
中获得了这种格式,然后我将其转换为秒以上传到我的服务器。
您需要声明字符串数据 private String mDateStr;
。
protected Void doInBackground(Void... voids) {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z",Locale.ENGLISH);
mDateStr = response.getFirstHeader("Date").getValue();
Date startDate = df.parse(mDateStr);
mDateStr = String.valueOf(startDate.getTime()/1000);
//Here I do something with the Date String
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (IOException e) {
Log.d("Response", e.getMessage());
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
.... it continues, thsi is an asynctask
您必须具有NTP服务器库。将代码放入尝试方法中。希望它能起作用。:)