Search code examples
javaandroidmultithreadingthread-sleep

How to define a thread with condition of "sleep" or not?


I need that as a condition the thread use time (sleep) or not.

For example:

Thread splashTread = new Thread() {
              @Override public void run() {
                  try {
                      if (!internet){
                          sleep(4000);
                      }
                          // do loads

                  } catch  (InterruptedException e) { 
                  } finally {
                      startActivity(new Intent( "MainScreen"));
                      finish(); 
                  } 
              } 

When online, the "progressbar" rises properly and visually. When no internet, going too fast and is not visible, I want the user to see the progressbar few seconds in this case. That's why I tried to use sleep, but it does not work if I enter it on one condition.


Solution

  • Handler handler = new Handler();
    
    Runnable spalshRunnable = new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(YourActivity.class, MainScreen.this));
            finish(); 
        }
    }
    

    inside onCreate:

    handler.postDelayed(spalshRunnable, 3000);