首页 > 代码库 > Android Handler Timer TimerTask组合实现定时刷新UI

Android Handler Timer TimerTask组合实现定时刷新UI

代码实现一个小计时器

类似 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);        }    };        /**     * 格式化输出时间字符串     * @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();    }        /**     * 加0处理,不足两位时补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();    }}

 

没有做停止处理,仅供参考、

Android Handler Timer TimerTask组合实现定时刷新UI