0

I've searched Google about this specific exception and multiple results have surfaced but I have not seen an answer to the question I have. I'm currently accessing an API on some server in the following manner:

// Setup...
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

nameValuePair.add(new BasicNameValuePair("key","value"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
String results = EntityUtils.toString(response.getEntity())

And of course the above code is not the exact same code I am using. Any UI blocking tasks are done on a separate thread using AsyncTask.

When this code gets executed for the first time, everything is fine. Then we execute the code again and the following exception appears, but only in Android 2.2 and 2.3 (I haven't tested this on 3.0 or 4.0):

Invalid use of SingleClientConnManager: connection still allocated

Now, one of the top answers to this question can be found here: Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated, which I haven't tried but before that, I am wondering why this exception is not being thrown when I run this on Android 4.1?

Community
  • 1
  • 1
Alex Fu
  • 5,509
  • 3
  • 31
  • 40

1 Answers1

2

The behavior of AsyncTask changed on Android 3.2: if your targetSdkVersion is 13 or higher, your AsyncTasks will share a single background thread by default, and only one task will run at a time. Otherwise, your AsyncTasks will use a thread pool and can run in parallel. Since HttpClient is not thread-safe by default, that is why you are encountering a difference in behavior.

If you want to use HttpClient across multiple threads, use a ThreadSafeClientConnManager.

For more on the AsyncTask behavior change: http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491