zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    二维数组展示到DataGridView(c#)
    发送请求获取响应内容(c#)
    重建freescale 4.6.2 multilib toolchain
    [raspberry pi3] raspberry 充当time machine
    sublime ctags
    lua遍历文件
    pthread中如何追踪stack over flow
    Core Dump
    2 plan team 服务器搭建
    mac上编译 arm linux gnueabi交叉编译工具链toolchain
  • 原文地址:https://www.cnblogs.com/hnrainll/p/3070407.html
Copyright © 2011-2022 走看看