What do I use now that Handler() is deprecated?

Hari Shankar S picture Hari Shankar S · Apr 4, 2020 · Viewed 41.6k times · Source

How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this?

Handler().postDelayed({
    context?.let {
        //code
    }
}, 3000)

Answer

Nikunj Paradva picture Nikunj Paradva · Sep 11, 2020

Only the parameterless constructor is deprecated, it is now preferred that you specify the Looper in the constructor via the Looper.getMainLooper() method.

Use it for Java

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // Your Code
    }
}, 3000);

Use it for Kotlin

Handler(Looper.getMainLooper()).postDelayed({
    // Your Code
}, 3000)