Android: Get Atomic Time

2020-03-30 01:42发布

I'm trying to get the atomic time for an Android app. I'm using http://hi-android.info/src/android/net/SntpClient.java.html as NTP client and the following code to implement the NTP (= sample code from SntpClient.java):

SntpClient client = new SntpClient();
if (client.requestTime("time.foo.com")) {
    long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
}

I tried different server from this list: http://mindprod.com/jgloss/timesources.html, but the "client.requestTime("SERVER")" is always "false" ...

My code:

SntpClient client = new SntpClient();
if (client.requestTime("hera.limescope.net", 10000)) {
    long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
    textAtomicClock.setText(String.valueOf(now));
}

What am I doing wrong?

Freddi

1条回答
Fickle 薄情
2楼-- · 2020-03-30 02:09

Found my mistake! I didn't know that I had to process the ntp task in the background ... I solved the problem with Androids AsyncTask function. Thanks to all who helped me!

查看更多
登录 后发表回答