handler.postDelayed() 不停

handler.postDelayed() not stopping

我正在使用 handler.postDelayed() 更新我的 UI,但它并没有在我希望它停止时停止。它不断更新 UI.

  int progress = 10;
Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        try {
            Log.d( "","entered run ");
            mWaveLoadingView.setCenterTitle(String.valueOf(progress)+"%");
            mWaveLoadingView.setProgressValue(progress);
            progress+=1;
            if(progress==90)
                stopRepeatingTask();

        } finally {
            // 100% guarantee that this always happens, even if
            // your update method throws an exception
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    }
};

void startRepeatingTask() {
    Log.d( "","entered update ");
    mStatusChecker.run();
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);

}

正在从另一个方法启动处理程序:

 Client.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Log.d( "","entered client ");
                    mHandler = new Handler();
                    startRepeatingTask();
                }
            });

知道如何让它停止吗?

现在,您在达到特定限制 (progress == 90) 时调用 stopRepeatingTask()。但是在 finally 块中,你无条件地开始下一个任务。如果尚未达到限制,您应该只开始新任务:

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        try {
            Log.d( "","entered run ");
            mWaveLoadingView.setCenterTitle(String.valueOf(progress)+"%");
            mWaveLoadingView.setProgressValue(progress);
            progress+=1;
            if(progress==90)
                stopRepeatingTask();

        } finally {
            // 100% guarantee that this always happens, even if
            // your update method throws an exception

            // only if limit has not been reached:
            if(progress<90){
                mHandler.postDelayed(mStatusChecker, mInterval);
            }
        }
    }
};