安卓:获取来自NTP服务器的日期和时间 [英] Android: Getting the date and time from a NTP server

查看:1383
本文介绍了安卓:获取来自NTP服务器的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得我自己的时间服务器(如192.168.1.X)的日期和时间,在我的Andr​​oid应用程序

I would like to obtain the date and time from my own time server (i.e. 192.168.1.X) for the use inside my Android application

我有搜索在网上,有两种解决方法:

I have searched in the web and there are two solutions:

<一个href="http://stackoverflow.com/questions/13064750/how-to-get-current-time-from-internet-in-android">solution 1

<一个href="http://stackoverflow.com/questions/8049912/how-can-i-get-the-network-time-from-the-automatic-setting-called-use-netw">solution 2

不过,我不知道是否有没有导入任何库中的任何解决方案?

However, I was wonder if there is any solution without importing any libraries?

谢谢!

推荐答案

我最终使用<一个href="http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/4.1.1_r1/android/net/SntpClient.java/">this 之一。

创建另一个类,然后里面添加code。然后调用类从我的主要活动取得的日期。

Create another class and then add the code inside. And then calling the class from my main activity to obtain the date.

在code是有点老了,我修改了它加入的AsyncTask ......工作正常,我...

The code is a bit old and I modified it by adding AsyncTask... works fine for me...

还有一件事,在类的用法(从什么code sugguest)给出了将String.valueOf(现)返回0日期应使用如下:

And one more thing, the usage of the class (from what the code sugguest) gives String.valueof(now) returns 0. Date should be used as below:

SntpClient client = new SntpClient();
if (client.requestTime("time.foo.com")) {
    long now = client.getNtpTime() + SystemClock.elapsedRealtime() - 
    client.getNtpTimeReference();
    Date current = new Date(now);
    Log.i("NTP tag", current.toString());
}

这篇关于安卓:获取来自NTP服务器的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆