aryaxt aryaxt - 6 months ago 33
Android Question

How to call a method after a delay in Android

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 android with java?
For example I need to be able to call a method after 5 seconds.

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

Answer

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.

private static final ScheduledExecutorService worker = 
  Executors.newSingleThreadScheduledExecutor();

void someMethod() {
  ⋮
  Runnable task = new Runnable() {
    public void run() {
      /* Do something… */
    }
  };
  worker.schedule(task, 5, TimeUnit.SECONDS);
  ⋮
}
Comments