如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
当前回答
协程 Kotlin
private val SPLASH_SCREEN_TIME_OUT_CONST: Long = 3000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
GlobalScope.launch {
delay(SPLASH_SCREEN_TIME_OUT_CONST)
goToIntro()
}
}
private fun goToIntro(){
startActivity(Intent(this, IntroActivity::class.java))
finish()
}
其他回答
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);
被弃用的函数是Handler的构造函数。请改用Handler(loop . mylooper ()) .postDelayed(runnable, delay)
只有无参数的构造函数已弃用,现在最好通过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
对于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。