Android SntpClient请求始终为false

时间:2016-02-09 09:53:40

标签: android ntp

我正在尝试使用SntpClient.java来获取NTP日期并在textView中显示它

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    tVNTP = (TextView) findViewById(R.id.textoNTP);
    tVNTP.setText("Waiting ntp server response...");
    consultaNTP();
}

所以这是我的onCreate(),我调用的函数是:

public void consultaNTP(){
    SntpClient client = new SntpClient();
    if (client.requestTime("es.pool.ntp.org", 30000)) {
        long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
        Log.i("consultarNTP", "Value: >"+now+"<");
        tVNTP.setText("Value: >"+now+"<");
    }
    else{
        Log.i("consultaNTP","ERROR: Request unsuccessful");
        tVNTP.setText("ERROR: Request unsuccessful");
    }
}

此外,我在AndroidManifest.xml中有下一个权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

发生的事情是我没有例外,但

client.requestTime("es.pool.ntp.org", 30000)

总是返回false。你有什么提示让它起作用吗?我看到的例子与我的没有什么不同,但目前还不行......

解决方案:

public void consultaNTP(){
    final SntpClient client = new SntpClient();

    new Thread()
    {
        public void run() {
            if (client.requestTime("es.pool.ntp.org", 30000)) {
                long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
                Log.i("consultarNTP", "Value: >"+now+"<");
                //tVNTP.setText("Value: >"+now+"<");
            }
            else{
                Log.i("consultaNTP","ERROR: Request unsuccessful");
                //tVNTP.setText("ERROR: Request unsuccessful");
            }
        }
    }.start();
}

0 个答案:

没有答案