First clarify the concept:
A timer is a class that performs a task, and he accepts timertask parameters;
There are two ways that a timer performs a task, one that executes a task Timer.schedule at a specified time (TimerTask task,data Data) and how long it takes to perform a task Timer.schedule ( TimerTask task,long delay);
TimerTask performs the specified task, but because Android is thread-safe, all interface updates must be placed in the main thread, so the handler object is used.
Android CPU allocation of the smallest unit is a thread, handler is generally created in a line thread, so handler and thread are bound to each other, one by one.
While Runnable is an interface, thread is a subclass of runnable.
Here are some examples of two methods
1 Packagecom.example.test007;2 3 ImportJava.util.Timer;4 ImportJava.util.TimerTask;5 6 Importandroid.app.Activity;7 ImportAndroid.os.Bundle;8 ImportAndroid.os.Handler;9 ImportAndroid.os.Message;Ten ImportAndroid.os.SystemClock; One ImportAndroid.widget.TextView; A - Public classMainactivityextendsActivity { - the PrivateTextView TV; - Private intTime=0; - - Private FinalTimer timer=NewTimer (); +Handler handler=NewHandler () { - @Override + Public voidhandlemessage (Message msg) { A++Time ; at if(Msg.what = = 1){ -Tv.settext ("Handler,timer and Timetask combination method:" +Time ); - } - Super. Handlemessage (msg); - } - }; in - //Initializing Timer tasks toTimerTask task =NewTimerTask () { + @Override - Public voidrun () { the //page updates need to be placed in the main thread because the main thread is secure *Message msg =NewMessage (); $Msg.what=1;Panax Notoginseng handler.sendmessage (msg); - } the }; + @Override A Public voidonCreate (Bundle savedinstancestate) { the Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); -TV =(TextView) Findviewbyid (R.ID.TV1); $ //execute once in 1s $Timer.schedule (Task, 1000, 1000); - } -}
1 Packagecom.example.test007;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 ImportAndroid.os.Handler;6 ImportAndroid.widget.TextView;7 8 Public classTimeactivityextendsActivity {9 PrivateTextView TV;Ten Private intTime=0; One A PrivateHandler Handler =NewHandler (); - PrivateRunnable Runnable =NewRunnable () { - @Override the Public voidrun () { -++Time ; -Tv.settext ("Handler postdelayed (Runnable, Long) method:" +Time ); -Handler.postdelayed ( This, 1000); + } - }; + @Override A protected voidonCreate (Bundle savedinstancestate) { at Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.test); -TV =(TextView) Findviewbyid (r.id.tv); -Handler.postdelayed (runnable, 1000); - - } in -}
Android_timer and runnable two methods of timer