We open a thread, the thread sends a message every second, and we update the time displayed on the TextView in the message OK.
First we put a textview in the layout file to display the time, as follows:
Copy Code code as follows:
<?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>
Then we write a thread that has an infinite loop inside the thread, sending a message every second, where the handler handles the displayed results:
Copy Code code as follows:
public class Timethread extends Thread {
@Override
public void Run () {
do {
try {
Thread.Sleep (1000);
msg = new Message ();
Msg.what = MsgKey1;
Mhandler.sendmessage (msg);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
} while (true);
}
}
Private Handler Mhandler = new Handler () {
@Override
public void Handlemessage (msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case MsgKey1:
Long systime = System.currenttimemillis ();
Charsequence systimestr = Dateformat.format ("Hh:mm:ss", systime);
Mtime.settext (SYSTIMESTR);
Break
Default
Break
}
}
};
We can then open this thread in the OnCreate method of the activity, when we can see a digital clock:
Copy Code code as follows:
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.time);
Mtime = (TextView) Findviewbyid (r.id.mytime);
New Timethread (). Start ();
}
Code for the entire activity:
Copy Code code as follows:
Package com.fermax.test;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.text.format.DateFormat;
Import Android.widget.TextView;
public class Testactivity extends activity {
private static final int msgKey1 = 1;
Private TextView Mtime;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.time);
Mtime = (TextView) Findviewbyid (r.id.mytime);
New Timethread (). Start ();
}
public class Timethread extends Thread {
@Override
public void Run () {
do {
try {
Thread.Sleep (1000);
msg = new Message ();
Msg.what = MsgKey1;
Mhandler.sendmessage (msg);
}
catch (Interruptedexception e) {
E.printstacktrace ();
}
} while (true);
}
}
Private Handler Mhandler = new Handler () {
@Override
public void Handlemessage (msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case MsgKey1:
Long systime = System.currenttimemillis ();
Charsequence systimestr = Dateformat.format ("Hh:mm:ss", systime);
Mtime.settext (SYSTIMESTR);
Break
Default
Break
}
}
};
}