当前位置 : 主页 > 手机开发 > android >

AndroidNTP时间同步机制详解

来源:互联网 收集:自由互联 发布时间:2023-02-01
目录 正文 初始化 NetworkTimeUpdateCallback AutoTimeSettingObserver MyHandler onPollNetworkTime 总结 正文 NTP是Android原生通过网络获取时间的机制,其中关键代码逻辑都在NetworkTimeUpdateService,它是Androi
目录
  • 正文
  • 初始化
  • NetworkTimeUpdateCallback
  • AutoTimeSettingObserver
  • MyHandler
  • onPollNetworkTime
  • 总结

正文

NTP是Android原生通过网络获取时间的机制,其中关键代码逻辑都在NetworkTimeUpdateService,它是Android系统服务,由SystemServer启动。

本篇文章基于Android 10源码分析。

初始化

我们从它的构造方法开始分析:

    public NetworkTimeUpdateService(Context context) {
        mContext = context;
        //NtpTrustedTime用于获取网络时间
        mTime = NtpTrustedTime.getInstance(context);
        mAlarmManager = mContext.getSystemService(AlarmManager.class);
        mTimeDetector = mContext.getSystemService(TimeDetector.class);
        mCM = mContext.getSystemService(ConnectivityManager.class);
        Intent pollIntent = new Intent(ACTION_POLL, null);
        //创建mPendingPollIntent,用于发送定时广播
        mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
        // 请求服务器频率 86400000ms = 24h
        //从配置文件LINUX/android/frameworks/base/core/res/res/values/config.xml中解析获得
        mPollingIntervalMs = mContext.getResources().getInteger(
                com.android.internal.R.integer.config_ntpPollingInterval);
        //请求时间间隔 60000ms = 10min
        mPollingIntervalShorterMs = mContext.getResources().getInteger(
                com.android.internal.R.integer.config_ntpPollingIntervalShorter);
        //最大尝试次数 3        
        mTryAgainTimesMax = mContext.getResources().getInteger(
                com.android.internal.R.integer.config_ntpRetry);
        mWakeLock = context.getSystemService(PowerManager.class).newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, TAG);
    }

构造方法中主要是对各种变量进行初始化操作,接下来分析systemRunning方法,它是个public方法,NetworkTimeUpdateService创建时,被SystemServer调用。

/** Initialize the receivers and initiate the first NTP request */
public void systemRunning() {
    //注册广播
    registerForAlarms();
    //初始化Handler
    HandlerThread thread = new HandlerThread(TAG);
    thread.start();
    mHandler = new MyHandler(thread.getLooper());
    //向ConnectivityManager注册网络状况监听
    mNetworkTimeUpdateCallback = new NetworkTimeUpdateCallback();
    mCM.registerDefaultNetworkCallback(mNetworkTimeUpdateCallback, mHandler);
    //使用ContentObsrver监听Settings.Global.AUTO_TIME值的变化
    mAutoTimeSettingObserver = new AutoTimeSettingObserver(mContext, mHandler,
            EVENT_AUTO_TIME_ENABLED);
    mAutoTimeSettingObserver.observe();
}
private void registerForAlarms() {
    mContext.registerReceiver(
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
                }
            }, new IntentFilter(ACTION_POLL));
}

这个方法中NetworkTimeUpdateService注册了三个监听:

  • 1.调用registerForAlarms,注册一个广播接收者,接收ACTION_POLL广播,收到后向消息队列发送一个EVENT_POLL_NETWORK_TIME的事件;
  • 2.向ConnectivityManager注册网络状况监听;
  • 3.监听Settings.Global.AUTO_TIME值的变化。

咱们对这三个监听以及如何触发挨个的分析。

NetworkTimeUpdateCallback

mNetworkTimeUpdateCallback = new NetworkTimeUpdateCallback();
mCM.registerDefaultNetworkCallback(mNetworkTimeUpdateCallback, mHandler);
private class NetworkTimeUpdateCallback extends NetworkCallback {
    @Override
    public void onAvailable(Network network) {
        Log.d(TAG, String.format("New default network %s; checking time.", network));
        mDefaultNetwork = network;
        // Running on mHandler so invoke directly.
        onPollNetworkTime(EVENT_NETWORK_CHANGED);
    }
    @Override
    public void onLost(Network network) {
        if (network.equals(mDefaultNetwork)) mDefaultNetwork = null;
    }
}

NetworkTimeUpdateCallback实现了NetworkCallback接口,当被回调onAvailable(网络切换/可用)时, 赋值mDefaultNetwork并调用onPollNetworkTime(EVENT_NETWORK_CHANGED)方法。

AutoTimeSettingObserver

mAutoTimeSettingObserver = new AutoTimeSettingObserver(mContext, mHandler,
               EVENT_AUTO_TIME_ENABLED);
       mAutoTimeSettingObserver.observe();
/**
 * Observer to watch for changes to the AUTO_TIME setting. It only triggers when the setting
 * is enabled.
 */
private static class AutoTimeSettingObserver extends ContentObserver {
    private final Context mContext;
    private final int mMsg;
    private final Handler mHandler;
    AutoTimeSettingObserver(Context context, Handler handler, int msg) {...}
    void observe() {
        ContentResolver resolver = mContext.getContentResolver();
        resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
                false, this);
    }
    @Override
    public void onChange(boolean selfChange) {
        if (isAutomaticTimeEnabled()) {
            mHandler.obtainMessage(mMsg).sendToTarget();
        }
    }
    /**
     * Checks if the user prefers to automatically set the time.
     */
    private boolean isAutomaticTimeEnabled() {
        ContentResolver resolver = mContext.getContentResolver();
        return Settings.Global.getInt(resolver, Settings.Global.AUTO_TIME, 0) != 0;
    }
}

监听Settings.Global.AUTO_TIME的变化,当值改变且AUTO_TIME != 0 时,向消息队列发送一个类型为EVENT_AUTO_TIME_ENABLED的消息。

看到这有三个东西我们还没确认,何时发送ACTION_POLL广播、onPollNetworkTime方法实现、Handler的实现。为了更有条理我打乱一下顺序,先介绍Handler和onPollNetworkTime。

MyHandler

/** Handler to do the network accesses on */
private class MyHandler extends Handler {
    MyHandler(Looper l) {
        super(l);
    }
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case EVENT_AUTO_TIME_ENABLED:
            case EVENT_POLL_NETWORK_TIME:
            case EVENT_NETWORK_CHANGED:
                onPollNetworkTime(msg.what);
                break;
        }
    }
}

三种类型的消息最终都会调用onPollNetworkTime,只有参数不一样。

onPollNetworkTime

private void onPollNetworkTime(int event) {
       // If we don't have any default network, don't bother.
       if (mDefaultNetwork == null) return;
       mWakeLock.acquire();
       try {
           onPollNetworkTimeUnderWakeLock(event);
       } finally {
           mWakeLock.release();
       }
   }

当前无网络情况直接返回,并使用PowerManager.WakeLock(屏幕恒亮)调用onPollNetworkTimeUnderWakeLock(event)。

   private void onPollNetworkTimeUnderWakeLock(int event) {
       // 使用NtpTrustedTime获取网络时间
       NtpTrustedTime.TimeResult cachedNtpResult = mTime.getCachedTimeResult();
       //cachedNtpResult.getAgeMillis()是上次请求ntp服务器的时间
       //如果大于等于1天,则强制刷新时间
       if (cachedNtpResult == null || cachedNtpResult.getAgeMillis() >= mPollingIntervalMs) {
           if (DBG) Log.d(TAG, "Stale NTP fix; forcing refresh");
           //该方法是个阻塞方法
           mTime.forceRefresh();
           cachedNtpResult = mTime.getCachedTimeResult();
       }
       //cachedNtpResult.getAgeMillis() < 1天
       if (cachedNtpResult != null && cachedNtpResult.getAgeMillis() < mPollingIntervalMs) {
           //设置定时广播,1天后触发
           resetAlarm(mPollingIntervalMs);
           // Suggest the time to the time detector. It may choose use it to set the system clock.
          // 设置系统时间
           TimestampedValue<Long> timeSignal = new TimestampedValue<>(
                   cachedNtpResult.getElapsedRealtimeMillis(), cachedNtpResult.getTimeMillis());
           NetworkTimeSuggestion timeSuggestion = new NetworkTimeSuggestion(timeSignal);
           timeSuggestion.addDebugInfo("Origin: NetworkTimeUpdateService. event=" + event);
           mTimeDetector.suggestNetworkTime(timeSuggestion);
       } else {
           mTryAgainCounter++;
           if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {
               //设置定时广播,10分钟后触发
               resetAlarm(mPollingIntervalShorterMs);
           } else {
               //设置定时广播,1天后触发
               mTryAgainCounter = 0;
               resetAlarm(mPollingIntervalMs);
           }
       }
   }

注意到上面调用了resetAlarm(),该方法即是定时发送ACTION_POLL广播。

private void resetAlarm(long interval) {
    mAlarmManager.cancel(mPendingPollIntent);
    long now = SystemClock.elapsedRealtime();
    long next = now + interval;
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
}

总结一下onPollNetworkTimeUnderWakeLock做的事情:

总结

NetworkTimeUpdateService启动后有两种方式触发时间更新。

1.网络发生变化;

2.Settings中的AUTO_TIME开关变化;

最终都会调用onPollNetworkTimeUnderWakeLock去设置时间,根据获取的cachedNtpResult情况设置不同时间的定时广播再去尝试更新时间。

以上就是Android NTP 时间同步机制详解的详细内容,更多关于Android NTP时间同步的资料请关注自由互联其它相关文章!

网友评论