在android / java中正确引入延迟

我想使用延迟在我的项目中设置booleanVariable。 所以基本上我有一个布尔变量,当用户触摸按钮时,该变量设置为true。 两秒后,布尔变量应该设置回false。 所以我的问题是如何引入2秒的延迟?

我有以下代码,但没有工作 –

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); } 

在另一种方法中,我调用getUserTouch()方法来查看用户是否在过去2秒内触摸了该按钮。 但该方法始终设置为false。 它永远不会是真的。 我的代码有问题吗? 应该是setUserTouch(true); 方法在try块内? 还有其他任何方式我可以实现我的目标吗? 即我可以引入2秒延迟的任何其他方法。 我现在正在尝试倒数计时器。 但我不知道任何其他方法。

如何使用Async任务管理器。 您可以在AsyncTask的doInBackGround方法中使用thread.sleep命令,然后使用publishProgress方法将userTouched布尔变量设置为false。

也请尝试以下代码。

 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); 
 // activity fields.. private Handler handler; private Runnable myRunnable; // .. some code // in the place where button is defined Button b = ... handler = new Handler(); // since you said "touch" and not "hold", I'll assume it's a normal "click" b.setOnClickListener(this); // here, "this" refers to the activity // somewhere else in the activity private Runnable makeRunnable() { return new Runnable() { @Override public void run() { // yes, this runnable holds a reference to the activity // do some work // setUserTouched(false); // ... // but then should take care of it handler.removeCallbacks(myRunnable); } } } // in onClick switch (v.getId()) { case SOME_ID: setUserTouched(true); myRunnable = makeRunnable(); handler.postDelayed(myRunnable, 2000L); break; } 

虽然活动破坏会导致其字段被破坏,但这是您在runnablehandler位于不同类中时确保避免内存泄漏的方法。