Android10.0(Q) 网络自动校时bug修改

2024-08-22 06:18

本文主要是介绍Android10.0(Q) 网络自动校时bug修改,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

问题现象

联网后系统时间依旧显示不对,和系统校时服务器有关系,之前低版本也修改过这个问题来着

修改方法

和之前低版本比对发现,以前的 NetworkTimeUpdateService 已经更名为 NewNetworkTimeUpdateService,而且代码变动不小,根据之前修改问题不大。

frameworks/base/services/core/java/com/android/server/NewNetworkTimeUpdateService.java

import java.io.PrintWriter;//M: For multiple NTP server retry
import java.util.ArrayList;
import android.os.AsyncTask;
import android.net.NetworkInfo;
+/*** Monitors the network time and updates the system time if it is out of sync* and there hasn't been any NITZ update from the carrier recently.
@@ -98,6 +103,18 @@ public class NewNetworkTimeUpdateService extends Binder implements NetworkTimeUp// connection to happen.private int mTryAgainCounter;//UGG add ,add ntp servers [S]                                         private static final String[] NTPSERVERLIST =  new String[]{"s1b.time.edu.cn","ntp3.aliyun.com","ntp4.aliyun.com","ntp5.aliyun.com",                                };                                        private AsyncTask ntpTimeTask;  private boolean isNtpTimeTaskRunning;  //UGG add ,add ntp servers [E] public NewNetworkTimeUpdateService(Context context) {mContext = context;mTime = NtpTrustedTime.getInstance(context);
@@ -138,6 +155,7 @@ public class NewNetworkTimeUpdateService extends Binder implements NetworkTimeUpprivate void registerForTelephonyIntents() {IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);mContext.registerReceiver(mNitzReceiver, intentFilter);}@@ -249,10 +267,49 @@ public class NewNetworkTimeUpdateService extends Binder implements NetworkTimeUpif (DBG) Log.d(TAG, "Received " + action);if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {mNitzTimeSetTime = SystemClock.elapsedRealtime();}else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {//UGG add ,add ntp servers [S]                                         NetworkInfo info = mCM.getActiveNetworkInfo();  if(info != null && info.isAvailable()) {String name = info.getTypeName();Log.d(TAG, "current networkType" + name);if(!isNtpTimeTaskRunning){isNtpTimeTaskRunning=true;new NtpTimeThread().start();}} else {Log.d(TAG, "no available network");// if(ntpTimeTask!=null){//     ntpTimeTask.cancel(true);// }}//UGG add ,add ntp servers [E]                                         }}};//UGG add ,add ntp servers [S]                                         public class NtpTimeThread extends Thread {@Overridepublic void run() {super.run();for(int i=0;i<NTPSERVERLIST.length;i++){try{sleep(1000);boolean result=GetNtpTIme.GetLocalNtpTime(NTPSERVERLIST[i]);Log.i(TAG,"NtpTimeThread result "+result);if(result){break;}}catch(Exception e){}}isNtpTimeTaskRunning=false;}}//UGG add ,add ntp servers [S]    /** Handler to do the network accesses on */private class MyHandler extends Handler {

同级目录下新增 GetNtpTIme.java 和 NtpMessage.java

frameworks/base/services/core/java/com/android/server/GetNtpTIme.java

package com.android.server;import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;
import java.util.Date;import android.os.SystemClock;
import android.util.Log;public class GetNtpTIme {private static String TAG="NetworkTimeUpdateService.GetNtpTIme";public static boolean GetLocalNtpTime(String ntpSvrIP) {boolean res = false;int retry = 0;int port = 123;int timeout = 10000;// get the address and NTP address requestInetAddress ipv4Addr = null;try {if(ntpSvrIP==null){ipv4Addr = InetAddress.getByName("s1b.time.edu.cn");}else{ipv4Addr = InetAddress.getByName(ntpSvrIP);}Log.d(TAG, "ntpSvrIP : " + ntpSvrIP+", ipv4Addr : "+ipv4Addr);} catch (UnknownHostException e1) {e1.printStackTrace();}int serviceStatus = -1;DatagramSocket socket = null;long responseTime = -1;try {socket = new DatagramSocket();socket.setSoTimeout(timeout); // will force the// InterruptedIOExceptionfor (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) {try {// Send NTP requestbyte[] data = new NtpMessage().toByteArray();DatagramPacket outgoing = new DatagramPacket(data,data.length, ipv4Addr, port);long sentTime = System.currentTimeMillis();socket.send(outgoing);// Get NTP ResponseDatagramPacket incoming = new DatagramPacket(data,data.length);socket.receive(incoming);responseTime = System.currentTimeMillis() - sentTime;double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;// 这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差// Validate NTP Response// IOException thrown if packet does not decode as expected.NtpMessage msg = new NtpMessage(incoming.getData());double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;Log.d(TAG,"poll: valid NTP request received the local clock offset is "+ localClockOffset + ", responseTime= "+ responseTime + "ms");Log.d(TAG, "poll: NTP message : " + msg.toString());SystemClock.setCurrentTimeMillis(msg.GetCurrentMS(msg.transmitTimestamp));serviceStatus = 1;res = true;} catch (Exception ex1) {// Ignore, no response received.Log.d(TAG, "InterruptedIOException: "+ ex1.toString());}}} catch (NoRouteToHostException e) {Log.d(TAG, "No route to host exception for address: "+ ipv4Addr);} catch (ConnectException e) {// Connection refused. Continue to retry.e.fillInStackTrace();Log.d(TAG, "Connection exception for address: " + ipv4Addr);} catch (IOException ex) {ex.fillInStackTrace();Log.d(TAG, "IOException while polling address: " + ipv4Addr);} finally {if (socket != null){socket.close();Log.d(TAG, "ntp address: " + ipv4Addr+" res:"+String.valueOf(res));return res;}}// Store response time if available//if (serviceStatus == 1) {Log.d(TAG, "responsetime==" + responseTime);}return res;}
}

frameworks/base/services/core/java/com/android/server/NtpMessage.java

package com.android.server;import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;public class NtpMessage {  /** *//** * This is a two-bit code warning of an impending leap second to be * inserted/deleted in the last minute of the current day. It''s values may * be as follows: *  * Value Meaning ----- ------- 0 no warning 1 last minute has 61 seconds 2 * last minute has 59 seconds) 3 alarm condition (clock not synchronized) */  public byte leapIndicator = 0;  /** *//** * This value indicates the NTP/SNTP version number. The version number is 3 * for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI). If * necessary to distinguish between IPv4, IPv6 and OSI, the encapsulating * context must be inspected. */  public byte version = 3;  /** *//** * This value indicates the mode, with values defined as follows: *  * Mode Meaning ---- ------- 0 reserved 1 symmetric active 2 symmetric * passive 3 client 4 server 5 broadcast 6 reserved for NTP control message * 7 reserved for private use *  * In unicast and anycast modes, the client sets this field to 3 (client) in * the request and the server sets it to 4 (server) in the reply. In * multicast mode, the server sets this field to 5 (broadcast). */  public byte mode = 0;  /** *//** * This value indicates the stratum level of the local clock, with values * defined as follows: *  * Stratum Meaning ---------------------------------------------- 0 * unspecified or unavailable 1 primary reference (e.g., radio clock) 2-15 * secondary reference (via NTP or SNTP) 16-255 reserved */  public short stratum = 0;  /** *//** * This value indicates the maximum interval between successive messages, in * seconds to the nearest power of two. The values that can appear in this * field presently range from 4 (16 s) to 14 (16284 s); however, most * applications use only the sub-range 6 (64 s) to 10 (1024 s). */  public byte pollInterval = 0;  /** *//** * This value indicates the precision of the local clock, in seconds to the * nearest power of two. The values that normally appear in this field * range from -6 for mains-frequency clocks to -20 for microsecond clocks * found in some workstations. */  public byte precision = 0;  /** *//** * This value indicates the total roundtrip delay to the primary reference * source, in seconds. Note that this variable can take on both positive and * negative values, depending on the relative time and frequency offsets. * The values that normally appear in this field range from negative values * of a few milliseconds to positive values of several hundred milliseconds. */  public double rootDelay = 0;  /** *//** * This value indicates the nominal error relative to the primary reference * source, in seconds. The values that normally appear in this field range * from 0 to several hundred milliseconds. */  public double rootDispersion = 0;  /** *//** * This is a 4-byte array identifying the particular reference source. In * the case of NTP Version 3 or Version 4 stratum-0 (unspecified) or * stratum-1 (primary) servers, this is a four-character ASCII string, left * justified and zero padded to 32 bits. In NTP Version 3 secondary servers, * this is the 32-bit IPv4 address of the reference source. In NTP Version 4 * secondary servers, this is the low order 32 bits of the latest transmit * timestamp of the reference source. NTP primary (stratum 1) servers should * set this field to a code identifying the external reference source * according to the following list. If the external reference is one of * those listed, the associated code should be used. Codes for sources not * listed can be contrived as appropriate. *  * Code External Reference Source ---- ------------------------- LOCL * uncalibrated local clock used as a primary reference for a subnet without * external means of synchronization PPS atomic clock or other * pulse-per-second source individually calibrated to national standards * ACTS NIST dialup modem service USNO USNO modem service PTB PTB (Germany) * modem service TDF Allouis (France) Radio 164 kHz DCF Mainflingen * (Germany) Radio 77.5 kHz MSF Rugby (UK) Radio 60 kHz WWV Ft. Collins (US) * Radio 2.5, 5, 10, 15, 20 MHz WWVB Boulder (US) Radio 60 kHz WWVH Kaui * Hawaii (US) Radio 2.5, 5, 10, 15 MHz CHU Ottawa (Canada) Radio 3330, * 7335, 14670 kHz LORC LORAN-C radionavigation system OMEG OMEGA * radionavigation system GPS Global Positioning Service GOES Geostationary * Orbit Environment Satellite */  public byte[] referenceIdentifier = { 0, 0, 0, 0 };  /** *//** * This is the time at which the local clock was last set or corrected, in * seconds since 00:00 1-Jan-1900. */  public double referenceTimestamp = 0;  /** *//** * This is the time at which the request departed the client for the server, * in seconds since 00:00 1-Jan-1900. */  public double originateTimestamp = 0;  /** *//** * This is the time at which the request arrived at the server, in seconds * since 00:00 1-Jan-1900. */  public double receiveTimestamp = 0;  /** *//** * This is the time at which the reply departed the server for the client, * in seconds since 00:00 1-Jan-1900. */  public double transmitTimestamp = 0;  /** *//** * Constructs a new NtpMessage from an array of bytes. */  public NtpMessage(byte[] array) {  // See the packet format diagram in RFC 2030 for details  leapIndicator = (byte) ((array[0] >> 6) & 0x3);  version = (byte) ((array[0] >> 3) & 0x7);  mode = (byte) (array[0] & 0x7);  stratum = unsignedByteToShort(array[1]);  pollInterval = array[2];  precision = array[3];  rootDelay = (array[4] * 256.0) + unsignedByteToShort(array[5]) + (unsignedByteToShort(array[6]) / 256.0) + (unsignedByteToShort(array[7]) / 65536.0);  rootDispersion = (unsignedByteToShort(array[8]) * 256.0) + unsignedByteToShort(array[9]) + (unsignedByteToShort(array[10]) / 256.0) + (unsignedByteToShort(array[11]) / 65536.0);  referenceIdentifier[0] = array[12];  referenceIdentifier[1] = array[13];  referenceIdentifier[2] = array[14];  referenceIdentifier[3] = array[15];  referenceTimestamp = decodeTimestamp(array, 16);  originateTimestamp = decodeTimestamp(array, 24);  receiveTimestamp = decodeTimestamp(array, 32);  transmitTimestamp = decodeTimestamp(array, 40);  }  /** *//** * Constructs a new NtpMessage */  public NtpMessage(byte leapIndicator, byte version, byte mode, short stratum, byte pollInterval, byte precision, double rootDelay, double rootDispersion, byte[] referenceIdentifier, double referenceTimestamp, double originateTimestamp, double receiveTimestamp, double transmitTimestamp) {  // ToDo: Validity checking  this.leapIndicator = leapIndicator;  this.version = version;  this.mode = mode;  this.stratum = stratum;  this.pollInterval = pollInterval;  this.precision = precision;  this.rootDelay = rootDelay;  this.rootDispersion = rootDispersion;  this.referenceIdentifier = referenceIdentifier;  this.referenceTimestamp = referenceTimestamp;  this.originateTimestamp = originateTimestamp;  this.receiveTimestamp = receiveTimestamp;  this.transmitTimestamp = transmitTimestamp;  }  /** *//** * Constructs a new NtpMessage in client -> server mode, and sets the * transmit timestamp to the current time. */  public NtpMessage() {  // Note that all the other member variables are already set with  // appropriate default values.  this.mode = 3;  this.transmitTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;  }  /** *//** * This method constructs the data bytes of a raw NTP packet. */  public byte[] toByteArray() {  // All bytes are automatically set to 0  byte[] p = new byte[48];  p[0] = (byte) (leapIndicator << 6 | version << 3 | mode);  p[1] = (byte) stratum;  p[2] = (byte) pollInterval;  p[3] = (byte) precision;  // root delay is a signed 16.16-bit FP, in Java an int is 32-bits  int l = (int) (rootDelay * 65536.0);  p[4] = (byte) ((l >> 24) & 0xFF);  p[5] = (byte) ((l >> 16) & 0xFF);  p[6] = (byte) ((l >> 8) & 0xFF);  p[7] = (byte) (l & 0xFF);  // root dispersion is an unsigned 16.16-bit FP, in Java there are no  // unsigned primitive types, so we use a long which is 64-bits  long ul = (long) (rootDispersion * 65536.0);  p[8] = (byte) ((ul >> 24) & 0xFF);  p[9] = (byte) ((ul >> 16) & 0xFF);  p[10] = (byte) ((ul >> 8) & 0xFF);  p[11] = (byte) (ul & 0xFF);  p[12] = referenceIdentifier[0];  p[13] = referenceIdentifier[1];  p[14] = referenceIdentifier[2];  p[15] = referenceIdentifier[3];  encodeTimestamp(p, 16, referenceTimestamp);  encodeTimestamp(p, 24, originateTimestamp);  encodeTimestamp(p, 32, receiveTimestamp);  encodeTimestamp(p, 40, transmitTimestamp);  return p;  }  /** *//** * Returns a string representation of a NtpMessage */  public String toString() {  String precisionStr = new DecimalFormat("0.#E0").format(Math.pow(2, precision));  return "Leap indicator: " + leapIndicator + " " + "Version: " + version + " " + "Mode: " + mode + " " + "Stratum: " + stratum + " " + "Poll: " + pollInterval + " " + "Precision: " + precision + " (" + precisionStr + " seconds) " + "Root delay: " + new DecimalFormat("0.00").format(rootDelay * 1000) + " ms " + "Root dispersion: " + new DecimalFormat("0.00").format(rootDispersion * 1000) + " ms " + "Reference identifier: " + referenceIdentifierToString(referenceIdentifier, stratum, version) + " " + "Reference timestamp: " + timestampToString(referenceTimestamp) + " " + "Originate timestamp: " + timestampToString(originateTimestamp) + " " + "Receive timestamp:   " + timestampToString(receiveTimestamp) + " " + "Transmit timestamp: " + timestampToString(transmitTimestamp);  }  /** *//** * Converts an unsigned byte to a short. By default, Java assumes that a * byte is signed. */  public static short unsignedByteToShort(byte b) {  if ((b & 0x80) == 0x80)  return (short) (128 + (b & 0x7f));  else  return (short) b;  }  /** *//** * Will read 8 bytes of a message beginning at <code>pointer</code> and * return it as a double, according to the NTP 64-bit timestamp format. */  public static double decodeTimestamp(byte[] array, int pointer) {  double r = 0.0;  for (int i = 0; i < 8; i++) {  r += unsignedByteToShort(array[pointer + i]) * Math.pow(2, (3 - i) * 8);  }  return r;  }  /** *//** * Encodes a timestamp in the specified position in the message */  public static void encodeTimestamp(byte[] array, int pointer, double timestamp) {  // Converts a double into a 64-bit fixed point  for (int i = 0; i < 8; i++) {  // 2^24, 2^16, 2^8, .. 2^-32  double base = Math.pow(2, (3 - i) * 8);  // Capture byte value  array[pointer + i] = (byte) (timestamp / base);  // Subtract captured value from remaining total  timestamp = timestamp - (double) (unsignedByteToShort(array[pointer + i]) * base);  }  // From RFC 2030: It is advisable to fill the non-significant  // low order bits of the timestamp with a random, unbiased  // bitstring, both to avoid systematic roundoff errors and as  // a means of loop detection and replay detection.  array[7] = (byte) (Math.random() * 255.0);  }  /** *//** * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a * formatted date/time string. */  public static String timestampToString(double timestamp) {  if (timestamp == 0)  return "0";  // timestamp is relative to 1900, utc is used by Java and is relative  // to 1970  double utc = timestamp - (2208988800.0);  // milliseconds  long ms = (long) (utc * 1000.0);  // date/time  String date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date(ms));  // fraction  double fraction = timestamp - ((long) timestamp);  String fractionSting = new DecimalFormat(".000000").format(fraction);  return date + fractionSting;  }  public long GetCurrentMS(double timestamp){if (timestamp == 0)  return 0;  // timestamp is relative to 1900, utc is used by Java and is relative  // to 1970  double utc = timestamp - (2208988800.0);  // milliseconds  long ms = (long) (utc * 1000.0);  return ms;}/** *//** * Returns a string representation of a reference identifier according to * the rules set out in RFC 2030. */  public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {  // From the RFC 2030:  // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)  // or stratum-1 (primary) servers, this is a four-character ASCII  // string, left justified and zero padded to 32 bits.  if (stratum == 0 || stratum == 1) {  return new String(ref);  }  // In NTP Version 3 secondary servers, this is the 32-bit IPv4  // address of the reference source.  else if (version == 3) {  return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]);  }  // In NTP Version 4 secondary servers, this is the low order 32 bits  // of the latest transmit timestamp of the reference source.  else if (version == 4) {  return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0) + (unsignedByteToShort(ref[3]) / 4294967296.0));  }  return "";  }  
}  

这篇关于Android10.0(Q) 网络自动校时bug修改的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1095473

相关文章

Python脚本实现自动删除C盘临时文件夹

《Python脚本实现自动删除C盘临时文件夹》在日常使用电脑的过程中,临时文件夹往往会积累大量的无用数据,占用宝贵的磁盘空间,下面我们就来看看Python如何通过脚本实现自动删除C盘临时文件夹吧... 目录一、准备工作二、python脚本编写三、脚本解析四、运行脚本五、案例演示六、注意事项七、总结在日常使用

SpringBoot项目启动后自动加载系统配置的多种实现方式

《SpringBoot项目启动后自动加载系统配置的多种实现方式》:本文主要介绍SpringBoot项目启动后自动加载系统配置的多种实现方式,并通过代码示例讲解的非常详细,对大家的学习或工作有一定的... 目录1. 使用 CommandLineRunner实现方式:2. 使用 ApplicationRunne

python修改字符串值的三种方法

《python修改字符串值的三种方法》本文主要介绍了python修改字符串值的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录第一种方法:第二种方法:第三种方法:在python中,字符串对象是不可变类型,所以我们没办法直接

SSID究竟是什么? WiFi网络名称及工作方式解析

《SSID究竟是什么?WiFi网络名称及工作方式解析》SID可以看作是无线网络的名称,类似于有线网络中的网络名称或者路由器的名称,在无线网络中,设备通过SSID来识别和连接到特定的无线网络... 当提到 Wi-Fi 网络时,就避不开「SSID」这个术语。简单来说,SSID 就是 Wi-Fi 网络的名称。比如

Mysql8.0修改配置文件my.ini的坑及解决

《Mysql8.0修改配置文件my.ini的坑及解决》使用记事本直接编辑my.ini文件保存后,可能会导致MySQL无法启动,因为MySQL会以ANSI编码读取该文件,解决方法是使用Notepad++... 目录Myhttp://www.chinasem.cnsql8.0修改配置文件my.ini的坑出现的问题

Java实现任务管理器性能网络监控数据的方法详解

《Java实现任务管理器性能网络监控数据的方法详解》在现代操作系统中,任务管理器是一个非常重要的工具,用于监控和管理计算机的运行状态,包括CPU使用率、内存占用等,对于开发者和系统管理员来说,了解这些... 目录引言一、背景知识二、准备工作1. Maven依赖2. Gradle依赖三、代码实现四、代码详解五

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

Spring使用@Retryable实现自动重试机制

《Spring使用@Retryable实现自动重试机制》在微服务架构中,服务之间的调用可能会因为一些暂时性的错误而失败,例如网络波动、数据库连接超时或第三方服务不可用等,在本文中,我们将介绍如何在Sp... 目录引言1. 什么是 @Retryable?2. 如何在 Spring 中使用 @Retryable

使用 Python 和 LabelMe 实现图片验证码的自动标注功能

《使用Python和LabelMe实现图片验证码的自动标注功能》文章介绍了如何使用Python和LabelMe自动标注图片验证码,主要步骤包括图像预处理、OCR识别和生成标注文件,通过结合Pa... 目录使用 python 和 LabelMe 实现图片验证码的自动标注环境准备必备工具安装依赖实现自动标注核心