本文實(shí)例講述了Android編程獲取網(wǎng)絡(luò)時(shí)間的方法。分享給大家供大家參考,具體如下:
在網(wǎng)上看到的最常見(jiàn)的方式有:
public static void main(String[] args) throws Exception { URL url=new URL("http://www.bjtime.cn");//取得資源對(duì)象 URLConnection uc=url.openConnection();//生成連接對(duì)象 uc.connect(); //發(fā)出連接 long ld=uc.getDate(); //取得網(wǎng)站日期時(shí)間 Date date=new Date(ld); //轉(zhuǎn)換為標(biāo)準(zhǔn)時(shí)間對(duì)象 //分別取得時(shí)間中的小時(shí),分鐘和秒,并輸出 System.out.print(date.getHours()+"時(shí)"+date.getMinutes()+"分"+date.getSeconds()+"秒");}原理:通過(guò)訪問(wèn)http://www.bjtime.cn網(wǎng)站來(lái)獲取
這里還為大家提供另外一種方式:通過(guò)網(wǎng)絡(luò)或者GPS的方式。
代碼如下:
LocationManager locMan = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE);//獲取最近一次知道的時(shí)間long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();或者實(shí)時(shí)的獲取時(shí)間:locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); //獲取當(dāng)前時(shí)間當(dāng)我們使用requestLocationUpdates時(shí),我們需要實(shí)現(xiàn)LocationListener接口。在LocationListen的回調(diào)onLocationChanged當(dāng)中獲取時(shí)間@Overridepublic void onLocationChanged(Location location) {// TODO Auto-generated method stublong time = location.getTime();Date date = new Date(time);System.out.println(time + " NETWORK_PROVIDER " + date);// System.out.println(STANDARD_TIME + " ");}@hnrainll更多關(guān)于Android開(kāi)發(fā)相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開(kāi)發(fā)入門與進(jìn)階教程》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選