如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
当前回答
在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)
}
其他回答
只有无参数的构造函数已弃用,现在最好通过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
使用Executor而不是handler获取更多信息。 使用ScheduledExecutorService实现post delay:
ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> {
public void run() {
// Do something
}
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
考虑使用协程
scope.launch {
delay(3000L)
// do stuff
}
根据文档(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。
我有三个解决方案:
显式地指定Looper: 处理程序(Looper.getMainLooper ()) .postDelayed ({ / /代码 },持续时间) 指定隐式线程本地行为: 处理程序(Looper.myLooper () ! !) .postDelayed ({ / /代码 },持续时间) 使用线程: 线程({ 尝试{ thread . sleep (3000) } catch (e:异常){ 把e } / /代码 }).start ()