您好,登录后才能下订单哦!
本篇内容主要讲解“Android NTP时间同步机制实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Android NTP时间同步机制实例分析”吧!
NTP是Android原生通过网络获取时间的机制,其中关键代码逻辑都在NetworkTimeUpdateService,它是Android系统服务,由SystemServer启动。
我们从它的构造方法开始分析:
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值的变化。
咱们对这三个监听以及如何触发挨个的分析。
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)方法。
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。
/** 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,只有参数不一样。
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做的事情:
到此,相信大家对“Android NTP时间同步机制实例分析”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。