What do I use now that Handler() is deprecated?
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)
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)
Note: use requireContext()
instead of this@MainActivity
if you are using fragment.