我有以下代码每秒运行一个任务,但是我也希望任务在10秒后停止。可以使用我正在使用的处理程序来实现此逻辑吗?我试着用while循环实现一个计数器,但无法正常工作
mHandler = new Handler();
mUpdateUI = new Runnable() {
public void run() {
mVistaInspectionDate = HousingFragment.getVistaInspectionDate();
mVistaInspectionDateTextView.setText(mVistaInspectionDate);
if (mVistaInspectionDate != null) {
mHandler.removeCallbacks(mUpdateUI);
}
mHandler.postDelayed(mUpdateUI, 1000); // 1 second
}
};
mHandler.post(mUpdateUI);
为了使用计数器,您可以将其包装在如下函数中:
private void postDelayedWrapped(final int counter, int delay) {
if (counter <= 0) return;
mUpdateUI = new Runnable() {
public void run() {
mVistaInspectionDate = HousingFragment.getVistaInspectionDate();
mVistaInspectionDateTextView.setText(mVistaInspectionDate);
if (mVistaInspectionDate != null) {
mHandler.removeCallbacks(mUpdateUI); //necessary?
}
postDelayedWrapped(counter - 1, 1000);
}
};
mHandler.postDelayed(mUpdateUI, delay);
}
您可以这样开始:
mHandler = new Handler();
postDelayedWrapped(10,0);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句