We know that system. currenttimemillis () can be used to obtain the current system time. We can start a thread and send messages through handler to update the system time displayed on textview in real time.
We start a thread and the thread sends a message every second. We can update the time displayed on textview in the message.
First, we put a textview in the layout file to display the time, as shown below:
<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: Background = "@ Android: color/White">
<Textview
Android: Id = "@ + ID/mytime"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: gravity = "center"
Android: textcolor = "@ Android: color/Black"
Android: textsize = "36sp"/>
</Linearlayout>
The main idea is to write a thread with infinite loops in the thread, send a message every second, process the message in the main thread and update the time.
Code of the entire activity:
Import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. annotation. suppresslint; import android. app. activity; import android. text. format. dateformat; import android. widget. textview; public class testactivity extends activity {private textview tvtime; @ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); tvtime = (textview) findviewbyid (R. id. mytime); New timethread (). start (); // start a new thread} class timethread extends thread {@ override public void run () {do {try {thread. sleep (1000); message MSG = new message (); MSG. what = 1; // message (an integer value) mhandler. sendmessage (MSG); // sends an msg to mhandler} catch (interruptedexception e) {e. printstacktrace () ;}while (true );}}
// Process the message in the main thread and update the UI. Private handler mhandler = new handler () {@ override public void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case 1: Long using IME = system. currenttimemillis (); charsequence policimestr = dateformat. format ("HH: mm: SS", systime); tvtime. settext (systimestr); // Update Time
Break;
Default:
Break;
}}};}