0

I need to toggle a image from red to yellow after 10 second and to green 3 seconds after clicking a button.
Images are "drawable" with three image stored into imgesView1 array.

The image is supposed to change its state into yellow after threadSleep 10 second and but when all communication is over with the server it changes to green state which is to come after yellow.

Here is my code.

new SendCommandRequest().execute(parameterForURL);
   try{Thread.sleep(10000);}
   catch (InterruptedException ie){}
   imageView1.setImageResource(images1[1]);
     switch(result1) {
       case "1":
         new SendCommandRequest().execute(parameterForURL);
         imageView1.setImageResource(images1[1]);
         try{Thread.sleep(3000);}
         catch (InterruptedException ie){}
         imageView1.setImageResource(images1[1]);

enter image description here

All tasks are done on a single button click.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Md . Sojib Ahmed
  • 431
  • 4
  • 14

1 Answers1

0

Try not to use Thread.sleep, use a CountDownTimer or a Runnable and Handler.postDelayed: https://developer.android.com/reference/android/os/CountDownTimer.html how to use postDelayed() correctly in android studio?

Ameer Taweel
  • 949
  • 1
  • 11
  • 37
  • I need to freeze the UI for particular second. that is why i can not use countdown timer or runable as both are parallel processing task. – Md . Sojib Ahmed Dec 09 '17 at 07:50
  • 1
    Why do you need to freeze it? – Ameer Taweel Dec 09 '17 at 07:50
  • because on first hit to the server it gives a command to do some task to the Microcontroller. But the Microcontroller responds after 8second. For some decision i need the last return. that is the problem – Md . Sojib Ahmed Dec 09 '17 at 07:53
  • 1
    If so, use an `AsyncTask`, it's perfect for long time tasks. – Ameer Taweel Dec 09 '17 at 07:55
  • actually for server communication i am using asyncTask. but i set network connection time 3 second. is that the main problem – Md . Sojib Ahmed Dec 09 '17 at 07:59
  • Yes, I think you should first send the request, at the same time use a `CountDownTimer` to change status to yellow after 10 seconds, when the final result returns, you change the status to green. – Ameer Taweel Dec 09 '17 at 08:11