示例代码:
1、新线程,定时更新文字
class testThread extends Thread{ public void run() { Message message = new Message(); mHandler.sendMessage(message); } } //在handler中更新UI private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { textView.setText("你想变的内容"); }; }; //启动线程 new testThread().start();
2、定时器,定时更新文字
private final Timer timer = new Timer(); private TimerTask task; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub textView.setText("XXXX"); super.handleMessage(msg); } }; task = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Message message = new Message(); message.what = 1; handler.sendMessage(message); } }; timer.schedule(task, 1000, 1000);
在TimerTask中执行界面相关的代码,比如setText,程序会崩溃。下面这段代码就不能完成更新文字。
TimerTask task = new TimerTask(){ public void run(){ mShortTestNo.setText(" Pass"); } }; Timer timer = new Timer(); timer.schedule(task, 6000);
时间: 2024-10-12 12:46:38