[英]How to run a task every second for 10 seconds.
我有以下代碼每秒運行一個任務,但我也希望任務在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);
使用帶有布爾變量的While循環並將此變量設置為true,那么您可以計算任務運行了多少次,並在每次運行后停止任務1秒鍾,但是可能會延遲1秒鍾而不是1秒鍾由於線程隱藏。
因此,您可以使用時間來計數並停止while循環。 節省您的當前時間,每1秒鍾將執行一次任務。 在線程終止10次之后,可以在while循環中終止線程,也可以將布爾變量設置為false。
為了使用計數器,您可以將其包裝在如下函數中:
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);
如何子類化Handler類並使用此類的實例來跟蹤postDelayed()被調用了多少次呢?
public class MyHandler extends Handler {
private int maxTimes;
private int currentTimes;
private Runnable runner;
public Handler(int maxTimes) {
this.maxTimes = maxTimes;
}
@Override
public void post(Runnable runner) {
this.runner = runner;
}
@Override
public void postDelayed(Runnable runner,long ms) {
if (currentTimes == maxTimes) {
this.removeCallbacks(runner);
} else {
super.postDelayed(runner,ms);
currentTimes++;
}
}
}
mHandler = new MyHandler(10);//using subclass instance
//from here on is the same as the original code.
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.