一、通过免费或者收费的API接口获取
1、免费
- QQ:http://cgi.im.qq.com/cgi-bin/cgi_svrtime
- 淘宝:http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp
- 苏宁:http://quan.suning.com/getSysTime.do
2、收费
详情:标准北京时间
二、通过访问某个地址并获取时间
1、HTTP协议访问某个网站
原理:HTTP协议的响应体中带有时间
HTTP/1.1 200 OK
Bdpagetype: 1
Bdqid: 0xf15515780000825e
Cache-Control: private
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html
Cxy_all: baidu+d96801e638778b0ae9d58b4082cb757e
Date: Fri, 29 Jun 2018 06:08:38 GMT
Expires: Fri, 29 Jun 2018 06:08:00 GMT
Android 获取方式:
private void getNetTime() {
URL url = null;//取得资源对象
try {
url = new URL("http://www.baidu.com");
//url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
//url = new URL("http://www.bjtime.cn");
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
final String format = formatter.format(calendar.getTime());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "当前网络时间为: \n" + format, Toast.LENGTH_SHORT).show();
tvNetTime.setText("当前网络时间为: \n" + format);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
2、NTP客户端访问NTP服务器
NTP(Network Time Protocol)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间校正(LAN上与标准间差小于1毫秒,WAN上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。
// NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
// NTP server list: http://www.ntp.org.cn/pool.php
public static final String TIME_SERVER = "time-a.nist.gov"; // 服务器域名或ip
public static long getCurrentNetworkTime() {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
//long localDeviceTime = timeInfo.getReturnTime();
long serverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(serverTime);
Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);
return serverTime;
}
3,注意:Android 4.0 之后不能在主线程中请求网络
否则出现以下crash报错,或者请求没有结果。
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getByName(InetAddress.java:743)
at com.lockapp.lock.apublic.util.IpCheckUtils.GetInetAddress(IpCheckUtils.java:148)
at org.linphone.socketclient.MyWebSocketServer$3.run(MyWebSocketServer.java:251)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
可以启动一条子线程进行你的网络请求,推荐使用这种:
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
// your method
}
}).start();
扫描二维码关注公众号,回复:
14408875 查看本文章
