I want to be able to call the following method after a specified delay. In objective c there was something like:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
Is there an equivalent of this method in java? For example I need to be able to call a method after 5 seconds.
public void DoSomething()
{
//do something here
}
Source: Tips4all
It looks like the Mac OS API lets the current thread continue, and schedules the task to run asynchronously. In the Java, the equivalent function is provided by the java.util.concurrent package. I'm not sure what limitations Android might impose.
ReplyDeleteprivate static final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
void someMethod() {
⋮
Runnable task = new Runnable() {
public void run() {
/* Do something… */
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
⋮
}
Thanks for all the great answers, I found a solution that best suits my needs.
ReplyDeleteHandler myHandler = new DoSomething();
Message m = new Message();
m.obj = c;//passing a parameter here
myHandler.sendMessageDelayed(m, 1000);
class DoSomething extends Handler {
@Override
public void handleMessage(Message msg) {
MyObject o = (MyObject) msg.obj;
//do something here
}
}
Better version:
ReplyDeletefinal Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
I suggest the Timer, it allows you to schedule a method to be called on a very specific interval. This will not block your UI, and keep your app resonsive while the method is being executed.
ReplyDeleteThe other option, is the wait(); method, this will block the current thread for the specified length of time. This will cause your UI to stop responding if you do this on the UI thread.
See this demo:
ReplyDeleteimport java.util.Timer;
import java.util.TimerTask;
class Test {
public static void main( String [] args ) {
int delay = 5000;// in ms
Timer timer = new Timer();
timer.schedule( new TimerTask(){
public void run() {
System.out.println("Wait, what..:");
}
}, delay);
System.out.println("Would it run?");
}
}
http://stackoverflow.com/questions/1520887/how-to-pause-sleep-thread-or-process-in-android
ReplyDeleteYeah, I would recommend using the Android-specific Handler class. I was looking into timers on the Android recently and this ended up being the best solution. I was trying to have something run at a certain interval, but it works the same way for a one-time delay. This page has all the details.
ReplyDelete