How to pause / sleep thread or process in Android?

后端 未结 12 875
故里飘歌
故里飘歌 2020-11-22 05:49

I want to make a pause between two lines of code, Let me explain a bit:

-> the user clicks a button (a card in fact) and I show it by changing the background of thi

相关标签:
12条回答
  • 2020-11-22 06:43

    I use CountDownTime

    new CountDownTimer(5000, 1000) {
    
        @Override
        public void onTick(long millisUntilFinished) {
            // do something after 1s
        }
    
        @Override
        public void onFinish() {
            // do something end times 5s
        }
    
    }.start(); 
    
    0 讨论(0)
  • 2020-11-22 06:45

    Or you could use:

    android.os.SystemClock.sleep(checkEvery)
    

    which has the advantage of not requiring a wrapping try ... catch.

    0 讨论(0)
  • 2020-11-22 06:48

    You probably don't want to do it that way. By putting an explicit sleep() in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.

    Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.

    Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.

    0 讨论(0)
  • 2020-11-22 06:50

    If you use Kotlin and coroutines, you can simply do

    GlobalScope.launch {
       delay(3000) // In ms
       //Code after sleep
    }
    

    And if you need to update UI

    GlobalScope.launch {
      delay(3000)
      GlobalScope.launch(Dispatchers.Main) {
        //Action on UI thread
      }
    }
    
    0 讨论(0)
  • 2020-11-22 06:50

    I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...

    new CountDownTimer(30000, 1000) {
    
        public void onTick(long millisUntilFinished) {
            mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        }
    
        public void onFinish() {
            mTextField.setText("done!");
        }
    }.start();
    

    https://developer.android.com/reference/android/os/CountDownTimer.html

    Hope this helps someone...

    0 讨论(0)
  • 2020-11-22 06:52

    I use this:

    Thread closeActivity = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(3000);
          // Do some stuff
        } catch (Exception e) {
          e.getLocalizedMessage();
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题