我需要每秒从Runnable/Handler更新我的UI的一些帮助。我使用此代码:Android每秒更新处理程序的ui
Runnable runnable = new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
prBar.setProgress(myProgress);
y = (double) ((double) myProgress/ (double) RPCCommunicator.totalPackets)*100;
txtInfoSync1.setText(Integer.toString((int)y) + "%");
prBar.setMax(RPCCommunicator.totalPackets);
int tmp = totalBytesReceived - timerSaved;
Log.w("","totalBytesReceived : "+totalBytesReceived + " timerSaved : "+timerSaved);
Log.w("","tmp : "+tmp);
if (avgSpeedCalc.size() > 10)
{
avgSpeedCalc.remove(0);
}
avgSpeedCalc.add(tmp);
int x = 0;
for (int y=0;y<avgSpeedCalc.size();y++)
{
x += avgSpeedCalc.get(y);
Log.d("","x : "+x);
}
x = Math.round(x/avgSpeedCalc.size());
Log.e("","x : "+x);
timerSaved = totalBytesReceived;
txtSpeed.setText(Integer.toString(x));
}
});
}
};
我handler.postDelayed(runnable, 1000);
在onCreate()
尝试过,但从来没有开始运行的。或者即使我尝试使用runnable.run();
,它仍然无法使用。
任何想法如何启动runnable /处理程序并每秒更新ui?
以及我如何在这之后停止:
试试这个?我的意思是,只有当我通过互联网获取数据时,我才需要运行它,并且我想在活动完成或用户单击取消按钮后停止可运行。 – 2012-02-06 12:24:47
更新了我的答案并引入了一个标志 – WarrenFaith 2012-02-06 12:33:59
实际上'handler.removeCallbacks(runnable);'也在做同样的事情。 – 2012-02-06 12:48:59