【发布时间】:2016-07-06 10:12:03
【问题描述】:
我制作了一个应用程序,可以根据纪元时间跨设备同步数据数据。我目前通过使用 httpurlconnection 在服务器上使用 rest api 来获取这个纪元时间,如下所示:
public static String getTime(String time){
InputStream is = null;
BufferedReader bufferedReader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(SERVERURL);
urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
return jsonObject.getString("time");
}
catch(JSONException e){
Log.d("getTime","json object creation failed");
}
catch(IOException e){
Log.d("getTime", "couldn't get time from server");
}
finally {
try {
if(urlConnection != null){
urlConnection.disconnect();
}
if(bufferedReader != null) {
bufferedReader.close();
}
if(is != null){
is.close();
}
}
catch(IOException e){
Log.d("async getGameName","io exception closing buffer");
}
}
return time;
}
以便所有设备都从一个已知来源获取时间戳。此方法在后台服务中运行,因此它不会减慢应用程序的响应速度,但它不会产生良好的用户体验,因为我需要此时间戳来向用户显示信息并且 http 请求需要很长时间。有时长达一分钟,因为这取决于网络连接,所以我想问一下所有android设备的本地纪元时间是否相同,以及在android上获取纪元时间戳的最佳方法是什么?提前致谢。
【问题讨论】:
-
不能保证所有安卓设备的时间都是正确的,因为它们的所有时钟都可能不同。正如您所发现的,准确的时间同步是一个相当困难的问题。