如何修复此代码中的弃用警告?或者,还有其他的选择吗?

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

当前回答

使用这个

Looper.myLooper()?.let {
    Handler(it).postDelayed({
        //Your Code
    },2500)
}

其他回答

使用Executor而不是handler获取更多信息。 使用ScheduledExecutorService实现post delay:

ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> {
    public void run() {
        // Do something
    }
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
import android.os.Looper
import android.os.Handler

inline fun delay(delay: Long, crossinline completion: () -> Unit) {
    Handler(Looper.getMainLooper()).postDelayed({
        completion()
    }, delay)
}

例子:

delay(1000) {
    view.refreshButton.visibility = View.GONE
}

Java的答案

我写了一个容易使用的方法。您可以在项目中直接使用此方法。delayTimeMillis可以是2000,这意味着该代码将在2秒后运行。

private void runJobWithDelay(int delayTimeMillis){
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            //todo: you can call your method what you want.
        }
    }, delayTimeMillis);
}

考虑使用协程

scope.launch {
    delay(3000L)
    // do stuff
}

使用生命周期范围会更容易。内部活动或片段。

 lifecycleScope.launch {
     delay(2000)
     // Do your stuff
 }

或者使用处理器

        Handler(Looper.myLooper()!!)