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

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

当前回答

只有无参数的构造函数已弃用,现在最好通过loop . getmainlooper()方法在构造函数中指定循环器。

用于Java

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

将它用于Kotlin

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

来源:developer.android.com

其他回答

handler()等代码是由Android Studio 4.0.1生成的,例如,当一个全屏活动从头创建时。我知道有人鼓励我们使用Kotlin,我也是这样做的,但是我不时地使用示例项目来实现一个想法。 奇怪的是,当AS实际生成代码时,我们却被AS责骂。这可能是一个有用的学术活动来检查错误并修复它们,但也许AS可以为我们爱好者生成新的干净的代码……

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

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

或者使用处理器

        Handler(Looper.myLooper()!!)

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

Handler()和Handler(Handler.)回调回调)构造函数已弃用。因为这可能会导致bug和崩溃。显式使用Executor或Looper。

对于Java

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //do your work here
   }
}, 1000);

在Kotlin中使用这种结构是个好主意

companion object Run {
   fun after(delay: Long, process: () -> Unit) {
      Handler(Looper.getMainLooper()).postDelayed({
          process()
      }, delay)
   }
}

稍后称为

Run.after(SPLASH_TIME_OUT) {
   val action = SplashFragmentDirections.actionSplashFragmentToLogin()
   v.findNavController().navigate(action)
}