Android獲取網絡時間的方法

1、經過免費或者收費的API接口獲取

一、免費
  • 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
二、收費

詳情:標準北京時間php

2、經過訪問某個地址並獲取時間

一、HTTP協議訪問某個網站

原理:HTTP協議的響應體中帶有時間html

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 獲取方式:java

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

詳情:Android - 獲取系統時間和網絡時間api

二、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";

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;
}

詳情:Get Network Time網絡

相關文章
相關標籤/搜索