Timer+TimerTask implements digital clock

Outcome display

Layout

The layout theme background color adopts #000000 (pure black), and the font color of each TextView adopts #FFFFFF (pure white).

Use five TextViews to implement hours: minutes, seconds, am, pm, Sunday, and specific dates.

Default layout

Constraint relationship

For the layout of several TextViews, we rely on a very practical method: Constraint(ConstraintLayout).

  • The default layout, relying on constraints to determine the position

  • Ability to flexibly position and resize interface elements

  • Without any nesting, reduce layout levels and optimize rendering performance

  • Can completely replace other layouts

Through the constraint relationship, component layout will become extremely easy~

Function realization

Use Timer + TimerTask to complete the digital clock, first create several Timer and TimerTask objects.

 Timer htimer = new Timer() //Create an hour-minute timer
 TimerTask hourtask = new TimerTask(){//Create hour-division timing task--sub-thread
     public void run(){
         ...
     }
 };

We use five TextViews in the layout, and we need to use the setText() function to implement the clock, so we need to create TextView objects in TimerTask.

 TextView tv1 = (TextView) findViewById(R.id.hourshow);

And use findViewById to bind components based on id value.

How to get real-time time data? There are two nice date APIs for this.

Calendar class

First, we use the getInstance() function that comes with Calendar to get the instance.

 //Get an instance of the Calendar class:
 private Calendar c = Calendar. getInstance();

Then we can use the get() function to obtain the data we want through the instance c, for example, to obtain the time and division here.

 int hour = c. get(Calendar. HOUR_OF_DAY);
 int minute = c. get(Calendar. MINUTE);

Then the time has been captured by hour and minute, we only need to pass the time to TextView.

 tv1.setText(String.format("d: d",hour,minute));

Note that the data obtained from the Calendar is all int type, and we need to convert it to String type before transmission. Similar to time division, several other data can be completed separately.

But there is an even better API.

SimpleDateFormat class

SimpleDateFormat is a class in Java for formatting dates and times. It provides a way to format dates and times in a specific style, making them better for interacting with a user interface or storing in a database.

We first create a SimpleDateFormat object dateFormat.

 SimpleDateFormat dateFormat = new SimpleDateFormat("HH : mm", Locale.CHINA);

“HH : mm”: This parameter is a string, where HH and mm are parameters that come with the API, HH means to display two-digit hours, mm means to display two-digit minutes;

Locale.CHINA: This parameter is a Locale object, which specifies the formatted locale. Here we choose CHINA, which is the Chinese environment.

Next, we format the current time as a string in am-pm time format using the following statement:

 String currentTime = dateFormat. format(new Date());

In Java, you can use new Date() to create a Date object representing the current time. When this statement is executed, it will call the system clock to get the current time and encapsulate it as a Date object.

Here, we use the format() method of SimpleDateFormat to format a Date object (representing the current time) into a string. This method returns a String object containing a date and time string in the specified format.

Finally, the function can be realized by using the setText function through TextView, so it will not be demonstrated again.

The following are details corresponding to some parameters of the SimpleDateFormat class:

< /table>

Note: uppercase HH 24 hours, lowercase hh 12 hours

TimerTask and runOnUiThread()

We have obtained real-time time data and passed the value to the TextView component in real time, but now we run the code, we will see the date passing by, and our most annoying accident – Flashback .

why?

–Android stipulates that only the main thread can update the UI. The UI cannot be updated directly in the TimerTask thread, but the runOnUiThread method can be called to put a Runnable sub-thread task in the main thread for execution.

So from the beginning, our TimerTask object hourtask left a problem.

 Timer htimer = new Timer() //Create an hour-minute timer
 TimerTask hourtask = new TimerTask(){//Create hour-division timing task--sub-thread
     public void run(){
         ... //Here should write a runOnUiThread() function
     }
 };

Then let’s write a new Runnable() through runOnUiThread.

 TimerTask hourtask = new TimerTask() { //clock
         @Override
         public void run() {
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     TextView tv1 = (TextView) findViewById(R.id.hourshow);
                     SimpleDateFormat dateFormat = new SimpleDateFormat("HH : mm", Locale. CHINA);
                     String currentTime = dateFormat. format(new Date());
                     tv1.setText(currentTime);
                 }
             });
         }
     };

A perfect function is thus written.

Then we only need to complete the use of hourtask in onCreate, which is our most important function.

 protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R. layout. activity_main);
         htimer.schedule(hourtask, 0, 1000);
     }
 htimer.schedule(hourtask, 0, 1000);
 timer.schedule(task, delay, period);

schedule is the scheduling function of Timer, 0 (delay) is to execute an hourtask task after 0 milliseconds, 1000 (period) is after 0 (delay) milliseconds, The hourtask task is executed every 1000 (period) milliseconds, and it is executed multiple times and repeatedly.

Here is after running the program, it starts at 0 milliseconds, and then updates the data every 1 second.

Finally, don’t forget to write an onDestroy() function.

 @Override
     protected void onDestroy() {
         super. onDestroy();
         htimer. cancel();
     }
 }

cancle() can stop the timer.

syntaxbug.com © 2021 All Rights Reserved.
Letter Date/Time Element Indicates Example
G Era Identifier AD
y Year Year 1996; 96
M Month of the year Month July; Jul;07
w Week of the year Number Number 27
W Number of weeks in the month Number 2
D Number of days in the year Number 189
d Number of days in the month Number 10
F week of the month Number 3
E Day of the week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour of the day Number (0-23) 0
k hour of the day Number (1-24) 24
K hour in am/pm Number (0-11) 0
h hour in am/pm Number (1-12) 12
m minute of the hour Number 30
s seconds in minutes Number 55
S Milliseconds Number 978
z Time Zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800