【问题标题】:Is android epoch time the same in all devicesandroid epoch time 在所有设备中都相同吗
【发布时间】: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上获取纪元时间戳的最佳方法是什么?提前致谢。

【问题讨论】:

  • 不能保证所有安卓设备的时间都是正确的,因为它们的所有时钟都可能不同。正如您所发现的,准确的时间同步是一个相当困难的问题。

标签: android epoch


【解决方案1】:

纪元时间取决于设备的时间同步,因此两个设备可能有不同的值。

此外,从 REST 端点获取时间信息似乎不是最有效的方式,因为除了一般的网络延迟之外,您还会在 API 端点上引入潜在的延迟。

由于 Android 设备使用各种 NTP 服务器来获取时间,为什么不从设备本身获取时间信息并转换为纪元?设备本身已经获得更新的时间信息,因此您不妨使用它。

如果你想从设备本身获取当前的纪元值,你可以使用[currentTimeMillis()][1]

System.currentTimeMillis()/1000

这会返回毫秒数,因此要获得一个以秒为单位的纪元值,只需除以 1000。

【讨论】:

  • 你能指导我使用获取时间戳的api吗?
  • @JeanCarlosHenriquez 我已经更新了答案,希望对您有所帮助。
  • 我仍然在生产环境中受苦, ***** 设备的时间完全混乱。不要相信安卓设备的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多