当前位置:   article > 正文

Android 通过NTP服务器自动获取时间的方法_android.pool.ntp.org

android.pool.ntp.org

        对于手机,如果有SIM卡支持的话,在设置时间时可以通过选择自动从网络获取时间来取得当地的时间和时区。

        但如果手机没有SIM卡,此时如果有Wifi链接,手机依然可以通过网络自动获取时间(时区此时需要手动设置)。 查看Android源码,在android.net 中有 SntpClient类,可以通过访问NTP服务器来取得当前的GMT时间。pool.ntp.org为最常用的一个NTF服务器。修改SntpClient代码,你也可以在自己的应用(包括非Android应用)中通过NTP服务器来取得当前GMT时间,代码如下:

  1. public class SntpClient{
  2. private static final int ORIGINATE_TIME_OFFSET = 24;
  3. private static final int RECEIVE_TIME_OFFSET = 32;
  4. private static final int TRANSMIT_TIME_OFFSET = 40;
  5. private static final int NTP_PACKET_SIZE = 48;
  6. private static final int NTP_PORT = 123;
  7. private static final int NTP_MODE_CLIENT = 3;
  8. private static final int NTP_VERSION = 3;
  9. // Number of seconds between Jan 1, 1900 and Jan 1, 1970
  10. // 70 years plus 17 leap days
  11. private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
  12. // system time computed from NTP server response
  13. private long mNtpTime;
  14. // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
  15. private long mNtpTimeReference;
  16. // round trip time in milliseconds
  17. private long mRoundTripTime;
  18. public boolean requestTime(String host, int timeout) {
  19. try {
  20. DatagramSocket socket = new DatagramSocket();
  21. socket.setSoTimeout(timeout);
  22. InetAddress address = InetAddress.getByName(host);
  23. byte[] buffer = new byte[NTP_PACKET_SIZE];
  24. DatagramPacket request = new DatagramPacket(buffer, buffer.length,
  25. address, NTP_PORT);
  26. // set mode = 3 (client) and version = 3
  27. // mode is in low 3 bits of first byte
  28. // version is in bits 3-5 of first byte
  29. buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
  30. // get current time and write it to the request packet
  31. long requestTime = System.currentTimeMillis();
  32. long requestTicks = System.nanoTime() / 1000;
  33. writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
  34. socket.send(request);
  35. // read the response
  36. DatagramPacket response = new DatagramPacket(buffer, buffer.length);
  37. socket.receive(response);
  38. long responseTicks = System.nanoTime() / 1000;
  39. long responseTime = requestTime + (responseTicks - requestTicks);
  40. socket.close();
  41. // extract the results
  42. long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
  43. long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
  44. long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
  45. long roundTripTime = responseTicks - requestTicks
  46. - (transmitTime - receiveTime);
  47. // receiveTime = originateTime + transit + skew
  48. // responseTime = transmitTime + transit - skew
  49. // clockOffset = ((receiveTime - originateTime) + (transmitTime -
  50. // responseTime))/2
  51. // = ((originateTime + transit + skew - originateTime) +
  52. // (transmitTime - (transmitTime + transit - skew)))/2
  53. // = ((transit + skew) + (transmitTime - transmitTime - transit +
  54. // skew))/2
  55. // = (transit + skew - transit + skew)/2
  56. // = (2 * skew)/2 = skew
  57. long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
  58. // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime +
  59. // " ms");
  60. // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset +
  61. // " ms");
  62. // save our results - use the times on this side of the network
  63. // latency
  64. // (response rather than request time)
  65. mNtpTime = responseTime + clockOffset;
  66. mNtpTimeReference = responseTicks;
  67. mRoundTripTime = roundTripTime;
  68. } catch (Exception e) {
  69. LogUtil.e("error"+e.getMessage());
  70. return false;
  71. }
  72. return true;
  73. }
  74. public long getNtpTime() {
  75. return mNtpTime;
  76. }
  77. public long getNtpTimeReference() {
  78. return mNtpTimeReference;
  79. }
  80. public long getRoundTripTime() {
  81. return mRoundTripTime;
  82. }
  83. private long read32(byte[] buffer, int offset) {
  84. byte b0 = buffer[offset];
  85. byte b1 = buffer[offset + 1];
  86. byte b2 = buffer[offset + 2];
  87. byte b3 = buffer[offset + 3];
  88. // convert signed bytes to unsigned values
  89. int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
  90. int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
  91. int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
  92. int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
  93. return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;
  94. }
  95. private long readTimeStamp(byte[] buffer, int offset) {
  96. long seconds = read32(buffer, offset);
  97. long fraction = read32(buffer, offset + 4);
  98. return ((seconds - OFFSET_1900_TO_1970) * 1000)
  99. + ((fraction * 1000L) / 0x100000000L);
  100. }
  101. private void writeTimeStamp(byte[] buffer, int offset, long time) {
  102. long seconds = time / 1000L;
  103. long milliseconds = time - seconds * 1000L;
  104. seconds += OFFSET_1900_TO_1970;
  105. // write seconds in big endian format
  106. buffer[offset++] = (byte) (seconds >> 24);
  107. buffer[offset++] = (byte) (seconds >> 16);
  108. buffer[offset++] = (byte) (seconds >> 8);
  109. buffer[offset++] = (byte) (seconds >> 0);
  110. long fraction = milliseconds * 0x100000000L / 1000L;
  111. // write fraction in big endian format
  112. buffer[offset++] = (byte) (fraction >> 24);
  113. buffer[offset++] = (byte) (fraction >> 16);
  114. buffer[offset++] = (byte) (fraction >> 8);
  115. // low order bits should be random data
  116. buffer[offset++] = (byte) (Math.random() * 255.0);
  117. }
  118. }
  1. SntpClient client = new SntpClient();
  2. if (client.requestTime("pool.ntp.org", 10000)) {
  3. long now = client.getNtpTime() + System.nanoTime() / 1000 - client.getNtpTimeReference();
  4. Date current = new Date(now);// GMT TIME
  5. //current.s
  6. //System.out.println(current.toString());
  7. LogUtil.i("NtpTime " + current.toString());
  8. }

 

调用以上方法,可以得到当前GMT时间。
————————————————

参考连接:https://blog.csdn.net/qq_43685118/article/details/87090487

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/808252
推荐阅读
相关标签
  

闽ICP备14008679号