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

更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  2. Android常用Manager
  3. Android的焦点(Focus)问题
  4. android中ListView控件&&onItemClick事件中获取listView传递的数
  5. android shareperfence的存储更改与读取
  6. Android(安卓)获取系统设置参数。
  7. Android(安卓)获取屏幕高宽度,密度,通知栏高度,截图等常用方法
  8. Android:获取APK签名信息 .
  9. Android中的getApplication()、getApplicationContext的区别与用

随机推荐

  1. Android获取屏幕宽高、屏幕密度、手动计
  2. 如何学Android
  3. Android 中 Log 机制详解
  4. Android(安卓)系统(239)---Android(安卓)PM
  5. android market开发者注册上传app应用教
  6. Android不支持web页滚动
  7. Android开机启动
  8. Android 将View 转化为bitmap 图片
  9. android textview 自动链接网址 修改默认
  10. Android 屏幕旋转时保存状态