Description: This is a prototype of a class of timing functions, used to run some timed services in a background thread, such as timing modification time
Knowledge Points:
1. Android multi-threaded message communication (handler)
2. Acquisition of time in Java, and formatting of string (SimpleDateFormat)
3. The regular implementation of Android Postdelay
4. TimerTask for regular updates
Here we are for handler method, open a new thread every 3 seconds, used to modify a textview time periodically. For TimerTask, the truth is the same, call the schedule method, updated every three seconds.
1. How to use handler:
protected voidUpdateclock2time (Boolean isChecked) {if(isChecked) {updatecurrenttime=NewThread () {@Override Public voidrun () {SimpleDateFormat formatter=NewSimpleDateFormat ("HH:mm:ss"); Date curdate=NewDate (System.currenttimemillis ()); String currenttime=Formatter.format (curdate); Message=handler.obtainmessage (UPDATE_MY_TV, currenttime); Handler.sendmessage (message); //Use Handler to control the timeHandler.postdelayed ( This, the); } }; Updatecurrenttime.start (); } Else{handler.removecallbacks (updatecurrenttime); } }
@SuppressLint ("Handlerleak") PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Caseupdate_my_tv:string currenttime=(String) msg.obj; Clock2.settext ("Current time :"+currenttime); Break; } } };
2. How to use TimerTask:
class Mytimertask extends TimerTask { @Override public void run () {simpledateformat format = new SimpleDateFormat (
"
hh:mm:ss
"
); Date Date =
new
date (); CTime =
Format.format (date); Messagehandler.sendmessage (Messagehandler.obtainmessage ()); } };
private Handler messagehandler = new Handler () {@Override public void Handlemessage (Message msg) { Clock1.settext ( current Time: Span style= "color: #800000;" > " + CTime); Super.handlemessage (msg); } };
protected void Updateclock1time (boolean isChecked) { if (isChecked) { new Timer (); New Mytimertask (); the the ); Else { timer.cancel (); } }
Android background thread, timertask implement regular update time