AsyncTask get()方法行为随着不同的API级别而改变

时间:2014-10-07 08:14:53

标签: android android-asynctask execute

我的应用程序的targetSdkVersion是11.我需要将其升级到14或更高版本。不幸的是,我目前的代码很大程度上取决于这样的代码。

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

在targetSdkVersion 11中: 此代码立即执行方法HttpMnagerAsync()的doInBackground()并等待5秒钟以完成执行并返回结果。如果在5秒内未能完成,则返回超时异常。 (这是期望)

更改为targetSdkVersion 14时: 此代码等待5秒钟无效,并返回超时异常,然后它命中HttpMnagerAsync()的doInBackground()方法。

我需要将targetSdkVersion升级到14。 任何解释都会被重写以解决这个问题。

1 个答案:

答案 0 :(得分:1)

调用get()不会使Asynctask异步,get()会等待阻塞ui线程的结果。删除get()并使用execute,例如:

new HttpMnagerAsync().execute();

然后,您可以在Http客户端设置超时,例如:

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();
}