Android手机时间自动同步

在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;
}
}
}
当不支持NITZ获取时间同步时就使用SNTP方式获取时间进行同步。不过使用SNTP方式进行时间同步时不能同步时区,需要自己先去掉自动同步并设置时区后再设置自动同步,这样才能进行网络时间的同步更新。

你可能感兴趣的:(android)