handler.postDelayed()没有停止

时间:2018-07-24 17:31:18

标签: android handler postdelayed

我正在使用handler.postDelayed()更新我的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();
                }
            });

关于如何使其停止的任何想法?

1 个答案:

答案 0 :(得分:0)

现在,您在达到某个限制(stopRepeatingTask())时致电progress == 90。但是在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);
            }
        }
    }
};