在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();java
Log.i(LOG_TAG, "revertToNitz new sntpclient");android
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);.net
setAndBroadcastNetworkSetTime(cachedNtp
+ (SystemClock.elapsedRealtime() - client.getNtpTimeReference()));
return;
}
}
}
當不支持NITZ獲取時間同步時就使用SNTP方式獲取時間進行同步。不過使用SNTP方式進行時間同步時不能同步時區,須要本身先去掉自動同步並設置時區後再設置自動同步,這樣才能進行網絡時間的同步更新。
get