How to call a method after a delay in Android
To call a method after a delay in Android, you can use the Handler
class and the postDelayed()
method. The postDelayed()
method takes a Runnable
and a delay in milliseconds as arguments, and it runs the Runnable
after the specified delay.
Here's an example of how you can use the Handler
class to call a method after a delay in Android:
public class MainActivity extends Activity {
private static final int DELAY = 5000; // 5 seconds
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Handler
Handler handler = new Handler();
// Create a Runnable that calls the doSomething() method
Runnable runnable = new Runnable() {
@Override
public void run() {
doSomething();
}
};
// Post the Runnable with a delay
handler.postDelayed(runnable, DELAY);
}
private void doSomething() {
// Do something here after the delay
}
}
In this example, a Handler
is created and a Runnable
is created that calls the doSomething()
method. The Runnable
is then posted to the Handler
with a delay of 5 seconds using the postDelayed()
method. The doSomething()
method will be called after the delay.
I hope this helps! Let me know if you have any questions.