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
Barbara StreisandOriginal
2024-12-28 11:03:23908browse

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)

Java:

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

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!

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