And*_*oid 9 android handler runnable
我需要一点帮助,每秒从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));
}
});
}
};
Run Code Online (Sandbox Code Playgroud)
我尝试handler.postDelayed(runnable, 1000);过onCreate(),但是runnable永远不会开始.或者即使我尝试过runnable.run();,它仍然无法正常工作.
任何想法我怎么能开始runnable/handler并每秒更新一次ui?
War*_*ith 28
为什么要在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);
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你想更新你的用户界面,我认为这是最好的选择
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do your work
}
},500);
Run Code Online (Sandbox Code Playgroud)