我需要一点帮助,每秒都从Runnable / Handler更新我的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永远不会启动。或者即使我尝试使用runnable.run();
,它仍然无效。
任何想法如何开始runnable / handler并每秒更新一次ui?
答案 0 :(得分:27)
为什么要在runnable中创建runnable?
试试这个:
// flag that should be set true if handler should stop
boolean mStopHandler = false;
Runnable runnable = new Runnable() {
@Override
public void run() {
// do your stuff - don't create a new runnable here!
if (!mStopHandler) {
mHandler.postDelayed(this, 1000);
}
}
};
// start it with:
mHandler.post(runnable);
答案 1 :(得分:3)
如果您想更新您的用户界面,我认为这是最佳选择
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do your work
}
},500);