2013-05-13 69 views
2

亲爱的Android开发者,获取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(); 
    } 
} 

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

这将是伟大的,当有人有任何想法或小费给我。

在此先感谢!

+0

问题是什么,会发生什么? – 2013-05-13 18:01:40

+0

什么都没有发生。我不知道我应该输入什么“网络超时”,目前它是“10”... – Marcus 2013-05-13 18:03:27

+0

我不认为这可能是问题。你调试了应用程序并检查它是否进入if区块? – 2013-05-13 18:05:08

回答

2

你应该把它的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

您可以使用此全部样本:

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(); 
0

检查你的表现有这样一条:?

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