Android 通过NTP服务器自动获取时间的方法


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

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

  1. import java.net.DatagramPacket;  
  2. import java.net.DatagramSocket;  
  3. import java.net.InetAddress;  
  4. import java.util.Date;  
  5.    
  6. public class GetTime {  
  7.    
  8.     public static void main(String[] args) {  
  9.         SntpClient client = new SntpClient();  
  10.         if (client.requestTime("pool.ntp.org"30000)) {  
  11.             long now = client.getNtpTime() + System.nanoTime() / 1000  
  12.                     - client.getNtpTimeReference();  
  13.             Date current = new Date(now);  
  14.             System.out.println(current.toString());  
  15.         }  
  16.    
  17.     }  
  18. }  
  19.    
  20. class SntpClient {  
  21.    
  22.     private static final int ORIGINATE_TIME_OFFSET = 24;  
  23.     private static final int RECEIVE_TIME_OFFSET = 32;  
  24.     private static final int TRANSMIT_TIME_OFFSET = 40;  
  25.     private static final int NTP_PACKET_SIZE = 48;  
  26.    
  27.     private static final int NTP_PORT = 123;  
  28.     private static final int NTP_MODE_CLIENT = 3;  
  29.     private static final int NTP_VERSION = 3;  
  30.    
  31.     // Number of seconds between Jan 1, 1900 and Jan 1, 1970   
  32.     // 70 years plus 17 leap days   
  33.     private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;  
  34.    
  35.     // system time computed from NTP server response   
  36.     private long mNtpTime;  
  37.    
  38.     // value of SystemClock.elapsedRealtime() corresponding to mNtpTime   
  39.     private long mNtpTimeReference;  
  40.    
  41.     // round trip time in milliseconds   
  42.     private long mRoundTripTime;  
  43.    
  44.     /** 
  45.      * Sends an SNTP request to the given host and processes the response. 
  46.      * 
  47.      * @param host 
  48.      *            host name of the server. 
  49.      * @param timeout 
  50.      *            network timeout in milliseconds. 
  51.      * @return true if the transaction was successful. 
  52.      */  
  53.     public boolean requestTime(String host, int timeout) {  
  54.         try {  
  55.             DatagramSocket socket = new DatagramSocket();  
  56.             socket.setSoTimeout(timeout);  
  57.             InetAddress address = InetAddress.getByName(host);  
  58.             byte[] buffer = new byte[NTP_PACKET_SIZE];  
  59.             DatagramPacket request = new DatagramPacket(buffer, buffer.length,  
  60.                     address, NTP_PORT);  
  61.    
  62.             // set mode = 3 (client) and version = 3   
  63.             // mode is in low 3 bits of first byte   
  64.             // version is in bits 3-5 of first byte   
  65.             buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);  
  66.    
  67.             // get current time and write it to the request packet   
  68.             long requestTime = System.currentTimeMillis();  
  69.             long requestTicks = System.nanoTime() / 1000;  
  70.             writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);  
  71.    
  72.             socket.send(request);  
  73.    
  74.             // read the response   
  75.             DatagramPacket response = new DatagramPacket(buffer, buffer.length);  
  76.             socket.receive(response);  
  77.             long responseTicks = System.nanoTime() / 1000;  
  78.             long responseTime = requestTime + (responseTicks - requestTicks);  
  79.             socket.close();  
  80.    
  81.             // extract the results   
  82.             long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);  
  83.             long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);  
  84.             long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);  
  85.             long roundTripTime = responseTicks - requestTicks  
  86.                     - (transmitTime - receiveTime);  
  87.             // receiveTime = originateTime + transit + skew   
  88.             // responseTime = transmitTime + transit - skew   
  89.             // clockOffset = ((receiveTime - originateTime) + (transmitTime -   
  90.             // responseTime))/2   
  91.             // = ((originateTime + transit + skew - originateTime) +   
  92.             // (transmitTime - (transmitTime + transit - skew)))/2   
  93.             // = ((transit + skew) + (transmitTime - transmitTime - transit +   
  94.             // skew))/2   
  95.             // = (transit + skew - transit + skew)/2   
  96.             // = (2 * skew)/2 = skew   
  97.             long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;  
  98.             // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime +   
  99.             // " ms");   
  100.             // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset +   
  101.             // " ms");   
  102.    
  103.             // save our results - use the times on this side of the network   
  104.             // latency   
  105.             // (response rather than request time)   
  106.             mNtpTime = responseTime + clockOffset;  
  107.             mNtpTimeReference = responseTicks;  
  108.             mRoundTripTime = roundTripTime;  
  109.         } catch (Exception e) {  
  110.    
  111.             return false;  
  112.         }  
  113.    
  114.         return true;  
  115.     }  
  116.    
  117.     /** 
  118.      * Returns the time computed from the NTP transaction. 
  119.      * 
  120.      * @return time value computed from NTP server response. 
  121.      */  
  122.     public long getNtpTime() {  
  123.         return mNtpTime;  
  124.     }  
  125.    
  126.     /** 
  127.      * Returns the reference clock value (value of 
  128.      * SystemClock.elapsedRealtime()) corresponding to the NTP time. 
  129.      * 
  130.      * @return reference clock corresponding to the NTP time. 
  131.      */  
  132.     public long getNtpTimeReference() {  
  133.         return mNtpTimeReference;  
  134.     }  
  135.    
  136.     /** 
  137.      * Returns the round trip time of the NTP transaction 
  138.      * 
  139.      * @return round trip time in milliseconds. 
  140.      */  
  141.     public long getRoundTripTime() {  
  142.         return mRoundTripTime;  
  143.     }  
  144.    
  145.     /** 
  146.      * Reads an unsigned 32 bit big endian number from the given offset in the 
  147.      * buffer. 
  148.      */  
  149.     private long read32(byte[] buffer, int offset) {  
  150.         byte b0 = buffer[offset];  
  151.         byte b1 = buffer[offset + 1];  
  152.         byte b2 = buffer[offset + 2];  
  153.         byte b3 = buffer[offset + 3];  
  154.    
  155.         // convert signed bytes to unsigned values   
  156.         int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);  
  157.         int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);  
  158.         int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);  
  159.         int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);  
  160.    
  161.         return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << <img class="wp-smiley" alt="8)" src="http://www.imobilebbs.com/wordpress/wp-includes/images/smilies/icon_cool.gif">  
  162.                 + (long) i3;  
  163.     }  
  164.    
  165.     /** 
  166.      * Reads the NTP time stamp at the given offset in the buffer and returns it 
  167.      * as a system time (milliseconds since January 1, 1970). 
  168.      */  
  169.     private long readTimeStamp(byte[] buffer, int offset) {  
  170.         long seconds = read32(buffer, offset);  
  171.         long fraction = read32(buffer, offset + 4);  
  172.         return ((seconds - OFFSET_1900_TO_1970) * 1000)  
  173.                 + ((fraction * 1000L) / 0x100000000L);  
  174.     }  
  175.    
  176.     /** 
  177.      * Writes system time (milliseconds since January 1, 1970) as an NTP time 
  178.      * stamp at the given offset in the buffer. 
  179.      */  
  180.     private void writeTimeStamp(byte[] buffer, int offset, long time) {  
  181.         long seconds = time / 1000L;  
  182.         long milliseconds = time - seconds * 1000L;  
  183.         seconds += OFFSET_1900_TO_1970;  
  184.    
  185.         // write seconds in big endian format   
  186.         buffer[offset++] = (byte) (seconds >> 24);  
  187.         buffer[offset++] = (byte) (seconds >> 16);  
  188.         buffer[offset++] = (byte) (seconds >> 8);  
  189.         buffer[offset++] = (byte) (seconds >> 0);  
  190.    
  191.         long fraction = milliseconds * 0x100000000L / 1000L;  
  192.         // write fraction in big endian format   
  193.         buffer[offset++] = (byte) (fraction >> 24);  
  194.         buffer[offset++] = (byte) (fraction >> 16);  
  195.         buffer[offset++] = (byte) (fraction >> 8);  
  196.         // low order bits should be random data   
  197.         buffer[offset++] = (byte) (Math.random() * 255.0);  
  198.     }  
  199. }  

运行这个Java应用,可以得到当前GMT时间,如:Sat Jun 16 10:52:19 BST 2012

更多Android相关信息见Android 专题页面 http://www.bkjia.com/topicnews.aspx?tid=11

相关内容