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

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

其他回答

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

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

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

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
}

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

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

或者使用处理器

        Handler(Looper.myLooper()!!)

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