2014-12-06 98 views
-1

我在android中运行一个异步任务来ping通特定的URL,但问题是当url无效或不可达时发生异常,因为sockettimeoutexception如此异常我想停止正在运行的任务。 iagve尝试使用取消()方法,但会导致应用程序崩溃。如何停止正在运行的异步任务?

我正在使用以下代码。

private class UrlDataProvider3 extends AsyncTask<String, Void, String> 
{ 

    String ret=""; 
    int checkStatus; 
    Boolean exception=false; 
    @Override 
    protected String doInBackground(String... url) 
    { 

     HttpURLConnection con = null; 

     try 
      { 

      Log.i("RAE", "urlData"+url[0]); 
      HttpURLConnection.setFollowRedirects(true); 
      con = (HttpURLConnection) new URL(url[0]).openConnection(); 
       con.setRequestMethod("POST"); 
       con.setConnectTimeout(20000); 




      } 


     catch (IOException e) 
      { 


      if(e.toString().contains("java.net.SocketTimeoutException:")) 
      { 



       return null; 

      } 



      } 



    return ret; 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     Log.i("RAE"," Asyc finished"); 



} 

回答

0

你做这样的事情:

if((this.downloadNetTask != null) 
     && (this.downloadNetTask.getStatus() != AsyncTask.Status.FINISHED)){ 
     this.downloadNetTask.cancel(true); 
} 

downloadNetTask是你实例异步任务。在异步任务中,实现以下方法来完成取消任务时所需的操作。

protected void onCancelled(List<CompanyNseQuoteDataVO> result) 

protected void onCancelled() 
+0

应用程序崩溃并显示taskCancellation例外 – 2014-12-06 05:12:51

+0

将堆栈跟踪粘贴到此处。 – Nazgul 2014-12-06 05:17:01

+0

12-06 10:42:06.192:E/AndroidRuntime(31001):致命例外:主 12-06 10:42:06.192:E/AndroidRuntime(31001):java.util.concurrent.CancellationException – 2014-12-06 05:22:20

0

事情是AsyncTask.cancel()调用只调用任务中的onCancel函数。这是您想要处理取消请求的地方。

这里是一个小任务,我用它来触发更新方法

private class SomeTask extends AsyncTask<Void, Void, Void> { 

     private boolean running = true; 

     @Override 
     protected void onCancelled() { 
      running = false; 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      super.onProgressUpdate(values); 
      onUpdate(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      while(running) { 
       publishProgress(); 
      } 
      return null; 
     } 
    } 

或者你可以检查你的任务如下图所示。

protected Object doInBackground(Object... x) { 
    while (/* condition */) { 
     // work... 
     if (isCancelled()) 
      break; 
     } 
    return null; 
}