Search code examples
androidandroid-asynctaskexecute

AsyncTask's get() method's behavior changed with different API levels


My app's targetSdkVersion is 11. I need to upgrade it to 14 or upper. Unfortunately my current code heavily depends on codes like this.

int timeout = 5000;  
return new HttpMnagerAsync().execute().get(timeout, TimeUnit.MILLISECONDS);

In targetSdkVersion 11: This code execute the method HttpMnagerAsync()'s doInBackground() immediately and wait for 5 seconds for complete the execution and return the results. If failed to finish in 5 seconds a timeout exception returns. (This is the expectation)

When changed to targetSdkVersion 14: This code waits 5 seconds doing nothing, and it returned timeout exception, and then it hits the HttpMnagerAsync()'s doInBackground() method.

I need to upgrade the targetSdkVersion to 14. any explanation is appreciated to overcode this issue.


Solution

  • Calling get() will not make Asynctask asynchronous, get() waits for the result blocking the ui thread. Remove get() and use execute like for example:

    new HttpMnagerAsync().execute();
    

    Then, you can set your timeout in Http client, for example:

    try
    {     
       HttpGet httpGet = new HttpGet(url);
       HttpParams httpParameters = new BasicHttpParams();
    
       // Set the timeout in milliseconds until a connection is established.
       // The default value is zero, that means the timeout is not used. 
       int timeoutConnection = 5000;
       HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    
       // Set the default socket timeout (SO_TIMEOUT) 
       // in milliseconds which is the timeout for waiting for data.
       int timeoutSocket = 6000;
       HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
       DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
       HttpResponse response = httpClient.execute(httpGet);
    } 
    catch (ConnectTimeoutException e) 
    {
        //Here Connection TimeOut excepion    
        Toast.makeText(xyz.this, "Your connection timedout", 11000).show();
    }