Question

I have a progress bar set initially INVISIBLE.after clicking a button i want the bar to appear for 5 seconds than disappear. I'm using Thread.sleep(5000) but nothing happen

public void dec(View v) throws InterruptedException{
ProgressBar pbar = (ProgressBar) findViewById(R.id.bar);
pbar.setVisibility(View.VISIBLE);
Thread.sleep(5000);
pbar.setVisibility(View.INVISIBLE);}
Was it helpful?

Solution

Well you're freezing the UI thread by doing that, so one approach would be to create a new Thread, and use a Handler to post back to the UI thread, so that it doesn't get clogged up and can continue drawing.

For instance:

final ProgressBar pbar = (ProgressBar) findViewById(R.id.bar); // Final so we can access it from the other thread
pbar.setVisibility(View.VISIBLE);

// Create a Handler instance on the main thread
Handler handler = new Handler();

// Create and start a new Thread
new Thread(new Runnable() { 
    public void run() {
         try{
             Thread.sleep(5000);
         }
         catch (Exception e) { } // Just catch the InterruptedException

         // Now we use the Handler to post back to the main thread
         handler.post(new Runnable() { 
            public void run() {
               // Set the View's visibility back on the main UI Thread 
               pbar.setVisibility(View.INVISIBLE);
            }
        });
    }
}).start();

And, as Chris suggested below, you should remove any pending messages from the Handler when the Activity is closing to avoid running into an IllegalStateException when trying to run the posted message/Runnable in an Activity that no longer exists:

@Override
public void onDestroy() {
    handler.removeCallbacksAndMessages(null);
    super.onDestroy();
}

OTHER TIPS

You could try creating a runnable and running it on the uithread with runOnUiThread(new Runnable());?

then do the same Thread.sleep(5000);

http://developer.android.com/reference/android/app/Activity.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top