---
title: " Android 获取网络时间"
author: "android_zhang"
date: "2014-03-12T11:42:45Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2014-03-12T11:42:45Z"
id: 2029812
url: "https://android-zhang.iteye.com/blog/2029812"
---

Android 获取网络时间

在网上看到的最常见的方式有：

public static void main(String args) throws Exception {

       URL url=new URL("http://www.bjtime.cn");//取得资源对象

       URLConnection uc=url.openConnection();//生成连接对象

       uc.connect(); //发出连接

       long ld=uc.getDate(); //取得网站日期时间

       Date date=new Date(ld); //转换为标准时间对象

       //分别取得时间中的小时，分钟和秒，并输出

       System.out.print(date.getHours()+"时"+date.getMinutes()+"分"+date.getSeconds()+"秒");

 }
来源：http://blog.sina.com.cn/s/blog_79d3696301015xo9.html

原理：通过访问http://www.bjtime.cn网站来获取

这里还为大家提供另外一种方式：通过网络或者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时，我们需要实现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