首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。