Jayizzle
Jayizzle

Reputation: 532

Android. How to stop a handler once it executed a runnable once

EDIT: Code works now. I ended up calling loadingIllusionLoader() from within createDialog()...

I am trying to get a 'fake' progress bar to show up once a user presses a button. I want the progress bar to appear for some random time ~ 2000ms and then have a Dialog box appear as well as hiding the progress bar (because it 'loaded').

I was told to try and use handler since Thread.sleep locks up the UI, which I dont want to really do. However, once I execute the code below, it runs the handler's postDelayed function and a new Dialog box appears every moment or so... the handeler is executing itself over and over again. How do I STOP the handler. the removeCallbacksAndMessages function on the handler was an option, but Im not sure how to exactly STOP the Dialog boxes from opening.

public void loadingIllusionLoader()
{
    ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
    theCircleLoader.setVisibility(View.VISIBLE);
    int timeToRest = (int) (Math.random() * 1000) + 1500;

   final Handler newHandle = new Handler();
    newHandle.postDelayed(new Runnable() {
        @Override
        public void run() {
            createDialog();
            hidingIllusionLoader();
            newHandle.removeCallbacksAndMessages(null);

        }
    }, timeToRest);
}

public void hidingIllusionLoader()
{
    ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
    theCircleLoader.setVisibility(View.INVISIBLE);
}

Upvotes: 0

Views: 204

Answers (1)

injecteer
injecteer

Reputation: 20699

I think you'd rather want to use a CountDownTimer:

CountDownTimer timer = new CountDownTimer( 10000, 1000 ) { 
  @Override public void onTick( long millisUntilFinished ) {
    theCircleLoader.setProgress( theCircleLoader.getProgress() - 1 );
  }
  @Override public void onFinish() {
    theCircleLoader.setVisibility(View.INVISIBLE);
  }
};

EDIT: almost forgotten:

timer.start();

EDIT2:

after looking at your code, I suggest you modify it so:

    Random rnd = new Random();
    int progressBarMax = rnd.nextInt( 10 ) + 1; // 10 - change it the way you like
    int timeToRest = progressBarMax * 500;
    theBarLoader.setMax( progressBarMax );
    theBarLoader.setProgress( 0 );

    CountDownTimer theTimer = new CountDownTimer(timeToRest, 500)

    {
        @Override public void onTick( long millisUntilFinished ) {
             theBarLoader.setProgress( theCircleLoader.getProgress() + 1 );
        }
        @Override public void onFinish() {
            theCircleLoader.setVisibility(View.INVISIBLE);
           // theBarLoader.setVisibility(View.INVISIBLE);
            createDialog();
        }
    };
    theTimer.start();

Upvotes: 1

Related Questions