In the realm of mobile development, the need often arises to execute a specific task after a predefined interval. This is where handlers come into play in Android. Handlers serve as messengers between threads, allowing you to schedule tasks to be performed at a future time.
In Objective-C, this was elegantly achieved using the performSelector method. It provided a convenient way to call a specific method after a specified delay:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
Android provides a similar mechanism through handlers. To delay the execution of a method, you can utilize the postDelayed() method. This method takes a Runnable object as its argument, which defines the code that should be executed after the specified delay. Here's how you can implement this in Kotlin and Java:
Handler(Looper.getMainLooper()).postDelayed({ // Do something after 100ms }, 100)
final Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after 100ms } }, 100);
In both examples, the delay is specified in milliseconds (100 in this case) as the second parameter. Remember to import the android.os.Handler class for both Kotlin and Java.
The above is the detailed content of How Can Handlers Be Used to Delay Method Calls in Android?. For more information, please follow other related articles on the PHP Chinese website!