Android时间同步机制概述

一、Android时间同步机制概述

Android时间同步机制常见的有基于GPS的时间同步和基于网络的时间同步,本文介绍基于网络的时间同步机制,以及简单介绍一下 MTK 遇见网络时间同步无法更新问题的解决方式。

1.1 framework相关代码

网络时间同步的代码在framework目录下

  1. frameworks\base\core\java\android\util\NtpTrustedTime.java
@Override
    public boolean forceRefresh() {
   
        if (TextUtils.isEmpty(mServer)) {
   
            // missing server, so no trusted time available
            return false;
        }
        // We can't do this at initialization time: ConnectivityService might not be running yet.
        synchronized (this) {
   
            if (mCM == null) {
   
                mCM = (ConnectivityManager) sContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            }
        }
        final NetworkInfo ni = mCM == null ? null : mCM.getActiveNetworkInfo();
        if (ni == null || !ni.isConnected()) {
   
            if (LOGD) Log.d(TAG, "forceRefresh: no connectivity");
            return false;
        }
        if (LOGD) Log.d(TAG, "forceRefresh() from cache miss");
        final SntpClient client = new SntpClient();//获取时间通过SntpClient类包装的socket访问ntp网址类
        if (client.requestTime(mServer, (int) mTimeout)) {
   
            mHasCache = true;
            mCachedNtpTime = client.getNtpTime();
            mCachedNtpElapsedRealtime = client.getNtpTimeReference();
            mCachedNtpCertainty = client.getRoundTripTime() / 2;
            return true;
        } else {
   
            return false;
        }
    }
  1. frameworks\base\services\core\java\com\android\server\NetworkTimeUpdateService.java
    限定默认轮巡的服务器地址,可以后期依据index进行更换
//当联网的时候,需要进行轮询的时间服务器,当然这个是已经添加过额外的服务器的列表。
 private static final String[] SERVERLIST =  new String[]{
   
                                            "ntp1.aliyun.com",
                                            "ntp2.aliyun.com",
                                            "edu.ntp.org.cn",
                                            "ntp.aliyun.com",
                                            "time.windows.com",
                                            "cn.pool.ntp.org",
                                             };           
 //NetworkTimeUpdateService 初始化属性和数组,
 public NetworkTimeUpdateService(Context context) {
   
        mContext = context;
        mTime = NtpTrustedTime.getInstance(context
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值