现在不推荐使用Handler(),我该怎么用?

问题描述:

如何解决此代码中的弃用警告?另外,还有其他选择吗?

How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this?

Handler().postDelayed({
    context?.let {
        //code
    }
}, 3000)

仅不建议使用无参数构造函数,现在最好通过Looper.getMainLooper()方法在构造函数中指定Looper.

Only the parameterless constructor is deprecated, it is now preferred that you specify the Looper in the constructor via the Looper.getMainLooper() method.

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // Your Code
    }
}, 3000);

将其用于Kotlin

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