Home >Java >javaTutorial >How to Call a Method After a Delay in Android?
Calling a Method After a Delay in Android
In Android, there are multiple methods to call a method after a specified delay. One effective approach is to use a Handler, enabling the scheduling of delayed tasks on the main thread. Here's how you can implement this using Kotlin and Java:
Handler(Looper.getMainLooper()).postDelayed({ //Do something after 100ms }, 100)
final Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { //Do something after 100ms } }, 100);
In both Kotlin and Java, the delay duration is specified as milliseconds in the third parameter of the postDelayed() method. In this example, the specified delay is 100 milliseconds.
Don't forget to import the appropriate class, which is android.os.Handler for both Kotlin and Java. Utilizing a Handler ensures that the delayed task executes on the main thread, allowing UI updates and other sensitive operations to be carried out smoothly.
The above is the detailed content of How to Call a Method After a Delay in Android?. For more information, please follow other related articles on the PHP Chinese website!