2011-04-21 51 views
2

我想在连接到服务器失败时取消我的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分钟的浇水棒都不好)

任何想法我的代码有什么问题?这不可能是正常的,对吧?

回答

4

doInBackground()方法,则需要返回String。你可以,如果你的HTTPPost fails.And返回null然后在onPostExecute()方法只是检查你想说什么,如果String为null不做任何事,你真的要和成功运行做你的用户界面工作

希望这会帮助你。

+0

任何想法如何我可以更快地检测到这个问题?因为现在我需要大约三分钟才能看到“连接已重置”错误。我应该在捕获物内还是在其他地方返回假? – networkprofile 2011-04-21 12:52:35

+0

没有可用的选项来更快地跟踪问题。在我注意到您的连接超时值为15秒时,您可以将其更改为一些小值。对套接字超时也使用'setSoTimeout'方法。 – 2011-04-21 13:08:22

+0

即使连接时间较短,出于某种原因,它只需要稍微超过三分钟才会跳转到onPostExecute()这就是为什么我一直在想我的代码有什么问题。 – networkprofile 2011-04-21 14:05:43

0
HttpHost target = new HttpHost("192.168.2.3", 80); 
HttpPost post = new HttpPost("/ping/login.php"); 

response = client.execute(target, post); 

这解决了服务器响应速度慢的问题。