Home >Java >javaTutorial >How Can I Execute Methods After a Delay in Android?

How Can I Execute Methods After a Delay in Android?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 15:29:11632browse

How Can I Execute Methods After a Delay in Android?

Executing Methods on a Delay in Android

In Android programming, you can utilize the Handler class and its postDelayed() method to execute methods after a specified time interval.

Kotlin Implementation

Handler(Looper.getMainLooper()).postDelayed({
    // Method to be executed after delay
}, delayInMillis)

For instance, to execute a method named DoSomething after a 100ms delay:

Handler(Looper.getMainLooper()).postDelayed({
    DoSomething()
}, 100)

Java Implementation

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Method to be executed after delay
    }
}, delayInMillis);

To call the DoSomething method after 100ms using Java:

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        DoSomething();
    }
}, 100);

Remember to import android.os.Handler for both Kotlin and Java implementations.

The above is the detailed content of How Can I Execute Methods 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