手机如何电脑时间不能自动更新新网络时间

Android 时间更新机制之网络更新时间
综述:网络时间更新,大体分两类。1、moderm相关更新,2、网络更新。本次主要介绍网路更新时间,主要涉及到NetworkTimeUpdateService,该类运行在SystemServer(ActivityManagerService)进程中。它有点特殊,从名字来看,其实Service,其实它和WifiService、ConnectivityManagerService等Service不同。
SystemServer.java
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e(System, ******************************************);
Slog.e(System, ************ Failure starting system services, ex);
startOtherServices方法中,会初始化该类实例:
networkTimeUpdater = new NetworkTimeUpdateService(context);
在ActivityManagerService的systemReady方法中,初始化时间更新环境。
mActivityManagerService.systemReady(new Runnable() {
public void run() {
if (networkManagementF != null)
networkManagementF.systemReady();
} catch (Throwable e) {
reportWtf(making Network Managment Service ready, e);
涉及代码路径如下:
frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java
frameworks/base/core/java/android/util/NtpTrustedTime.java
frameworks/base/core/java/android/net/SntpClient.java
一、NetworkTimeUpdateService实例
public NetworkTimeUpdateService(Context context) {
mContext =
mTime = NtpTrustedTime.getInstance(context);
mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Intent pollIntent = new Intent(ACTION_POLL, null);
mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);//时间同步有可能超时,使用该PendingIntent进行(间隔再次发起)时间同步。
mPollingIntervalMs = mContext.getResources().getInteger(
com.android.internal.R.integer.config_ntpPollingInterval);//10天
mPollingIntervalShorterMs = mContext.getResources().getInteger(
com.android.internal.R.integer.config_ntpPollingIntervalShorter);//30秒
mTryAgainTimesMax = mContext.getResources().getInteger(
com.android.internal.R.integer.config_ntpRetry);
mTimeErrorThresholdMs = mContext.getResources().getInteger(
com.android.internal.R.integer.config_ntpThreshold);
//LEUI-START [BUG][MOBILEP-6067] [System time sync added
mDefaultServer = ((NtpTrustedTime) mTime).getServer();
mNtpServers.add(mDefaultServer);
for (String str : SERVERLIST)
mNtpServers.add(str);
mTryAgainCounter = 0;
//LEUI-END [BUG][MOBILEP-6067] [System time sync added
在该构造上,有几个重要的变量:
1、mPollingIntervalMs:多次尝试同步时间无果,10天会再次发起时间同步请求
2、mPollingIntervalShorterMs :时间同步超时,再次发起时间同步请求。
3、SERVERLIST:时间同步服务器。此处建议多增加几个时间同步服务器,大陆、美国、台湾等多梯度配置。
4、初始化NtpTrustedTime对象。
mTime = NtpTrustedTime.getInstance(context);
一、NetworkTimeUpdateService初始化时间同步环境
开机后,会调用该类的systemRunning方法,在该方法中:
public void systemRunning() {
registerForTelephonyIntents();
registerForAlarms();
registerForConnectivityIntents();
HandlerThread thread = new HandlerThread(TAG);
thread.start();
mHandler = new MyHandler(thread.getLooper());
// Check the network time on the new thread
mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
mSettingsObserver.observe(mContext);
1、registerForTelephonyIntents该方法,注册监听来自Telephony Ril相关的广播。此部分会在moderm相关同步时间中介绍。
private void registerForTelephonyIntents() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
mContext.registerReceiver(mNitzReceiver, intentFilter);
2、registerForAlarms此方法,是配合第&一&中介绍的mPendingPollIntent 来工作的,主要作用是构造handler Message并再次发起时间同步请求。
3、registerForConnectivityIntents此方法监听移动数据连接,移动网络连接后,收到信息,发起时间同步请求。此部分会在moderm相关同步时间中介绍。
private void registerForConnectivityIntents() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mConnectivityReceiver, intentFilter);
4、构建Message,发起时间同步请求。
HandlerThread thread = new HandlerThread(TAG);
thread.start();
mHandler = new MyHandler(thread.getLooper());
// Check the network time on the new thread
mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
5、构建监听的Observer,监听来自设置等发起的时间同步请求。在SettingsObserver中构建handler Message请求,发起时间同步。
mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
mSettingsObserver.observe(mContext);
我们的第二部分,很多地方都会主动或者被动发送Handler Message请求,在我们Handler中,我们是如何处理的那?
三、时间同步请求处理逻辑。
在第二部分,我们讲到了接收的来自Telephony相关的广播,或者数据库变化,我们都会发送Message给Handler,我们的handler是如下处理这些请求的:
private class MyHandler extends Handler {
public MyHandler(Looper l) {
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_AUTO_TIME_CHANGED:
case EVENT_POLL_NETWORK_TIME:
case EVENT_NETWORK_CONNECTED:
onPollNetworkTime(msg.what);
接收请求类型:EVENT_AUTO_TIME_CHANGED、EVENT_POLL_NETWORK_TIME、
EVENT_NETWORK_CONNECTED,这些请求逻辑,我们都会发起onPollNetworkTime来进行相关逻辑处理。
也就是说,onPollNetworkTime方法就是我们时间同步的主要关注对象。
1、onPollNetworkTime:
private void onPollNetworkTime(int event) {
//1、是否勾选自动同步时间配置
// If Automatic time is not set, don't bother.
if (!isAutomaticTimeRequested())
//2、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);
//3、如果机器刚启动,或者机器运行时间大于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.1、是否含有时间缓冲,如无,发起时间同步,
// 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.1、遍历时间服务器,发起时间同步
if (mTime instanceof NtpTrustedTime)
((NtpTrustedTime) mTime).setServer(mNtpServers.get(index));
mTime.forceRefresh();
((NtpTrustedTime) mTime).setServer(mDefaultServer);
mTime.forceRefresh();
//LEUI-END [BUG][MOBILEP-6067] [System time sync added
//3.2、获取最新同步的时间缓冲数据,如无,则再次发起时间同步,间隔时间为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.1、如果开机第一次同步或者最新时间与当前时间差别超过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 =
// Make sure we don't overflow, since it's going to be converted to an int
//3.2.2、设定同步时间
if (ntp / 1000 & Integer.MAX_VALUE) {
SystemClock.setCurrentTimeMillis(ntp);
if (DBG) Log.d(TAG, Ntp time is close enough =
mLastNtpFetchTime = SystemClock.elapsedRealtime();
// Try again shortly
//3.3 如果不大于最大同步次数,30秒后进行时间同步,否则,10天后更新。
mTryAgainCounter++;
if (mTryAgainTimesMax & 0 || mTryAgainCounter &= mTryAgainTimesMax) {
resetAlarm(mPollingIntervalShorterMs);
// Try much later
mTryAgainCounter = 0;
resetAlarm(mPollingIntervalMs);
//4、如果刚更新时间不久,则10天后再发起时间同步请求。
resetAlarm(mPollingIntervalMs);
四、三中介绍了时间获取的相关逻辑,我们接下来介绍下时间是如何发起同步的,这个方法的主角为:NtpTrustedTime
在该类中通过forceRefresh方法来更新获取服务器时间。
public boolean forceRefresh() {
if (mServer == null) {
// missing server, so no trusted time available
if (LOGD) Log.d(TAG, forceRefresh() from cache miss);
final SntpClient client = new SntpClient();
if (client.requestTime(mServer, (int) mTimeout)) {
mHasCache =
mCachedNtpTime = client.getNtpTime();
mCachedNtpElapsedRealtime = client.getNtpTimeReference();
mCachedNtpCertainty = client.getRoundTripTime() / 2;
在该方法逻辑中,通过SntpClient来封装请求。
SntpClient.java
public boolean requestTime(String host, int timeout) {
DatagramSocket socket =
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 +
// if (false) Log.d(TAG, clock offset:
+ clockOffset +
// save our results - use the times on this side of the network latency
// (response rather than request time)
mNtpTime = responseTime + clockO
mNtpTimeReference = responseT
mRoundTripTime = roundTripT
} catch (Exception e) {
if (false) Log.d(TAG, request time failed:
} finally {
if (socket != null) {
socket.close();
我们传入在NetworkTimeUpdateService传入的服务器地址以及请求超时时间,向host服务器发起请求,并将相应结果按照编解码规则封装进二进制数组。
总结:NetworkTimeUpdateService时间同步,一旦发起成功的时间同步,时间数据会存在内存中,并根据当前机器运行时间来设定最新的时间。
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'在线时间77小时
铜币334威望0元宝56贡献力0
系统时间无法自动更新
发表于: &&&&来自: PC端
机型:尼凯恩NX旗舰系统:2.7.3-R1-7问题:拔掉电池后,再装回电池开机,系统时间停留在日8:00,需要到系统设置中,手工将时间自动更新的开关关闭再开启,时间才能显示正常。12306的最新客户端还是不能用,虽然可以使用第三方的,但是第三方的账号安全问题让人有所顾虑。
评价一下你浏览此帖子的感受
在线时间1小时
铜币3威望0元宝0贡献力0
发表于: &&&&来自:
我的是C2一样的问题。
在线时间910小时
铜币2468威望0元宝0贡献力0
发表于: &&&&来自: PC端
1工程师们正在加紧处理。建议你手机上可以先安装路路通或者智行火车票用着,那个也可以订票[ 此帖被聂灰灰在 17:57重新编辑 ]
在线时间910小时
铜币2468威望0元宝0贡献力0
发表于: &&&&来自: PC端
扣掉电池 手机是没有办法记录时间的呢 所有手机都是这样呢
在线时间77小时
铜币334威望0元宝56贡献力0
发表于: &&&&来自: PC端
回 聂灰灰 的帖子
:扣掉电池 手机是没有办法记录时间的呢 所有手机都是这样呢 ( 17:37) 亲,以前是可以的呢,其他的手机,除了老的诺基亚,新的也是可以的。你说长时间扣掉电池会丢失,我还能理解,但是就换块电池的时间,这个应该是有问题了吧。其实问题的关键不在这个时间丢失,而是系统重新启动后,为什么不能联网获取时间,必须我手工触发,才能更新
如果您在写长篇帖子又不马上发表,建议存为草稿
&回复后跳转到最后一页12:42:151344
ROOT,把GMS服务包里的GoogleServicesFramework.apk文件拷贝进/system/app/,权限644,然后恢复出厂设置。
以后就能自动从网络更新时间了。
送上2.3的GMS服务包提取的GoogleServicesFramework.apk。
本帖有隐藏内容,需要感谢楼主之后才能查看哦!点击快捷回复: 谢楼楼主!楼主威武!
反反复复反反复复发
机会故意妇幼
不要迷恋哥,哥只是个传说!,~~~~~~~~~~~~
下载试试SSSSSSSSSSSSSSSSS
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
哥顶的不是帖子,是寂寞!,~~~~~~~~~~~~~~
此贴已被删除
看帖顶帖这是必须滴!,~~~~~~~~~~~~~~~~~~~
哥顶的不是帖子,是寂寞!,~~~~~~~~~~~~~~
您需要注册登录后,才能回帖哦!
快速登录:当前【全部】
全部安卓手机安卓平板安卓电视iPhoneiPad其他
当前位置:>>>同步网络时间
热门排行榜
14万+人在玩94万+人在玩25万+人在玩137万+人在玩10万+人在玩2472+人在玩
同步网络时间app相关推荐
发现该应用有下载安装使用错误或恶意扣费携带病毒,请
版权所有 京ICP备号-5
京公网安备 50 备}

我要回帖

更多关于 手机时间不能自动更新 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信