0

Possible Duplicate:
How to call a method after a delay

When a user clicks a button, I want to doThis(myVar1);. 1 second later I want to doThis(myVar2);. How can I schedule that 2nd call?

Community
  • 1
  • 1
Roger
  • 4,249
  • 10
  • 42
  • 60

3 Answers3

2

Create a handler and do a postDelayed() on a runnable. Check the documentation for Handler.

Handler handler = new Handler();
final Runnable r = new Runnable()
{
    public void run() 
    {
        doThis(myVar2);.
    }
};
...
...
handler.postDelayed(r, 1000);
Ron
  • 24,175
  • 8
  • 56
  • 97
2

try this way using Thread:

 btnbtnstart.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
        if(mthreadRunning==false)
        {
            doThis(myVar1);
            mthreadRunning=true;
            dojobThread();
        }
    }
});

 public void dojobThread(){
        Thread th=new Thread(){
         @Override
         public void run(){
          try
          {
           while(mthreadRunning)
           {
           Thread.sleep(100L);
           mthreadRunning=false;
           doThis(myVar2);//call doThis(myVar2); here after 1 second delay

           }
          }catch (InterruptedException e) {
            // TODO: handle exception
          }
         }
        };
        th.start();
       }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
1

In a desktop GUI app, I would use javax.swing.Timer from the Swing API. Perhaps the Android API has something similar? Of course, the Thread example above by imran khan is essentially the same thing.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268