Android - Network Date/Time

旧巷老猫 提交于 2019-12-01 08:37:26
Sean Barbeau

GPS or Network timestamp can be retrieved by using the LocationListener in the Android Location API.

See the open-source GPSTest project for a fully working example: https://github.com/barbeau/gpstest

You can request to listen to either Network location updates:

lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

or GPS location updates:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

Then, when a location is passed into the LocationListener.onLocationChanged method, you can read the timestamp from that location:

@Override
public void onLocationChanged(Location location) {
    Log.i("Timestamp", "New timestamp: " + location.getTime());
}

Another option is to make a request to a Network Time Protocol (NTP) server, which is completely independent of the device and cell network.

See this post for details on implementing an NTP client:

use of ntp service

 public static final String TIME_SERVER = "time-a.nist.gov";
 public static void printTimes() throws IOException {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        //long returnTime = timeInfo.getReturnTime();   //local device time
        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time

        //Get Current Time
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();
        Log.e("After get PrintTime..","After get PrintTime..>>"+ts);

    enter code here
        Log.e("getCurrentNetworkTime", "Time from " + TIME_SERVER + ": " + returnTime/*time*/);

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!