pijushcse
pijushcse

Reputation: 550

Android Button stop taking new action utill onClick() block execution finish

    b.setOnClickListener(new OnClickListener()) {
    public void onClick(View arg0) {
        try{
         Thread.sleep(10000);
       }catch(Exception e){}
     }   
  });

On above code, I don not want to take any more Button action until the Therad is working. Currently when I press again and again Application ask for force close or wait. I don't want that rather I do not like to take anymore action on this button.

Need help. Thanks

Upvotes: 0

Views: 1968

Answers (3)

Aleks G
Aleks G

Reputation: 57316

There are at least two ways to block further clicks while the previous one is being processed:

1) Disable the button at the beginning and re-enable at the end of your onClick:

b.setOnClickListener(new OnClickListener()) {
    public void onClick(View arg0) {
        b.setEnabled(false);

        //do your stuff

        b.setEnabled(true);
    }   
});

2) Set a flag in the beginning of your onClick and clear it in the end:

(class-level)

boolean isInOnClick = false;

and then

b.setOnClickListener(new OnClickListener()) {
    public void onClick(View arg0) {
        if(!isInOnClick) {
            isInOnClick = true;

            //do your stuff

            isInOnClick = false;
        }
    }   
});

Upvotes: 0

user370305
user370305

Reputation: 109237

Better to use AsyncTask for your works. And use the get() method of AsyncTask for your requirement.

Suppose on Button's click execute() AsyncTask and disable button after wait for get() of AsyncTask which will return Result on completion of AsyncTask and on Result just enable your button again. So you can avoid ANR in your Activity.

Upvotes: 0

Shubhayu
Shubhayu

Reputation: 13552

Add a global boolean and set it to true when u click it. Check for it in your button click. if it is set then return, else run the thread. at the end of the thread set it to false again.

boolean clicked = false;

b.setOnClickListener(new OnClickListener()) {
    public void onClick(View arg0) {
        if( clicked )
            return;
        try{
         clicked = true;
         Thread.sleep(10000);
       }catch(Exception e){}
     }   
  });

set clicked = false when u return from sleep.

Upvotes: 4

Related Questions