How to pause but not freeze Android execution?

I am trying to set the background color of the ImageView in a certain amount of time (pauses between each color switch) based on certain criteria (such as string = "a" or "b"). My problem is that I can not make the whole application wait for one change until it moves to the next, so for the user it just looks like the color starts, and then the last color.

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

Here is an example of what I'm trying to do:

Set the color in ImageView to red
sleep for 500 ms

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 such a crazy person, but I tried all of the above methods that I could think of without success, actually making the program wait, but not completely stopping it.

Thanks.

+4
source share
3 answers

Put this in your activity (make it an inner class):

 private class ColorChanger extends Thread { final ImageView imageView; public ColorChanger(ImageView imageView) { this.imageView = imageView; } private void changeColor(final int color) { YourActivity.this.runOnUiThread(new Runnable() { public void run() { // Set imageView to color here } }); } @Override public void run() { try { Thread.sleep(500); changeColor(0xffff0000); Thread.sleep(500); changeColor(0xff0000ff); // Etc. } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

Then you can simply do:

 new ColorChanger(/*Your imageview*/).start(); 

Anywhere in your business.

+2
source

Over the past two decades, most graphical interfaces have been based on event driven models. Some, like Android, use a single-threaded event-driven model. Your request for a color change has no immediate effect; rather, it puts the message on the work queue, processed by the main thread of the application. This main thread of applications is also what runs your code, unless you specifically move this code to a background thread.

As a result, never sleep in the main theme of the application. Otherwise, this thread is bound and cannot handle any GUI events, not to mention your request for a color change.

postDelayed() (in View or Handler ) allows you to schedule code to run in the future in the main thread of the application after a delay without binding the main thread of the application during this delay.

+3
source

Create a separate thread that pauses and starts. From the messages in the message stream to the user interface stream, change the color of its image.

+2
source

Source: https://habr.com/ru/post/1343344/


All Articles