从Android应用程序中获取NTP服务器的时间

时间:2013-05-13 17:57:01

标签: java android networking client ntp

亲爱的Android开发者,

我正在尝试在我的应用程序中实现sntpclient类,但它不起作用。

课程:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/net/SntpClient.java

在我的代码中我有以下几行:

public void onClickBtn(View v)
{
    SntpClient client = new SntpClient();
     if (client.requestTime("pool.ntp.org", 10)) {
         long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
         Toast.makeText(this, "Offset: " + now, Toast.LENGTH_LONG).show();
     }
} 

在这种情况下,我真的不知道网络超时是什么意思。

如果有人对我有任何想法或提示,那就太棒了。

提前致谢!

3 个答案:

答案 0 :(得分:4)

你应该把它放在AsyncTask中:

class GetNTPAsynctask extends AsyncTask<String, Void, Boolean> {

@Override
        protected Boolean doInBackground(String... params) {
            private SntpClient sntpClient = new SntpClient();
            return sntpClient.requestTime("pool.ntp.org", 30000);
        }
}

超时:网络超时(以毫秒为单位)。所以我使用30000意味着30秒。

答案 1 :(得分:3)

您可以使用此完整示例:

class getCurrentNetworkTime extends AsyncTask<String, Void, Boolean> {

    private Exception exception;

    protected Boolean doInBackground(String... urls) {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(3000);
        InetAddress inetAddress = null;
        boolean is_locale_date = false;
        try {
            inetAddress = InetAddress.getByName(G.TIME_SERVER);
            TimeInfo timeInfo = null;
            timeInfo = timeClient.getTime(inetAddress);
            long localTime = timeInfo.getReturnTime();
            long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
            if (new Date(localTime) != new Date(serverTime))
                is_locale_date = true;

        } catch (UnknownHostException e) {
            e.printStackTrace();
            Log.e("UnknownHostException: ", e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("IOException: ", e.getMessage());
        }
        return is_locale_date;
    }

    protected void onPostExecute(boolean local_date) {
        if(!local_date) {
            Log.e("Check ", "dates not equal" + local_date);
        }
    }
}

使用方法:

new getCurrentNetworkTime().execute();

答案 2 :(得分:1)

检查你的清单是否有这个:

<uses-permission android:name="android.permission.INTERNET" />
相关问题