Android Handler Timer TimerTask combination to implement timed UI refreshing and androidtimertask
Code implements a small timer
Format similar to 00: 01: 00
Import java. util. timer; import java. util. timerTask; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. textView; public class MainActivity extends Activity {TextView textView; Timer timer; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. text); timer = new Timer (); timer. schedule (task, 1000,1000);} final Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case 1: textView. setText (msg. obj. toString (); break;} super. handleMessage (msg) ;}}; long time = 0; TimerTask task = new TimerTask () {@ Override public void run () {Message msg = new Message (); msg. what = 1; msg. obj = formatElapsedTime (time); time ++; handler. sendMessage (msg) ;}};/*** format the output time String * @ param elapsedSeconds * @ return */public static String formatElapsedTime (long elapsedSeconds) {long hours = 0; long minutes = 0; long seconds = 0; if (elapsedSeconds> = 3600) {hours = elapsedSeconds/3600; elapsedSeconds-= hours * 3600;} if (elapsedSeconds> = 60) {minutes = elapsedSeconds/60; elapsedSeconds-= minutes * 60;} seconds = elapsedSeconds; StringBuilder sb = new StringBuilder (); sb. append (addZeroIfNeed (hours); sb. append (":"); sb. append (addZeroIfNeed (minutes); sb. append (":"); sb. append (addZeroIfNeed (seconds); return sb. toString ();}/*** add 0 for processing. If there are less than two digits, add 0 * @ param number * @ return */public static String addZeroIfNeed (long number) {StringBuilder sb = new StringBuilder (); if (number> = 0 & number <= 9) {return sb. append ("0 "). append (number ). toString ();} return sb. append (number ). toString ();}}
No stop processing, for reference only,