Java – How do I pause but not get stuck Android execution?

How do I pause but not get stuck Android execution?… here is a solution to the problem.

How do I pause but not get stuck Android execution?

I’m trying to set the background color of an ImageView for a specified amount of time (pause between each color switch) based on a specific condition such as string = “a” or “b”. My problem is that I can’t seem to get the whole app to wait for one change until it moves to the next, so to the user it looks like the color starts and then immediately the last color.

I’ve tried CountDownTimers (which just continues while another timer is running), handlers (postDelayed(null, 5000)), Thread.Sleeps, etc.

Here’s an example of what I’m trying to do:

Set the color of the ImageView to red
hibernate 500ms

for(int i = 0; i < stringArray.length; i++){  
    if(stringCompare = "a") {  
    Set color on ImageView to blue  
    sleep for 500ms }  
else if(stringCompare = "b") {  
    Set color on ImageView to blue  
    sleep for 1000ms  
  }  
Set color on ImageView to red  
sleep for 500ms  
}  

I

know it’s a bit crazy, but I’ve tried everything I can think of above, but haven’t succeeded in getting the program to really wait, but not stopping it completely.

Thank you.

Solution

Over the past two decades, most GUIs have been based on an event-driven model. Some, such as Android, use a single-threaded event-driven model. Your request to change the color does not take effect immediately; Instead, it puts the message into a work queue for processing by the main application thread. The main application thread is also the thread that runs your code, unless you specifically move that code to a background thread.

Therefore, never hibernate on the main application thread. Otherwise, the thread will be occupied and will not be able to handle any kind of GUI event, let alone your request to change the color.

postDelayed() (on View or Handler) will allow you to schedule your code to run on the main application thread in the future, after a delay that does not tie up the main application thread during that delay.

Related Problems and Solutions