Android-the method of acquiring network time, obtaining time and time synchronization of a particular time zone _android

Source: Internet
Author: User
Tags current time set time time and date time limit

Recently sorted out the android-to get the network time, to obtain a specific time zone, time synchronization method. Specifically as follows:

Method One:

SimpleDateFormat DFF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 
Dff.settimezone (Timezone.gettimezone ("gmt+08")); 
String ee = dff.format (new Date ());

This method gets a 24-hour result, and the month is correct.

This method does not change with the change of mobile phone time. In other words, even if the phone is set to another time zone, not East Eight, this method returns is also the Beijing time!!! This is the way I used to do the project!! Completely solve the project needs!

Method Two:

Calendar calendar = Calendar.getinstance ();
SimpleDateFormat SDF = new SimpleDateFormat ("dd-mmm-yyyy hh:mm:ss");
Sdf.settimezone (Timezone.gettimezone ("gmt+8"));
String RT = Sdf.format (Calendar.gettime ());

This method obtains the result is not 24 hours system, the month also is correct.

Method Three:

public static string getlocaldatetimestring (String local) { 
  Calendar cal = new GregorianCalendar ( Timezone.gettimezone (local)); 
  Cal.settimeinmillis (Calendar.getinstance (). Gettimeinmillis ()); 
  String date = Cal.get (calendar.year) + "-" + (Cal.get (calendar.month) + 1) + "-" + cal.get (calendar.day_of_month); 
  String time = Cal.get (calendar.hour_of_day) + ":" + cal.get (Calendar.minute) + ":" + cal.get (calendar.second); 
  Return date + "" + Time; 
} 

Method call:

 
 

The code also sees that this adds a 1, 24-hour system to the month.

The above three methods are validated as follows:

Import Java.sql.Time;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.GregorianCalendar;


Import Java.util.TimeZone;
    public class Timetest {/** * @param args */public static void main (string[] args) {method1 ();
    Method2 ();
  Method3 (); 
    The static void Method1 () {SimpleDateFormat DFF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 
    Dff.settimezone (Timezone.gettimezone ("gmt+08"));
    String ee = dff.format (new Date ());
  System.out.println ("ee=" +ee);
    } static void Method2 () {Calendar calendar = calendar.getinstance ();
    SimpleDateFormat SDF = new SimpleDateFormat ("dd-mmm-yyyy hh:mm:ss");
    Sdf.settimezone (Timezone.gettimezone ("gmt+8"));
    String RT = Sdf.format (Calendar.gettime ());
  System.out.println ("Timetest.method2 () rt=" +rt);
    static void Method3 () {String local = ' gmt+8 '; 
    Calendar cal = new GregorianCalendar (timezone.gettimezone (local)); Cal.settimeinmillIs (Calendar.getinstance (). Gettimeinmillis ()); 
    String date = Cal.get (calendar.year) + "-" + (Cal.get (calendar.month) + 1) + "-" + cal.get (calendar.day_of_month); 
    String time = Cal.get (calendar.hour_of_day) + ":" + cal.get (Calendar.minute) + ":" + cal.get (Calendar.second);
  System.out.println ("timetest.method3 () date=" +date+ ", time=" +time);

 }

}

The results are as follows:

I am using the first method, because the first method of time is not with the phone time to change the settings.

The second method is also possible, but the time is 12.

The fourth method:

There is also a way to get time on the Internet:

URL url=new url ("http://www.bjtime.cn");//Get Resource object
    urlconnection uc=url.openconnection ();//Generate Connection object
    Uc.connect (); Issue Connection
    long ld=uc.getdate ()///Get web site date time
    date=new date (LD);//Convert to Standard Time object
    //////time, minutes and seconds respectively, and output
    System.out.print (date.gethours () + "Time" +date.getminutes () + "Min" +date.getseconds () + "seconds");

This approach requires opening a thread to get time, and there is a risk that the problem of not getting the response is due to network problems. Another important problem is that the acquisition of this time will change as the mobile time zone changes.

Method Five:

Through the network or GPS way.

Code:

Locationmanager Locman = (locationmanager) this.getsystemservice (mainactivity.location_service);
Gets the last known time
long networkts = Locman.getlastknownlocation (Locationmanager.network_provider). GetTime ();

or real-time acquisition time:

Locman.requestlocationupdates (locationmanager.network_provider, 0, 0, this); Get current time

When we use requestlocationupdates, we need to implement the Locationlistener interface.

Get time in Locationlisten's callback onlocationchanged

@Override public
void onlocationchanged (Location Location) {
//TODO auto-generated a stub
long time = l Ocation.gettime ();
Date date = new Date (time);
System.out.println (Time + "Network_provider" + date);
System.out.println (Standard_time + "");
}

This approach is to use the mobile phone positioning system for time acquisition, but this method will change with the mobile phone set time zone changes.

The fourth and fifth way, I have been on the phone side of the verification, you can get the normal time. The way is no problem.

Since there are so many ways, people look at that way to suit their needs, choose the appropriate method.

I still recommend the first Method! Simple and practical!!!! ^_^

Today, I will add some content to the foundation of this article. Now my project has such a demand: is the time to play the video, especially the monitoring video, I want to have the time limit, in a certain period of time can be viewed, beyond the set time, can not watch.

Android side of this demand, the above several methods are not, because the above methods are related to the mobile phone system, when I change the time of the mobile phone system, time zone, etc. will cause the time does not correspond to the server time is wrong. What do we do? There are ways to!!!

That's what I did. When the information, such as video node information, the server with the current time to return to the server, with the time of the server, the rest of me to take advantage of the user operation of the time interval, plus the server time is not the location of the mobile phone is the current time?

What about the time interval? Take a look at the following Systemclock classes in several ways:

1, System.currenttimemillis () is a standard "wall" clock (time and date), representing the number of milliseconds from the era to the present. The wall clock can be set by a user or telephone network (see Setcurrenttimemillis (Long)), so the time may jump forward or backward unpredictably. The clock should only be used when the real world's corresponding date and time are important situations, such as a calendar or alarm clock application. The time interval and elapsed time should use a different clock. If you use System.currenttimemillis (), you can consider listening to ACTION for Action_time_tick, action_time_changed, action_timezone_changed Radio to listen for time changes.

2, Uptimemillis () indicates the start count, in milliseconds, from the system startup. Returns the period of inactivity from the system boot to the current process. The clock stops when the system goes into deep sleep (the CPU shuts down, the device turns black, and waits for an external input device). But the clock will not be adjusted by the clock, idle or other energy-saving machine impact. This is the basic point for most of the time intervals, such as Thread.Sleep (Millls), object.wait (Millis), and System.nanotime (). The clock is guaranteed to be monotonous and is suitable for detecting intervals that do not contain hibernation. Most methods accept a timestamp value except for the Uptimemillis () clock.

3. Elapsedrealtime () and Elapsedrealtimenanos () returns the time when the system was started, including the depth of the device sleep. The clock is guaranteed to be monotonous, even if the CPU is in power-saving mode, the time will continue to be timed. The clock can be used when the measurement time interval may span the system sleep time period.

There are several mechanisms to control when an event occurs:

1, Standard methods like Thread.Sleep (Millis) and object.wait (Millis) are always available, these methods use the Uptimemillis () clock, if the device into a deep sleep, the remaining time will be postponed until the system wakes up. These synchronization methods may be interrupted by Thread.Interrupt () and you must handle interruptedexception exceptions.

2, Systemclock.sleep (Millis) is a practical method similar to Thread.Sleep (Millis), but it ignores interruptedexception exceptions. The delay generated by using this function is if you do not use Thread.Interrupt (), because it saves the interrupt state of the thread.

3. Handler can set asynchronous callbacks at a relative or absolute time, handler class objects also use the Uptimemillis () clock and require a loop (often appearing in GUI programs).

4. Alarmmanager can trigger one or more occurrences, even if the device is deeply dormant or the application is not running. The event can optionally set the time with Currenttimemillis or Elapsedrealtime () (elapsed_realtime), which triggers a broadcast when the event occurs.

Method:

1, public static long Currentthreadtimemillis () the number of milliseconds to run on the current thread.

2. The public static long Elapsedrealtime () returns the number of milliseconds that the system started to now, including the sleep time.

3. The public static long Elapsedrealtimenanos () returns the number of nanoseconds that the system started to now, including the sleep time.

4, public static Boolean Setcurrenttimemillis (Long Millis) sets the current "wall" time, requiring the calling process to have permission. Returns whether successful.

5. public static void sleep (long ms) waits for a given time. Similar to Thread.Sleep (Millis), but it does not throw interruptedexception exceptions. The event was deferred to the next interrupt operation. The method does not return until the specified time passes.

6. The public static long Uptimemillis () returns the number of milliseconds that the system started to now, and does not contain hibernation time. This means that the statistical system has been activated to the current non dormant period of time.

We'll see how these methods look.

The rest is to calculate the event interval:

public static long Elapsedrealtime () returns the number of milliseconds that the system started to now, including the sleep time

This method calculates the time interval from the time the server returns to the user action and plays the video. Can you do this without the time limit of the mobile phone system?

/**
   * * 
   @param ts form yyyy-mm-dd hh:mm:ss
   * @param intervaltime Long type
   * @return String HH:mm:ss
   */
    @SuppressLint ("SimpleDateFormat") public
  static String getTime (String ts,long intervaltime) {
    SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");
    Timestamp T=null;
    String tt= "";
      try {
      t = new Timestamp (format.parse (TS). GetTime ());
      Long SS = T.gettime ();
      Long st = Ss+intervaltime;
      tt= GetTime (ST);
    catch (Java.text.ParseException e) {
      e.printstacktrace ();
    }
    return TT;
  }
  /**
   * @param mis
   * @return HH:mm:ss
  /@SuppressLint ("SimpleDateFormat") public
  static String getTime (long mis) {
    SimpleDateFormat DFF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    String ee = dff.format (new Date (mis));
    Return ee.substring (one);
  

In the above method, the TS parameter is the current time that the server returns, like the string intervaltime parameter of Yyyy-mm-dd Hh:mm:ss, which is to obtain the time interval that the server responds to the user to operate, and is to use the above Elapsedrealtime () Method obtained by two times of time calculation.

method returns a string, such as HH:MM:SS, so that it is convenient to compare time characters. Due to the video event limit, is the time and minutes, it is not possible to relate to the date, so here is the direct return minutes and seconds.

With this approach, it's a perfect solution to the Android app's need to stay in line with server time. However, there are some problems, because the server return time is uncertain, may be long and short, so the time does not and the server's current time is not bad, there will always be delay, but this delay can be accepted, probably up to 10 seconds or so. You can add a little bit to the time interval. Basically meet the demand.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.