3

亲爱的安卓开发者,

我正在尝试在我的应用程序中实现 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();
     }
} 

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

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

提前致谢!

4

3 回答 3

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 秒。

于 2014-06-08T02:11:36.257 回答
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();
于 2015-06-24T04:43:13.247 回答
1

Check that your manifest has this one:

<uses-permission android:name="android.permission.INTERNET" />
于 2016-10-25T11:34:35.760 回答