androidhandlerpostdelayed

handler.postDelayed() not stopping


I am updating my UI using the handler.postDelayed() but it is not stopping when I'm wanting it to stop. it keeps updating the 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);

}

The handler is being started from another method:

 Client.this.runOnUiThread(new Runnable() {

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

any idea on how to make it stop?


Solution

  • Right now, you call stopRepeatingTask() on reaching a certain limit (progress == 90). But in the finally block, you unconditionally start the next task. You should only start the new task if the limit has not yet been reached:

    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);
                }
            }
        }
    };