I searched about this, but I did not find my specific question. I understand that AskyncTask can be undone with .cancel(true) , but this will only happen if I have a loop in which I can check the value of isCanceled() .
But my question is here: how can I cancel AsyncTask (which is stuck in httpclient.execute() ) when the user clicks back? If the user goes from this operation and goes to another, I donβt want the uncontrolled number of AsyncTask starts to run, as this can lead to memory problems, the user can move back and forth and create an undefined number of tasks. That's why I want to close them. Does anyone know the way? I am posting the code that I use to connect:
public class Test extends Activity { @Override protected void onStart() { super.onStart(); new ConnectionTask().execute("https://www.mywebserver.com/webservice.php?param1=test"); } private class ConnectionTask extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { try { HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager); HttpPost httpPost = new HttpPost(params[0]); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if(httpEntity != null) return EntityUtils.toString(httpEntity); } catch (Exception e) { e.printStackTrace(); } return null; } } }
Do you know what I have to add to onStop () to cancel the current httpClient.execute () function? Sometimes stuck almost forever.
I would really appreciate your help, thanks a lot in advance.
UPDATE
If I close the ConnectionManager , I must again acknowledge for https, right? Look at this code when I create httpClient , I use it for https:
HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager);
Thank you all for your prompt answers and the variety of solutions offered here. I will try to use timeouts (in order not to wait too much) + the cancel() function to avoid processing onPostExecute . I will say if results are expected! Thank you very much!
source share