簡體   English   中英

Android系統。 一旦執行了可運行對象,如何停止處理程序

[英]Android. How to stop a handler once it executed a runnable once

編輯:代碼現在可以使用。 我最終從createDialog()內調用loadingIllusionLoader()...

我試圖讓“假”進度條在用戶按下按鈕后顯示。 我希望進度條顯示約2000ms的隨機時間,然后出現一個對話框以及隱藏進度條(因為它已“加載”)。

有人告訴我嘗試使用處理程序,因為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();

EDIT2:

查看代碼后,建議您將其修改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM