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
Release: 2024-12-29 15:29:11
Original
657 people have browsed it

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)
Copy after login

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

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

Java Implementation

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

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template