Android NTP 時間同步機制詳解

正文

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時間同步的資料請關註WalkonNet其它相關文章!

推薦閱讀: