dmSherazi
dmSherazi

Reputation: 3831

stop previous Handler postdelayed and start new

I am using Handler postDelayed() to start a timer for 7 secs. if during this interval I receive a reply from server I will stop the timer. but if the reply isnt recieved within 7 sec it will show error.

I am using this code for the purpose

handler = new Handler();

Runnable wait4TO = new Runnable(){
    @Override
    public void run() {
        if(pressedButton==INACTVE) ;
        // if reply is recieved pressedbutton will be INACTIVE

        else
        {
            sentFailed();
        }

    }
};

handler.postDelayed(wait4TO, 7000 );

It works correctly, but if another message is sent I want to cancel this timeout and start a new one or extend the existing timeout for another 7 secs. How can I acheive this?

I tried cancelling the handler by using handler.removeCallbacks(wait4TO) and handler.removeCallbacks(null) but no success. the previous handler will still run

Upvotes: 0

Views: 1039

Answers (2)

Blackbelt
Blackbelt

Reputation: 157437

removeCallbacks works. Just be aware of the fact that every handler as its own queue, and in your case, to achieve what you want, you need only one instance of Handler.

Upvotes: 2

Gooziec
Gooziec

Reputation: 2776

So maybe try add flag that you check in runnable

boolean flag=true;

Runnable wait4TO = new Runnable(){
    @Override
    public void run() {
 if(!flag)
 return;
        if(pressedButton==INACTVE) ;
        // if reply is recieved pressedbutton will be INACTIVE

        else
        {
            sentFailed();
        }

    }
};

handler.postDelayed(wait4TO, 7000 );

And when You want to deactivate it You just set flag to false;

Eventually try

handler.removeCallbacs(wait4TO);

Upvotes: 2

Related Questions