Joyson
Joyson

Reputation: 1653

Timer in android to execute after a specific time?

I am using the following code to execute a method after a specific time period say 9seconds.The code works fine only after the first execution.However i want that when the activity is launched the method must be called after 9 secs.Now what happens is the method is called the moment the activity is launched followed by after 9 seconds again it is called. Following is my code:

 private Timer myTimer;
 myTimer = new Timer();
 myTimer.schedule(new TimerTask() 
 {          
    @Override
    public void run() 
    {
        TimerMethod();
    }
 }, 0, 9000);


   private void TimerMethod()
   {
        this.runOnUiThread(Timer_Tick);
   }
  private Runnable Timer_Tick = new Runnable() 
  {
    public void run() 
    {

        //Did some UI Operation 
        Toast.makeText(context, msg, 1000).show();

    }
  };

Upvotes: 0

Views: 262

Answers (1)

MSA
MSA

Reputation: 2482

You can use this:

 private void TimeMethod() {

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

            //TODO after 9 sec
        }
    }, 9000);

}

Hope this will be usefull,

Cheers

Upvotes: 3

Related Questions