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

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

当前回答

我通常用这个

代码:

Handler(Looper.myLooper() ?: return).postDelayed({
           // Code what do you want
        }, 3000)

截图:

其他回答

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

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

如果你想避免在Kotlin (?或者!!)你可以使用loop . getmainlooper()如果你的Handler正在处理一些UI相关的事情,像这样:

Handler(Looper.getMainLooper()).postDelayed({
   Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)

注意:如果使用fragment,请使用requireContext()而不是this@MainActivity。

考虑使用协程

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

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

如果你使用变量作为处理程序和可运行的,然后像这样使用它。

private Handler handler;
private Runnable runnable;

handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(runnable = () -> {
        // Do delayed stuff here
         handler.postDelayed(runnable, 1000);
    }, delay);

你还需要删除onDestroy()中的回调

@Override
public void onDestroy() {
    super.onDestroy();
    if (handler != null) {
        handler.removeCallbacks(runnable);
    }
}