android 如何关闭NTP网络时间同步?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 如何关闭NTP网络时间同步?相关的知识,希望对你有一定的参考价值。

从应用层代码具体地讲

Linux停止ntp服务即可关闭时间同步。
①关闭ntp服务(临时设置重启后自动开启)

service ntpd stop
②设置永久关闭ntp服务(重启后也是关闭的)
chkconfig ntpd off
参考技术A 综述:android网络时间更新,大体分两类。1、moderm相关更新,2、网络更新。本次主要介绍网路更新时间,主要涉及到NetworkTimeUpdateService,该类运行在SystemServer(ActivityManagerService)进程中。它有点特殊,从名字来看,其实Service,其实它和WifiService、ConnectivityManagerService等系统Service不同。
SystemServer.java
try
startBootstrapServices();
startCoreServices();
startOtherServices();
catch (Throwable ex)
Slog.e(System, ******************************************);
Slog.e(System, ************ Failure starting system services, ex);
throw ex;


startOtherServices方法中,会初始化该类实例:
networkTimeUpdater = new NetworkTimeUpdateService(context);

在ActivityManagerService的systemReady方法中,初始化时间更新环境。
mActivityManagerService.systemReady(new Runnable()
@Override
public void run()
try
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 = context;
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)
super(l);


@Override
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);
break;




接收请求类型: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()) return;
//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);
return;

//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);

else

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 = + ntp);
// 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);

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;


//4、如果刚更新时间不久,则10天后再发起时间同步请求。
resetAlarm(mPollingIntervalMs);
本回答被提问者采纳

#yyds干货盘点# 如何在 Linux 上安装配置 NTP 服务器和客户端?

@TOC

前言

<font size=3> NTP时间同步是一种时间同步网络技术。

<font size=3> 有多种时间同步技术,每一种技术都各有特点,不同技术的时间同步精度也存在较大的差异。

<hr />

一、Chrony

1、简述

  • chrony是网络时间协议(NTP)的另一种实现,与网络时间协议后台程序(ntpd)不同,它可以更快地且更准确地同步系统时钟,请注意,ntpd仍然包含其中以供需要运行NTP服务的客户使用。

  • 两个主要程序:chronyd和chronyc
            chronyd:后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务器同步。它确定计算机增减时间的比率,并对此进行补偿
            chronyc:命令行用户工具,用于监控性能并进行多样化的配置。它可以在chronyd实例控制的计算机上工作,也可在一台不同的远程计算机上工作

  • 服务unit文件: /usr/lib/systemd/system/chronyd.service

  • 监听端口: 323/udp,123/udp
  • 配置文件: /etc/chrony.conf

2、时间时区概念理解

  • UTC:协调世界时,又称世界统一时间、世界标准时间、国际协调时间。由于英文(CUT)和法文(TUC)的缩写不同,作为妥协,简称UTC
  • GMT:是指格林尼治所在地的标准时间,也是表示地球自转速率的一种形式。以地球自转为基础的时间计量系统。地球自转的角度可用地方子午线相对于地球上的基本参考点的运动来度量。
  • CST:中国标准时间 (China Standard Time)
  • DST:夏令时(Daylight Saving Time) 指在夏天太阳升起的比较早时,将时间拨快一小时,以提早日光的使用(中国不使用)。

二、时间服务器

1、软件包

[root@chronyd_host ~]# yum -y install chrony  // 安装时间同步服务软件包

[root@chronyd_host ~]# rpm -qc chrony       // 查看软件包下有哪些配置文件
/etc/chrony.conf
/etc/chrony.keys
/etc/logrotate.d/chrony
/etc/sysconfig/chronyd

2、修改配置文件

  • 主配置文件: /etc/chrony.conf
# 修改配置文件
[root@chronyd_host ~]# vim /etc/chrony.conf
allow 192.168.1.100/24          // 允许那个IP或网络访问NTP
allow  0.0.0.0/0        // 允许所有的客户端使用

deny 192.168.2.10           // 拒绝那个IP或网络访问NTP

local stratum 10        // 设置NTP服务器的层数量

3、时间服务管理与基础命令

[root@chronyd_host ~]# systemctl restart chronyd        // 重启服务,让配置生效

[root@chronyd_host ~]# systemctl enable chronyd     // 设置开机自启动

[root@chronyd_host ~]# timedatectl status       // 查看时间同步状态
[root@chronyd_host ~]# timedatectl set-ntp true     // 开启网络时间同步

三、客户端

1、修改配置文件

  • 主配置文件: /etc/chrony.conf
# 修改配置文件
[root@localhost ~]# vim /etc/chrony.conf
server chronyd_host iburst

allow  0.0.0.0/0        // 允许所有的客户端使用

2、启动服务

[root@localhost ~]# systemctl start chronyd     // 重启服务,让配置生效

[root@localhost~]# systemctl enable chronyd     // 设置开机自启动

[root@localhost ~]# chronyc sources -v      // 查看时间是否同步
.
--
Source mode ^ = server, = = peer, # = local clock.
/ .- Source state * = current synced, + = combined , - = not combined,
| / ? = unreachable, x = time may be in error, ~ = time too variable.
||

===============================================================================
^* 192.168.2.100

* : 代表当前状态为同步正常
? :代表不可达

3、常用命令

[root@localhost ~]# timedatectl             // 显示系统当前日期和时间

// 设置日期和时间 
[root@localhost ~]# timedatectl set-time "YYYY-MM-DD HH:MM:SS"
[root@localhost ~]# timedatectl set-time "YYYY-MM-DD"
[root@localhost ~]# timedatectl set-time "HH:MM:SS"

[root@localhost ~]# timedatectl set-timezone Asia/Shanghai  // 设置时区

以上是关于android 如何关闭NTP网络时间同步?的主要内容,如果未能解决你的问题,请参考以下文章

Android11 使用NTP同步时间

NTP时钟服务器的特点(京准电子)

搭建ntp服务器

如何在linux 上配置NTP 时间同步

网络时钟同步设备(NTP时间同步服务器)技术设计应用方案

内网ntp时间同步配置