首頁 > 軟體

Android NTP 時間同步機制詳解

2022-08-07 22:00:33

正文

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時間同步的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com