Home >Java >javaTutorial >How to Call a Method After a Delay in Android?

How to Call a Method After a Delay in Android?

DDD
DDDOriginal
2024-12-24 04:22:11836browse

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:

Kotlin

Handler(Looper.getMainLooper()).postDelayed({
    //Do something after 100ms
}, 100)

Java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn