我想在連接到服務器失敗時取消我的AsyncTask。我試過cancel()
,但onPostExecute()
方法仍然被調用,而不是onCancelled()
。HTTPPost失敗時取消AsyncTask?
這是我裏面doInBackground()
:
protected String doInBackground(String... params) {
Log.i("ping", "doInBackground() started");
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse response;
HttpEntity entity;
try {
HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", getEmail()));
nvps.add(new BasicNameValuePair("password", getPassword()));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream iStream = entity.getContent();
read(iStream);
iStream.close();
if(entity != null)
entity.consumeContent();
Log.i("ping", "doInBackground() vervolgd");
} catch (Exception e) {
e.printStackTrace();
Log.e("tvsping", "Exception: " + e.getMessage());
cancel(true);
}
return null;
}
我想看看會發生什麼,當服務器無法達到(我將其關閉,所以沒有辦法我的手機得到任何答覆),我得到IOException: the connection was reset
。
任何想法,我應該檢查,如果沒有連接?
更新 我解決了這個問題,就像Tanmay建議的那樣,用布爾值。但我有另一個問題: 每次調用doInBackground()時,如果找不到服務器,大概需要三分鐘的時間停止。一切都很好,當它可以到達服務器,但我不能有這需要3分鐘之前,用戶被通知任何事情(我可以做一個後臺進程,但仍然是一個3分鐘的澆水棒都不好)
任何想法我的代碼有什麼問題?這不可能是正常的,對吧?
任何想法如何我可以更快地檢測到這個問題?因爲現在我需要大約三分鐘才能看到「連接已重置」錯誤。我應該在捕獲物內還是在其他地方返回假? – networkprofile 2011-04-21 12:52:35
沒有可用的選項來更快地跟蹤問題。在我注意到您的連接超時值爲15秒時,您可以將其更改爲一些小值。對套接字超時也使用'setSoTimeout'方法。 – 2011-04-21 13:08:22
即使連接時間較短,出於某種原因,它只需要稍微超過三分鐘纔會跳轉到onPostExecute()這就是爲什麼我一直在想我的代碼有什麼問題。 – networkprofile 2011-04-21 14:05:43