等待5秒钟

39

我希望在执行另一个公共void方法之前等待5秒钟。线程睡眠对我不起作用。如果有一种不使用Threads的wait()方法,我会很高兴知道。

public void check(){
    //activity of changing background color of relative layout
}

我想在更改相对布局颜色之前等待3秒钟。


1
可能是如何在Android中暂停/休眠线程或进程?的重复问题。 - till
2
@till 根据规定,我检查了这些,但对我没有用,还是谢谢您的考虑 :) - user7320356
1
实际上看不出引用问题的答案和您选择的答案之间的区别... - till
9个回答

96

看看这是否适用于您。确保导入android.os.Handler

      Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    // yourMethod();
                }
            }, 5000);   //5 seconds

或者Kotlin

Handler().postDelayed({
    // yourMethod()
}, 5000)

它会报错,提示Handler是一个抽象类,无法实例化。 - user7320356
我认为这是我的错误,明天我会用清醒的头脑再次检查。 - user7320356
4
使用android.os.Handler处理程序。您当前正在使用日志处理程序,该处理程序没有postDelay方法。您还会收到未初始化的错误,因为您必须实现一些方法以使用日志处理程序。 - Jcorretjer
这个应该是一个答案。 - danyapd

47

只需使用lambda表达式添加一行代码

(new Handler()).postDelayed(this::yourMethod, 5000);

澄清编辑: yourMethod是指您想在5000毫秒后执行的方法。


好的解决方案,速度也很快,但并不适用于所有需求。一个很好的例子是在需要在Adapter中执行/调用活动方法之前等待时。 - danyapd
这是同步还是异步的? - Jitin
1
这并不是真正的等待,它只是在稍后执行一个函数…… - Jitin
1
(new Handler(Looper.getMainLooper())).postDelayed(null, 5000); 因为没有参数的构造函数已经过时,如果您想要等待而不进行任何方法调用,请传递null。 - Raja Nagendra Kumar

13

6

导入方式: import android.os.Handler;

new Handler().postDelayed(new Runnable() {
    public void run() {
        // yourMethod();
    }
}, 5000); // 5 seconds

3

This works for me:

    val handler = Handler()
    handler.postDelayed({
        // your code to run after 2 second
    }, 2000)

1
我喜欢的是:
(new Handler()).postDelayed(this::here is your method,2000);

0
Java 8 中的一行代码。
new Handler().postDelayed(() -> check(), 3000);

这是干净而适合阅读的


0
由于Android 11及以上版本中,Handler类的无参构造函数已被弃用,如果您使用上述代码,将会抛出一个弃用警告:
'Handler()'在API 30(Android 11.0 (R))中已被弃用。
现在,您应该通过Looper.getMainLooper()方法在构造函数中指定Looper,如下所示:
Java
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // Your Code
    }
}, 5000);

Kotlin
Handler(Looper.getMainLooper()).postDelayed({
    // Your Code
}, 5000)

java - Handler()被弃用后我现在该使用什么? - Stack Overflow


-1
我在另一个问题中发布了this answer,但它也可能对你有帮助。
类:
import android.os.Handler;
import android.os.Looper;

public class Waiter {

WaitListener waitListener;
int waitTime = 0;
Handler handler;
int waitStep = 1000;
int maxWaitTime = 5000;
boolean condition = false;

public Waiter(Looper looper, final int waitStep, final int maxWaitTime){

    handler = new Handler(looper);
    this.waitStep = waitStep;
    this.maxWaitTime = maxWaitTime;

}

public void start(){

    handler.post(new Runnable() {
        @Override
        public void run() {

            waitListener.checkCondition();

            if (condition) {

                waitListener.onConditionSuccess();

            } else {
                if (waitTime <= maxWaitTime) {

                    waitTime += waitStep;
                    handler.postDelayed(this, waitStep);

                } else {

                    waitListener.onWaitEnd();
                }
            }
        }
    });

}

public void setConditionState(boolean condition){
    this.condition = condition;
}

public void setWaitListener(WaitListener waitListener){
    this.waitListener = waitListener;
}

}

界面:

public interface WaitListener {

public void checkCondition();

public void onWaitEnd();

public void onConditionSuccess();

}

使用示例:

ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");

final Waiter waiter = new Waiter(getMainLooper(), 1000, 5000);
waiter.setWaitListener(new WaitListener() {

            @Override
            public void checkCondition() {
                Log.i("Connection", "Checking connection...");
                NetworkInfo networkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
                waiter.setConditionState(networkInfo.isConnected());
            }

            @Override
            public void onWaitEnd() {
                Log.i("Connection", "No connection for sending");
                //DO
            }

            @Override
            public void onConditionSuccess() {
                Log.i("Connection", "Connection success, sending...");
                //DO
            }

});

waiter.start();

1
你应该在自己的回答中包含链接答案的相关部分,除非它更适合作为评论。 - Abandoned Cart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接