在移动设备上使用准确的时间

上一篇文章写了在服务器同步NTP服务器时间的方案。如果你有兴趣可以点击下面的链接查看。

下面介绍在移动端同步NTP时间的方案(非修改系统时间,是直接使用NTP服务器时间)。

Android端

本教程使用第三方库 [TrueTime-Android]

引入最新版本

implementation 'com.github.instacart:truetime-android:3.5'

在一个稳定页面初始化

注意,这里初始化经常会有奇怪的问题,需要你写一个足够的冗余条件!!!下面是我的方案

        try {
            val thread = Thread {
                try {
                    TrueTimeRx.build()
                        .withNtpHost("ntp.aliyun.com")
                        .withRootDelayMax(1000f)
                        .withRootDispersionMax(1000f)
                        .initialize()
                } catch (e: Exception) {
                }
            }
            thread.start()
        } catch (e: Exception) {
        }

使用时

正常使用语句

//获取当前时间:

val time = TrueTimeRx.now()

//获取当前时间戳

val timestamp = TrueTimeRx.now().time

我的使用方案

val timestamp = try {
   TrueTimeRx.now().time
}catch (e: Exception){
   System.currentTimeMillis()
}

iOS端

本教程使用第三方库 [TrueTime.swift]

引入插件

github "instacart/TrueTime.swift"
# 或者
pod 'TrueTime'

swift

import TrueTime

// At an opportune time (e.g. app start):
let client = TrueTimeClient.sharedInstance
client.start()

// You can now use this instead of NSDate():
let now = client.referenceTime?.now()

// To block waiting for fetch, use the following:
client.fetchIfNeeded { result in
    switch result {
        case let .success(referenceTime):
            let now = referenceTime.now()
        case let .failure(error):
            print("Error! \(error)")
    }
}

Object-C

@import TrueTime;

// At an opportune time (e.g. app start):
TrueTimeClient *client = [TrueTimeClient sharedInstance];
[client startWithPool:@[@"ntp.aliyun.com"] port:123];

// You can now use this instead of [NSDate date]:
NSDate *now = [[client referenceTime] now];

// To block waiting for fetch, use the following:
[client fetchIfNeededWithSuccess:^(NTPReferenceTime *referenceTime) {
    NSLog(@"True time: %@", [referenceTime now]);
} failure:^(NSError *error) {
    NSLog(@"Error! %@", error);
}];

关于NTP服务器,下面是我总结的一些NTP服务器,推荐程度从上到下

# 腾讯云
ntp.tencent.com
ntp1.tencent.com
ntp2.tencent.com
ntp3.tencent.com
ntp4.tencent.com
ntp5.tencent.com

# 阿里云
ntp.aliyun.com
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com

# 以下为不推荐国内使用的方案

# 中科院,大部分情况正常,但是偶尔会有延迟,需要自己做冗余方案!!
ntp.ntsc.ac.cn

# 来自 https://www.ntppool.org/ 的服务地址,这是绝大多数LINUX的默认NTP服务器
0.pool.ntp.org
1.pool.ntp.org
2.pool.ntp.org
3.pool.ntp.org

# 苹果和微软
time.apple.com
time.asia.apple.com
time.windows.com
time.nist.gov

# 苹果的其他服务地址
time1.apple.com
time2.apple.com
time3.apple.com
time4.apple.com
time5.apple.com
time6.apple.com
time7.apple.com

# Google
time1.google.com
time2.google.com
time3.google.com
time4.google.com

Comments

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注