Cancel an ongoing connection when user presses back
<p>I have been searching about this but I did not find my specific question. I understand that AskyncTask can be canceled using .cancel(true) but this only happens if I have a loop in which I can check the value isCanceled(). </p>

<p>But my question here is.. how can I cancel an AsyncTask (that is stuck in httpclient.execute() ) when the user presses back?  If the user navigates away from that Activity and goes to another I dont want to have an uncontrolled number of AsyncTask running because this may lead to memory problems, the user could navigate back and forth and create undetermined number of tasks. That is why I want to close them. Anyone knows a way? I post the code I use to connect:</p>

<pre><code>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&lt;String, Void, String&gt;{

    @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;        
    }

  }

}
</code></pre>

<p>Do you know what I should add in onStop() to cancel the ongoing httpClient.execute() function? Sometimes gets stuck almost forever.</p>

<p>I would really appreciate your help, thank you very much in advance.</p>

<h2>UPDATE</h2>

<p>If I close the ConnectionManager I have to do the handshaking for https again, right? Look at this code when I create the httpClient, I use this for https:</p>

<pre><code>HttpClient httpclient = DefaultHttpClient(params,clientConnectionManager);
</code></pre>

<p>Thank you all for your quick responses and the variety of solutions exposed here. I will try to use the timeouts (for not having to wait too much) + the cancel() function to avoid processing onPostExecute. I will tell if the results are as expected! Thank you very much you all!</p>
