如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
如何修复此代码中的弃用警告?或者,还有其他的选择吗?
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
当前回答
handler()等代码是由Android Studio 4.0.1生成的,例如,当一个全屏活动从头创建时。我知道有人鼓励我们使用Kotlin,我也是这样做的,但是我不时地使用示例项目来实现一个想法。 奇怪的是,当AS实际生成代码时,我们却被AS责骂。这可能是一个有用的学术活动来检查错误并修复它们,但也许AS可以为我们爱好者生成新的干净的代码……
其他回答
协程 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()
}
在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)
}
对于Xamarin Android,而不是
Handler handler;
handler = new Handler();
只写
Handler handler;
handler = new Handler(Looper.MyLooper());
其余的代码都很好。
使用Executor而不是handler获取更多信息。 使用ScheduledExecutorService实现post delay:
ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> {
public void run() {
// Do something
}
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
根据文档(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。