实际上,我设计了一个单独的Timer类,带有处理程序,用于在textview上显示分钟和秒。这工作正常,因为我已经调试它和处理程序将reaise句柄但文本视图没有得到更新pl帮助我在这方面。 我正在为Timer Class标记下面的代码。 提前谢谢。
public class Timer
{
private int _interval;
public int getInterval()
{
return _interval;
}
public void setInterval(int delay)
{
_interval = delay;
}
private Handler handler;
private Runnable _tickHandler;
private Runnable delegate;
private boolean ticking;
public boolean getIsTicking()
{
return ticking;
}
public Timer(int interval)
{
_interval = interval;
handler = new Handler();
}
public Timer(int interval, Runnable onTickHandler)
{
_interval = interval;
setOnTickHandler(onTickHandler);
handler = new Handler();
}
public void start(int interval, Runnable onTickHandler)
{
if (ticking) return;
_interval = interval;
setOnTickHandler(onTickHandler);
handler.postDelayed(delegate, _interval);
ticking = true;
}
public void start()
{
if (ticking) return;
handler.postDelayed(delegate, _interval);
ticking = true;
}
public void stop()
{
handler.removeCallbacks(delegate);
ticking = false;
}
public void setOnTickHandler(Runnable onTickHandler)
{
if (onTickHandler == null) return;
_tickHandler = onTickHandler;
delegate = new Runnable()
{
public void run()
{
if (_tickHandler == null) return;
_tickHandler.run();
handler.postDelayed(delegate, _interval);
}
}
;
}
}
及以下是我用于更新文本视图的代码
Timer tmr = new Timer(100,new Runnable()
{
public void run()
{
long millis = System.currentTimeMillis() - mStartTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
lblDevOnOff.setText("");
lblDevOnOff.setText(String.format("%d:%02d", minutes,seconds));
}
}
);
tmr.start();
答案 0 :(得分:1)
将此代码放入
handler
或runOnUIThread()
类似这样的内容
runOnUIThread(new Runnable(){
public void run(){
lblDevOnOff.setText("");
lblDevOnOff.setText(String.format("%d:%02d", minutes,seconds));
}
})
你应该这样做,因为任何与UI相关的东西都应该只在UI Thread上运行......
答案 1 :(得分:0)
是的,这是来自Android Dev Guide:
因此,Android的单线程模型只有两个规则:
- 不要阻止UI线程
- 不要从UI线程外部访问Android UI工具包