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

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

当前回答

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

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

或者使用处理器

        Handler(Looper.myLooper()!!)

其他回答

对于Xamarin Android,而不是

Handler handler;
handler = new Handler();

只写

Handler handler;
handler = new Handler(Looper.MyLooper());

其余的代码都很好。

根据文档(https://developer.android.com/reference/android/os/Handler#Handler()):

Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, {link android.view.View#getHandler}, or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers.

我们应该停止使用没有Looper的构造函数,而是指定一个Looper。

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

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

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

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

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

被弃用的函数是Handler的构造函数。请改用Handler(loop . mylooper ()) .postDelayed(runnable, delay)