How to properly kill AsyncTack thread in Android?

I am subclassing AsyncTask in my android project.

I want to implement a function that allows the user to cancel the current AsyncTack and start a new one if the current task is taking too long.

MyAsyncTask mat = new MyAsyncTask();

      

When the user clicks the cancel button, I implement the following code and then start a new task.

mat.cancel(true);

      

However, later on I realize that the new task does not start until the old task completes. The old task protector is still running.

I am checking the official doc on google. It seems that I have to call the following expression in doInBackGroud (Params ... params) .

if (isCancelled()) break;

      

The problem is that I found the code below is responsible for a long time.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);

      

But how can I check if the task is canceled or not when httpClient.execute (httpPost) is executed ? Is there a way, like onProgressChanged (int progress) , that I can override in the DefaultHttpClient?

+3


source to share


3 answers


I want to implement a function that allows the user to cancel the current AsyncTack and start a new one if the current task is taking too long.

Since you cannot start a new task before the old task completes, you can create a new instance of Asyntask. In fact, its a bad idea to use the AsyncTask instance multiple times. After

HttpResponse httpResponse = httpClient.execute(httpPost);

      

You can check if it is canceled



if(!isCanceled()){

}

      

Have a look at the docs , last line under Threading Rules.
Update as the comment noted. Depends on your platform, so check your platform version before executing.

   if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
      myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
    else {
      myTask.execute();
    }

      

+1


source


You need to cancel your request by calling abort

on your object httpPost

. This will cause the method to return immediately execute

and stop blocking the thread.



+1


source


I wouldn't use AsyncTask at all. AsyncTasks are prone to memory leaks and are poorly tied to the Activity lifecycle, so you will be in trouble.

Consider using RoboSpice , as not only will it help you resolve your issue, but it will also avoid AsyncTasks issues and skip writing by hand using the HttpClient. I'm not one of the developers of RoboSpice but recently started using it and it's a great project.

0


source







All Articles