Android2.3.4时间同步

      在Android2.3.4系统中,Settings->Date & time->Automatic项打上后,时间会通过网络进行同步,而Android默认使用的是NITZ来获取移动网络时间,需要有移动网络服务 商的支持才能使用,而有些Android产品只支持WIFI等无线网络,而不支持移动网络,此时就需要采用SNTP方式来获取网络时间进行同步了,相应需 要修改到的文件为frameworks/base/telephony/java/com/android/internal/telephony /cdma/CdmaServiceStateTracker.java和frameworks/base/telephony/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java这两个文件,需要修改的都是一样的内容,如下:

 添加如下内容:
    import android.net.SntpClient;
    修改如下内容:
    把
    private void revertToNitz() {
        if (Settings.System.getInt(phone.getContext().getContentResolver(),
                Settings.System.AUTO_TIME, 0) == 0) {
            return;
        }
        Log.d(LOG_TAG, "Reverting to NITZ: tz='" + mSavedTimeZone
                + "' mSavedTime=" + mSavedTime
                + " mSavedAtTime=" + mSavedAtTime);
        if (mSavedTimeZone != null && mSavedTime != 0 && mSavedAtTime != 0) {
            setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
            setAndBroadcastNetworkSetTime(mSavedTime
                    + (SystemClock.elapsedRealtime() - mSavedAtTime));
        }
    }
    修改为:
    private void revertToNitz() {
        if (Settings.System.getInt(phone.getContext().getContentResolver(),
                Settings.System.AUTO_TIME, 0) == 0) {
            return;
        }
        Log.d(LOG_TAG, "Reverting to NITZ: tz='" + mSavedTimeZone
                + "' mSavedTime=" + mSavedTime
                + " mSavedAtTime=" + mSavedAtTime);
        if (mSavedTimeZone != null && mSavedTime != 0 && mSavedAtTime != 0) {
            setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
            setAndBroadcastNetworkSetTime(mSavedTime
                    + (SystemClock.elapsedRealtime() - mSavedAtTime));
            return;
        }
        int tryCount = 5;
        SntpClient client = new SntpClient();

        Log.i(LOG_TAG, "revertToNitz new sntpclient");

        for(int i = 0; i < tryCount; i++){
            if(client.requestTime("north-america.pool.ntp.org", 10000)) {
                long cachedNtp = client.getNtpTime();
                long cachedNtpTimestamp = SystemClock.elapsedRealtime();

                Log.i(LOG_TAG, "Sntp NtpTime = " + cachedNtp);

                setAndBroadcastNetworkSetTime(cachedNtp
                   + (SystemClock.elapsedRealtime() - client.getNtpTimeReference()));
                return;
            }
        }
    }

 

north-america.pool.ntp.org是服务器地址,是北美地区的,当然也可以用国内的比如:ntp.api.bz

 

网上时间更新的文章有很多,http://www.cnblogs.com/AdiSky/archive/2012/11/29/2795168.html 这个文章讲的相当不错!

你可能感兴趣的:(android)