Jake Wilson
Jake Wilson

Reputation: 91193

Android - Thread.sleep and Handler.postDelayed() freezes animated UI elements

In my activity, my app downloads a list of something from a website via an Http Connection. Before this list of things is displayed on the screen, I have a Loading... TextView with a little spinning ProgressBar to indicate that the data is currnetly being downloaded.

I noticed, that if I do any type of Thread.sleep() during the process of fetching the data from the web, it freezes the spinning ProgressBar.

Even if I put the method in it's own Handler Runnable so that it's on it's own thread, the animation freezing still occurs.

Is there anything I can do about this?

Upvotes: 1

Views: 3845

Answers (3)

Jatin
Jatin

Reputation: 31724

The reason for such a behaviour is that: When you do thread.sleep() inside a runnable, it is the UI thread which executes that runnable rather than the respective other thread which you created. Basically what happens is that when you post any runnable through the handler of the UI thread, UI thread will poll from its queue and execute the runnable; in this case the runnable will do sleep.

Hence no change in progress bar

Upvotes: 1

Dori
Dori

Reputation: 18413

Any application should do long running tasks on a seperate thread to the UI thread as any blocking calls will not allow the UI to update.

As the other poster said, using Runnables alone do not mean the code will be executed on a seperate thread. In this case the run() method will execute on whatever thread your Handler object was created on. Either subclass Thread or pass your runnabe to new thread object with public Thread (Runnable runnable).

Using AsyncTasks, Loaders or Threads will help.

Also read Designing for Responsiveness and Multithreading For Performance. Following the above approaches will help you avoid ANRs

Upvotes: 1

Reuben Scratton
Reuben Scratton

Reputation: 38707

Yes, use AsyncTask.

A Handler is usually attached to the UI thread. Posting Runnables to it doesn't change the fact that they will run on the UI thread.

Upvotes: 2

Related Questions