Home > Java > javaTutorial > How to Achieve Asynchronous Method Invocation with a Delay in Android?

How to Achieve Asynchronous Method Invocation with a Delay in Android?

Barbara Streisand
Release: 2024-12-28 11:03:23
Original
905 people have browsed it

How to Achieve Asynchronous Method Invocation with a Delay in Android?

Async Method Invocation in Android

In Android, a common requirement is to call a method after a specific delay. In Objective-C, this can be achieved using the performSelector method. This article provides Java equivalents for this functionality in Android, enabling developers to schedule method invocations for later execution.

The following code block demonstrates how to call the method DoSomething after a delay of 5 seconds:

Kotlin:

Handler(Looper.getMainLooper()).postDelayed({
    // Do something here
}, 5000)
Copy after login

Java:

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something here
    }
}, 5000);
Copy after login

In both cases, the Handler class is responsible for scheduling the method invocation. The postDelayed method takes two parameters: a Runnable object that encapsulates the code to be executed, and a delay in milliseconds.

When the specified delay elapses, the Runnable's run method is invoked on the main thread. This allows developers to perform asynchronous operations without blocking the main UI thread.

The above is the detailed content of How to Achieve Asynchronous Method Invocation with 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