MTK NTP和NITZ更新時間的問題

NITZ(Network Identity and Time Zone,網絡標識和時區),是一種用於自動配置本地的時間和日期的機制,同時也經過無線網向移動設備提供運營商信息。NITZ是自從PHASE 2+ RELEASE 96 的GSM中的可選功能,常常被用來自動更新移動電話的系統時鐘。NITZ須要運營商網絡支持(經過CS網絡),目前國內電信、移動都支持NITZ方式更新時間日期,而聯通目前不支持。java

一。配置服務器端:android

 

那麼好比在英國的話就能夠選擇下面兩個服務器 服務器

0.uk.pool.ntp.org 
1.uk.pool.ntp.org 

它的通常格式都是number.country.pool.ntp.org網絡

中國的ntp服務器地址:app

server 133.100.11.8 prefer 
server 210.72.145.44 
server 203.117.180.36 
server 131.107.1.10 
server time.asia.apple.com 
server 64.236.96.53 
server 130.149.17.21 
server 66.92.68.246 
server www.freebsd.org 
server 18.145.0.30 
server clock.via.net 
server 137.92.140.80 
server 133.100.9.2 
server 128.118.46.3 
server ntp.nasa.gov 
server 129.7.1.66 
server ntp-sop.inria.fr

server (國家授時中心服務器IP地址)

 

二。修改默認NTP配置less

1.經過SntpClient.java來封裝請求。socket

frameworks/base/core/java/android/net/SntpClient.javaide

public boolean requestTime(String host, int timeout) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            InetAddress address = InetAddress.getByName(host);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
 
            // set mode = 3 (client) and version = 3
            // mode is in low 3 bits of first byte
            // version is in bits 3-5 of first byte
            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
 
            // get current time and write it to the request packet
            long requestTime = System.currentTimeMillis();
            long requestTicks = SystemClock.elapsedRealtime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
 
            socket.send(request);
 
            // read the response
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            long responseTicks = SystemClock.elapsedRealtime();
            long responseTime = requestTime + (responseTicks - requestTicks);
 
            // extract the results
            long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
            // receiveTime = originateTime + transit + skew
            // responseTime = transmitTime + transit - skew
            // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
            //             = ((originateTime + transit + skew - originateTime) +
            //                (transmitTime - (transmitTime + transit - skew)))/2
            //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
            //             = (transit + skew - transit + skew)/2
            //             = (2 * skew)/2 = skew
            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
            // if (false) Log.d(TAG, round trip:  + roundTripTime +  ms);
            // if (false) Log.d(TAG, clock offset:  + clockOffset +  ms);
 
            // save our results - use the times on this side of the network latency
            // (response rather than request time)
            mNtpTime = responseTime + clockOffset;
            mNtpTimeReference = responseTicks;
            mRoundTripTime = roundTripTime;
        } catch (Exception e) {
            if (false) Log.d(TAG, request time failed:  + e);
            return false;
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
 
        return true;
    }

2.發起同步的,這個方法的主角爲:NtpTrustedTime.java  在該類中經過forceRefresh方法來更新獲取服務器時間。fetch

frameworks/base/core/java/android/util/NtpTrustedTime.javathis

public boolean forceRefresh() {
        if (mServer == null) {
            // missing server, so no trusted time available
            return false;
        }
 
        if (LOGD) Log.d(TAG, forceRefresh() from cache miss);
        final SntpClient client = new SntpClient();
        if (client.requestTime(mServer, (int) mTimeout)) {
            mHasCache = true;
            mCachedNtpTime = client.getNtpTime();
            mCachedNtpElapsedRealtime = client.getNtpTimeReference();
            mCachedNtpCertainty = client.getRoundTripTime() / 2;
            return true;
        } else {
            return false;
        }
    }

3.時間同步請求處理邏輯。在onPollNetworkTime方法中進行同步處理。

/frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java

private void onPollNetworkTime(int event) {
//一、是否勾選自動同步時間配置
        // If Automatic time is not set, don't bother.
        if (!isAutomaticTimeRequested()) return;
//二、mNitzTimeSetTime 來自Moderm,若是當前時間剛經過moderm更新不久,則不進行時間同步。
        final long refTime = SystemClock.elapsedRealtime();
        // If NITZ time was received less than mPollingIntervalMs time ago,
        // no need to sync to NTP.
        if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < mPollingIntervalMs) {
            resetAlarm(mPollingIntervalMs);
            return;
        }
        //三、若是機器剛啓動,或者機器運行時間大於mPollingIntervalMs,即10天,或者設置等發起的主動更新時間請求,則發起網絡時間同步請求。不然,10天后再進行時間同步。
        final long currentTime = System.currentTimeMillis();
        if (DBG) Log.d(TAG, System time =  + currentTime);
        // Get the NTP time
        if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + mPollingIntervalMs
                || event == EVENT_AUTO_TIME_CHANGED) {
            if (DBG) Log.d(TAG, Before Ntp fetch);
//3.一、是否含有時間緩衝,如無,發起時間同步,
            // force refresh NTP cache when outdated
            if (mTime.getCacheAge() >= mPollingIntervalMs) {
                //LEUI-START [BUG][MOBILEP-6067] [System time sync added
                //mTime.forceRefresh();
                int index = mTryAgainCounter % mNtpServers.size();
                if (DBG) Log.d(TAG, mTryAgainCounter =  + mTryAgainCounter + ;mNtpServers.size() =  + mNtpServers.size() + ;index =  + index + ;mNtpServers =  + mNtpServers.get(index));
                //3.1.一、遍歷時間服務器,發起時間同步
                if (mTime instanceof NtpTrustedTime)
                {
                    ((NtpTrustedTime) mTime).setServer(mNtpServers.get(index));
                    mTime.forceRefresh();
                    ((NtpTrustedTime) mTime).setServer(mDefaultServer);
                }
                else
                {
                    mTime.forceRefresh();
                }
                //LEUI-END [BUG][MOBILEP-6067] [System time sync added
            }
//3.二、獲取最新同步的時間緩衝數據,如無,則再次發起時間同步,間隔時間爲mPollingIntervalShorterMs,即30秒。
            // only update when NTP time is fresh
            if (mTime.getCacheAge() < mPollingIntervalMs) {
                final long ntp = mTime.currentTimeMillis();
                mTryAgainCounter = 0;
                // If the clock is more than N seconds off or this is the first time it's been
                // fetched since boot, set the current time.
                //3.2.一、若是開機第一次同步或者最新時間與當前時間差異超過mTimeErrorThresholdMs即25秒,則進行時間設定。不然認定新同步時間與當前時間差異不大,不覆蓋當前時間。
                if (Math.abs(ntp - currentTime) > mTimeErrorThresholdMs
                        || mLastNtpFetchTime == NOT_SET) {
                    // Set the system time
                    if (DBG && mLastNtpFetchTime == NOT_SET
                            && Math.abs(ntp - currentTime) <= mTimeErrorThresholdMs) {
                        Log.d(TAG, For initial setup, rtc =  + currentTime);
                    }
                    if (DBG) Log.d(TAG, Ntp time to be set =  + ntp);
                    // Make sure we don't overflow, since it's going to be converted to an int
                    //3.2.二、設定同步時間
                    if (ntp / 1000 < Integer.MAX_VALUE) {
                        SystemClock.setCurrentTimeMillis(ntp);
                    }
                } else {
                    if (DBG) Log.d(TAG, Ntp time is close enough =  + ntp);
                }
                mLastNtpFetchTime = SystemClock.elapsedRealtime();
            } else {
                // Try again shortly
                //3.3 若是不大於最大同步次數,30秒後進行時間同步,不然,10天后更新。
                mTryAgainCounter++;
                if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {
                    resetAlarm(mPollingIntervalShorterMs);
                } else {
                    // Try much later
                    mTryAgainCounter = 0;
                    resetAlarm(mPollingIntervalMs);
                }
                return;
            }
        }
        //四、若是剛更新時間不久,則10天后再發起時間同步請求。
        resetAlarm(mPollingIntervalMs);
    }

4.減少NTP請求的時間,確保開機聯網當即同步時間

/frameworks/base/core/res/res/values/config.xml

<integer name="config_ntpPollingIntervalShorter">10000</integer>
相關文章
相關標籤/搜索