Android。如何在处理程序执行一次可运行后停止处理程序

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

编辑:代码现在可以工作了。我最终从 createDialog() 中调用了 loadingIllusionLoader()...

我正在尝试让 'fake' 进度条在用户按下按钮后显示。我希望进度条随机出现 ~ 2000 毫秒,然后出现一个对话框并隐藏进度条(因为它 'loaded')。

有人告诉我尝试使用处理程序,因为 Thread.sleep 锁定了 UI,我真的不想这样做。但是,一旦我执行了下面的代码,它就会运行处理程序的 postDelayed 函数,并且每时每刻都会出现一个新的对话框……处理程序会一遍又一遍地执行自己。我如何停止处理程序。处理程序上的 removeCallbacksAndMessages 函数是一个选项,但我不确定如何完全停止打开对话框。

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

我想你更愿意使用 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);
  }
};

编辑:差点被遗忘:

timer.start();

编辑 2:

看了你的代码后,我建议你这样修改:

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