0

I want to set a booleanVariable in my project using delay. So basically I have a boolean variable which is set to true when user touches a button. And after two seconds that boolean variable should be set back to false. So my question is how do I introduce that delay of 2 seconds?

I have following code which DID NOT work-

boolean userTouch;

public void buttonTouched(){//This gets called when user touches the button
  setUserTouch(true);
  try{
  Thread.sleep(2000);
     }catch(Exception e){
  e.printStackTrace;
     }
  setUserTouch(false);
} 

In another method I call getUserTouch() method to see if user has touched the button in past 2 seconds. But that method is always set to false. It's never true. Is there something wrong with my code? should the setUserTouch(true); method be inside the try block? Also is there any other wayI can accomplish my goal? i.e. any other method by which I can introduce 2 second delay. I'm trying out countdown timer now. But I don't know any other method.

supernova
  • 49
  • 1
  • 4
  • Possible Duplicate Question: https://stackoverflow.com/a/15874176/6142219 – Deepak kaku Apr 24 '18 at 21:31
  • Hi Deepak kaku, Handler did not work for me. I don't know which to import. There were multiple options. I tried all and notone of them worked. I also tried import android.os.*. That too did not work. Any other ideas? – supernova Apr 24 '18 at 21:44
  • use the Handler code inside buttonTouched() method. and import android.os.Handler; – Deepak kaku Apr 24 '18 at 21:47
  • Hey, I tried `import android.os.Handler; `. That's not working. The Handler remains red and when I hover over it, android studio say can't resolve the symbol 'handler'. I also cleaned the project and rebuild it. But still same error when trying to add the imports. Android studio suggests a lot of imports for Handler like java.util.logging. But they don't work out – supernova Apr 24 '18 at 21:55
  • that is not possible. Handler is integral part of Android SDK. I don't see why you would have issues importing it. try restarting your android studio. android.os.Handler is the one you're looking for – Deepak kaku Apr 24 '18 at 22:04

1 Answers1

0

How about using Async task manager. You can use thread.sleep command in doInBackGround method of AsyncTask and then use publishProgress method to set the userTouched boolean variable back to false.

Also try following code.

setUserTouched(true);
long DELAY = 2000;

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // code in here will get executed after DELAY variable
        setUserTouched(false);
    }
}, DELAY);
hyperCoder
  • 271
  • 2
  • 13
  • Hi hyper, this is actually not working for me. Because I don't know which handler to import. There are multiple choices and none of them worked out for me. any other ideas? – supernova Apr 24 '18 at 21:43