Tùng Phan Thanh
Tùng Phan Thanh

Reputation: 151

Can asyntask in android auto stop their task?

I have an Asynctask that does some work in the background, and I define it like this.

MyAsynctask myAsynctask;

Then in my button click event I do something like this:

public void onClick(Event event){
    mAsynctask = new MyAsynctask(context);
    mAsynctask.execute();
}

When I run the code, the work that I do in the background always seems to work well. But I'm afraid to have two AsyncTask running at the same time if I press the button the second time when the first AsyncTask is not finished.

Is this likely to be an issue?

Upvotes: 1

Views: 63

Answers (2)

Milad Faridnia
Milad Faridnia

Reputation: 9477

you can use yourButton.setEnabled(false); in your onClickListener and the after the task is finished in onPostExecute of your AsynchTasck set your button enable again. something like this :

boolean myFlag = true;
public void onClick(Event event){
    //yourBusston.setEnabled(false);
    if (myFlag){
    myFlage = false;
    mAsynctask = new MyAsynctask(context);
    mAsynctask.execute();
    }
}

and then in your AsynchTask do something like this:

@Override
    protected void onPostExecute(Void void) {
      //after you ensure that your task was successful 
      // yourButton.yourButton.setEnabled(true);
       myFlag = true;           
}

You can also cancel your task when ever you want by this line of code :

task.cancel(true);

Upvotes: 0

Nick Hargreaves
Nick Hargreaves

Reputation: 436

You can check status of the task as follows:

int taskStatus = myAsynctask.getStatus();

The status can be any of the following:

AsyncTask.Status.PENDING

AsyncTask.Status.RUNNING

AsyncTask.Status.FINISHED

So you can do something like :

if(taskStatus == AsyncTaskStatus.RUNNING){
 //task is still running
}

Upvotes: 1

Related Questions