Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// runs a method every 2000ms
// example runThisEvery2seconds();
}
}, 2000);
} //end of OnCreate
public void runThisEvery2seconds()
{
//code that runs every 2 seconds
Toast.makeText(getBaseContext(), "Run from timer", Toast.LENGTH_SHORT);
}
For the time being I have tried this but the Toast message doesn’t appear. Don’t know if you’re allowed to do that but anyway in general, if I actually execute code inside runThisEvery2seconds() , other than Toast, will it run every 2 seconds ?
Make sure you call
show()when you make your toast message.And no, your message won’t be displayed every 2 seconds.
postDelayedruns the task once, after the specified delay, but after that it’s done. If you want to have tasks run on a schedule, take a look at Java’s Timer or ScheduledExecutorService.