bubbly
bubbly

Reputation: 493

Android timer to auto run method

    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 ?

Upvotes: 0

Views: 1971

Answers (4)

Akshay Nandwana
Akshay Nandwana

Reputation: 1292

Call the show() method.

Toast.makeText(getBaseContext(), "Run from timer", Toast.LENGTH_SHORT).show();

Upvotes: 0

Samir Mangroliya
Samir Mangroliya

Reputation: 40406

.show() end of the toast.

Toast.makeText(getBaseContext(), "Run from timer", Toast.LENGTH_SHORT).show();

Upvotes: 1

Itsik
Itsik

Reputation: 3930

You aren't showing the Toast.
Call the show method.

Toast.makeText(getBaseContext(), "Run from timer", Toast.LENGTH_SHORT).show();

Upvotes: 1

derekerdmann
derekerdmann

Reputation: 18252

Make sure you call show() when you make your toast message.

Toast.makeText(getBaseContext(), "Run from timer", Toast.LENGTH_SHORT).show();

And no, your message won't be displayed every 2 seconds. postDelayed runs 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.

Upvotes: 1

Related Questions