问题
Could anyone know, how to fix deprecated waring or any alternate solution for this.
Handler().postDelayed({
context?.let {
//code
}
}, 3000)
回答1:
If you want to avoid the null check thing in Kotlin (?
or !!
) you can use Looper.getMainLooper()
if your Handler
is working with some UI related thing, like this:
Handler(Looper.getMainLooper()).postDelayed({
Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)
回答2:
Consider using coroutines
scope.launch {
delay(3000L)
// do stuff
}
回答3:
The deprecated function is that constructor for Handler. Use Handler(Looper.myLooper()) .postDelayed(runnable, delay)
instead
回答4:
Use Executor instead of handler for more info Executor
to achieve post delay use ScheduledExecutorService
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = new Runnable() {
public void run() {
// Do something
}
};
worker.schedule(runnable, 2, TimeUnit.SECONDS);
回答5:
According to the document (https://developer.android.com/reference/android/os/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."
we should quit using the constructor without a Looper, specific a Looper instead.
来源:https://stackoverflow.com/questions/61023968/how-to-solve-handler-deprecated