Post Top Ad

How to call a method after a delay in Android

I recently wanted to call a method after some time for my project. What i rally wanted was, i have already created a splash screen for my app. And then after 5seconds or so i wanted to remain it in active and start another activity.( in fact MainActivity).

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

IOS Approach For This Problem

Ex: In ios you will find a method called to do this task easilty
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
 

In Android what would be the best way to achieve this

I achieved this using java.util.concurrent package.

Here is the code

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

void someMethod() {

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

}
 
Note:
 
1. worker.schedule(task, 5, TimeUnit.SECONDS); 
   Here i have set the delay to 5 seconds. 
2. /* Do something… */
   Insert your code to be run there after the given time exceeds.   
 
 
 
 
 

No comments:

Post a Comment

My Instagram