Android programming to obtain network time example analysis
- 2021-01-14 06:34:34
- OfStack
This article illustrates the Android programming method to obtain network time. To share with you for your reference, as follows:
The most common ways to see it online are:
public static void main(String[] args) throws Exception {
URL url=new URL("http://www.bjtime.cn");// Getting the resource object
URLConnection uc=url.openConnection();// Generate connection objects
uc.connect(); // A connection
long ld=uc.getDate(); // Get the date and time of the site
Date date=new Date(ld); // Convert to a standard time object
// Gets the hours, minutes and seconds of the time, respectively, and outputs them
System.out.print(date.getHours()+" when "+date.getMinutes()+" points "+date.getSeconds()+" seconds ");
}
Principle: by accessing http: / / www bjtime. cn website to obtain
Here's another way to do it: via the Internet or GPS.
The code is as follows:
LocationManager locMan = (LocationManager) this.getSystemService(MainActivity.LOCATION_SERVICE);
// For the recent 1 The last known time
long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();
Or the real-time acquisition time:
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); // Get the current time
When we use requestLocationUpdates When we need to implement LocationListener Interface.
in LocationListen The callback onLocationChanged Get the time in the middle
@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
For more information on Android development, please check out the Android Introduction and Advanced Course.
Hope this article described to everyone Android program design is helpful.