Android編程獲取網(wǎng)絡時間實例分析
更新時間:2016年01月19日 08:49:13 作者:Leo Chin
這篇文章主要介紹了Android編程獲取網(wǎng)絡時間,結合實例形式對比分析了Android通過訪問網(wǎng)絡及通過GPS獲取網(wǎng)絡時間的具體步驟與實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了Android編程獲取網(wǎng)絡時間的方法。分享給大家供大家參考,具體如下:
在網(wǎng)上看到的最常見的方式有:
public static void main(String[] args) throws Exception { URL url=new URL("http://www.bjtime.cn");//取得資源對象 URLConnection uc=url.openConnection();//生成連接對象 uc.connect(); //發(fā)出連接 long ld=uc.getDate(); //取得網(wǎng)站日期時間 Date date=new Date(ld); //轉換為標準時間對象 //分別取得時間中的小時,分鐘和秒,并輸出 System.out.print(date.getHours()+"時"+date.getMinutes()+"分"+date.getSeconds()+"秒"); }
原理:通過訪問http://www.bjtime.cn網(wǎng)站來獲取
這里還為大家提供另外一種方式:通過網(wǎng)絡或者GPS的方式。
代碼如下:
LocationManager locMan = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE); //獲取最近一次知道的時間 long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime(); 或者實時的獲取時間: locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); //獲取當前時間 當我們使用requestLocationUpdates時,我們需要實現(xiàn)LocationListener接口。 在LocationListen的回調onLocationChanged當中獲取時間 @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub long time = location.getTime(); Date date = new Date(time); System.out.println(time + " NETWORK_PROVIDER " + date); // System.out.println(STANDARD_TIME + " "); } @hnrainll
更多關于Android開發(fā)相關內容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進階教程》
希望本文所述對大家Android程序設計有所幫助。
相關文章
Android使用開源組件PagerBottomTabStrip實現(xiàn)底部菜單和頂部導航功能
這篇文章主要介紹了Android使用PagerBottomTabStrip實現(xiàn)底部菜單和頂部導航功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08Android WebView交互傳遞json字符串并解析的方法
這篇文章主要給大家介紹了關于Android中WebView交互傳遞json字符串并解析的相關資料,文中通過示例代碼介紹的非常詳細,對各位Android開發(fā)者具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-05-05