In project development, it is often necessary to fulfill our project requirements through time-lapse loading. So how to implement the delay, the following combination of Java and Android-related methods to implement the delay problem.
I. using the thread's Sleep method
<span style= "Font-family:microsoft yahei;font-size:18px;" ><span style= "White-space:pre" ></span>new Thread (New Runnable () {@Overridepublic void Run () {//TODO Auto-generated method Stubtry {thread.sleep (+); myhandler.sendemptymessage (what);//Handle main thread methods} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}); </span>
Two. using timer and timertask delay timer
<span style= "Font-family:microsoft yahei;font-size:18px;" ><span style= "White-space:pre" ></span>//1. Instantiate Timertimer timer = new timer ();//2. Instantiate timertasktimertask TimerTask = new TimerTask () {@Overridepublic void Run () {//TODO auto-generated Method stub}};//3. Kai Dynamic Timer/** * task:the task to schedule. * Delay:amount of time in milliseconds before first execution. * Period:amount of time in milliseconds between subsequent executions */timer.schedule (timertask, delay, period);//4. Close Timer if (timertask! = null) {Timertask.cancel (); timertask = null;} 5. Re-enable timer, need to re-instantiate timertask = new TimerTask () {@Overridepublic void Run () {//TODO auto-generated method Stub}};timer.sc Hedule (TimerTask, delay, period);</span>
3. using the handler message processing from Android
<span style= "Font-family:microsoft yahei;font-size:18px;" >/** * delaymillis:the delay (in milliseconds) until the Runnable would be executed. */new Handler (). postdelayed (New Runnable () {@Overridepublic void Run () {//TODO auto-generated Method stub}}, Delaymillis );</span>
4.Schduleexecutorservice Interface processing delay iterations
<span style= "Font-family:microsoft yahei;font-size:18px;" ><span style= "White-space:pre" ></span>/** * Scheduledexecutorservice provides the ability to perform tasks on a schedule, which provides methods that include: * Schedule (Task,initdelay): Schedule the submitted callable or runnable task to execute after the specified time in Initdelay. * Scheduleatfixedrate (): Schedule the submitted runnable task to repeat at specified intervals * Schedulewithfixeddelay (): Schedule the submitted runnable task after each execution, Waits for the time specified by delay to execute repeatedly. * * Initialdelay:the time to delay first execution * Period:the period between successive executions * unit:the time U NIT of the InitialDelay and period parameters *///1. Instantiating Scheduledexecutorservice schedule = Executors.newscheduledthreadpool (2);//2. Turn on timed loop iterative processing schedule.scheduleatfixedrate (new Runnable () {@Overridepublic void Run () {//TODO auto-generated Method stub}}, InitialDelay, period, unit),//3. Close if (schedule! = null) {Schedule.shutdow n (); schedule = null;} </span>