Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to call a method after a delay in Android

I need to have the option to call the accompanying technique after a specified delay. In target c there was a like thing:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

public void DoSomething()
{
//do something here
}
by

2 Answers

rahul07
Kotlin

Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)

Java

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
RoliMishra
In my case Iused the native java Timer instead.

new Timer().schedule(new TimerTask() {          
@Override
public void run() {
// this code will be executed after 2 seconds
}
}, 2000);

Login / Signup to Answer the Question.