主类调用一个暂挂任务。暂挂任务调用2个过程。第一个解析XML文件并获取html链接的文件。第二个阅读该html文件。粘贴了异步任务代码和第二个过程,该过程读​​取了一个html文件(不要认为第一个过程会引起问题),即使在处理了每个http异常并设置了套接字超时之后,我仍然遇到了“强制关闭”异常。如果我分别调用readfile过程,那么我的手机会收到一个sockettimeout异常(如果连接速度很慢)。但是,如果我从异步任务中调用它,则会收到“强制关闭”异常。

1)即使我已经处理了异常,为什么在我的logcat中仍然收到sockettimeout异常?
2)我将异常错误消息传递回asynctask。但仍然没有得到显示。我是否还应该在异步任务过程中应用try-catch?

请帮忙。

问候,
山姆

           private class SelectDataTask extends AsyncTask<String, Void, List<String> {
           private final ProgressDialog dialog = new ProgressDialog(MessageList.this);
           // can use UI thread here
          @Override
           protected void onPreExecute() {
            dialog.setMessage("Fetching scores...");
            dialog.show();
         }


         // automatically done on worker thread (separate from UI thread)
         @Override
         protected List<String> doInBackground(final String... args) {
                  List<String> scores = new ArrayList<String>();
                  List<String> scores1 = new ArrayList<String>();
                  scores =  loadFeed() ;

                  //return loadFeed();
                  for (String sco : scores) {
                      scores1.add(readFile(sco));
                  }
                  return scores1;

         }


         // can use UI thread here
        @Override
         protected void onPostExecute(final List<String> result) {
            if (dialog.isShowing()) {
               dialog.dismiss();
            }
           adapter =
                  new ArrayAdapter<String>(MessageList.this,R.layout.row,result);
           MessageList.this.setListAdapter(adapter);

         }
      }

      private String readFile(String htmllink){
       String TAG = "myActivity";
      List<String> scores = new ArrayList<String>();
      String result="";
      String score = "";
      int CONNECTION_TIMEOUT_MS = 30 * 1000; // ms

      HttpParams my_httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(my_httpParams,CONNECTION_TIMEOUT_MS);
      HttpConnectionParams.setSoTimeout(my_httpParams, CONNECTION_TIMEOUT_MS);
      HttpClient client = new DefaultHttpClient(my_httpParams);  // get http client with given params
      HttpGet request = new HttpGet(htmllink);
      try{
             HttpResponse response = client.execute(request);
             //txtResult.setText(HttpHelper.request(response));
             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                 try{
                     InputStream in = response.getEntity().getContent();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                     StringBuilder str = new StringBuilder();
                     String line = null;
                     while((line = reader.readLine()) != null){
                         str.append(line + "\n");
                     }
                     in.close();

                     result = str.toString();
                     //result = str.toString().substring(1,500);

                     Pattern p = Pattern.compile(
                             "<title>(.*)</title>",
                              Pattern.DOTALL
                         );
                     Matcher matcher = p.matcher(
                              result
                         );

                     if (matcher.find())
                     {
                          score = matcher.group(1).toString();

                     }

                     return score;

                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                     Toast.makeText(this, "IOException e  = " + e.toString(), Toast.LENGTH_LONG).show();
                     Log.d(TAG, "IOException e  = " + e.toString());
                        client.getConnectionManager().shutdown();
                     return "IOException e  = " + e.toString();
                  }catch(Exception ex){
                     result = "Error";
                     ex.printStackTrace();
                     Toast.makeText(this, "Exception ex  = " + ex.toString(), Toast.LENGTH_LONG).show();
                     Log.d(TAG,"Exception ex  = " + ex.toString());
                        client.getConnectionManager().shutdown();
           return "Exception ex  = " + ex.toString();
                 }
             } else {
                    client.getConnectionManager().shutdown();
                 return   "Error connecting" + response.getStatusLine().toString();
                 //sin.close();
             } //httpstatus
          } catch (SocketTimeoutException e) {
             e.printStackTrace();
             Toast.makeText(this, "SocketTimeoutException e  = " + e.toString(), Toast.LENGTH_LONG).show();
             Log.d(TAG, "SocketTimeoutException e  = " + e.toString());
             client.getConnectionManager().shutdown();
             return "SocketTimeoutException e  = " + e.toString();
          }catch(Exception ex){
              Toast.makeText(this, "Exception ex1  = " + ex.toString(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "Exception ex1  = " + ex.toString());
                client.getConnectionManager().shutdown();
                return  "Exception ex1  = " + ex.toString();
         }

Logcat错误消息
          W/System.err(18422): java.net.SocketTimeoutException
      W/System.err(18422):  at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:564)
      W/System.err(18422):  at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:88)
      W/System.err(18422):  at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
      W/System.err(18422):  at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
      W/System.err(18422):  at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
      W/System.err(18422):  at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
      W/System.err(18422):  at java.io.InputStreamReader.read(InputStreamReader.java:275)
      W/System.err(18422):  at java.io.BufferedReader.fillBuf(BufferedReader.java:155)
      W/System.err(18422):  at java.io.BufferedReader.readLine(BufferedReader.java:425)
      W/System.err(18422):  at com.warriorpoint.androidxmlsimple.MessageList.readFile(MessageList.java:214)
      W/System.err(18422):  at com.warriorpoint.androidxmlsimple.MessageList.access$1(MessageList.java:182)
      W/System.err(18422):  at com.warriorpoint.androidxmlsimple.MessageList$SelectDataTask.doInBackground(MessageList.java:158)
      W/System.err(18422):  at com.warriorpoint.androidxmlsimple.MessageList$SelectDataTask.doInBackground(MessageList.java:1)
      W/System.err(18422):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
      W/System.err(18422):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
      W/System.err(18422):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
      W/System.err(18422):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
      W/System.err(18422):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
      W/System.err(18422):  at java.lang.Thread.run(Thread.java:1096)
      W/dalvikvm(18422): threadid=7: thread exiting with uncaught exception (group=0x400207d8)
      E/AndroidRuntime(18422): FATAL EXCEPTION: AsyncTask #1
      E/AndroidRuntime(18422): java.lang.RuntimeException: An error occured while executing doInBackground()
      E/AndroidRuntime(18422):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
      E/AndroidRuntime(18422):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
      E/AndroidRuntime(18422):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
      E/AndroidRuntime(18422):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
      E/AndroidRuntime(18422):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
      E/AndroidRuntime(18422):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
      E/AndroidRuntime(18422):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
      E/AndroidRuntime(18422):  at java.lang.Thread.run(Thread.java:1096)
      E/AndroidRuntime(18422): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
      E/AndroidRuntime(18422):  at android.os.Handler.<init>(Handler.java:121)
      E/AndroidRuntime(18422):  at android.widget.Toast.<init>(Toast.java:68)
      E/AndroidRuntime(18422):  at android.widget.Toast.makeText(Toast.java:231)
      E/AndroidRuntime(18422):  at com.warriorpoint.androidxmlsimple.MessageList.readFile(MessageList.java:276)
      E/AndroidRuntime(18422):  at com.warriorpoint.androidxmlsimple.MessageList.access$1(MessageList.java:182)
      E/AndroidRuntime(18422):  at com.warriorpoint.androidxmlsimple.MessageList$SelectDataTask.doInBackground(MessageList.java:158)
      E/AndroidRuntime(18422):  at com.warriorpoint.androidxmlsimple.MessageList$SelectDataTask.doInBackground(MessageList.java:1)
      E/AndroidRuntime(18422):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
      E/AndroidRuntime(18422):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
      E/AndroidRuntime(18422):  ... 4 more
      W/ActivityManager(  158):   Force finishing activity com.warriorpoint.androidxmlsimple/.MessageList

最佳答案

SocketTimeoutException并非强制关闭的原因,异常堆栈跟踪只是打印到日志中,因为您要求将其打印出来(e.printStackTrace())。

这是真正的问题:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

要解决实际问题,请看这里:Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

关于android - Android:http套接字超时-强制关闭错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5230013/

10-11 02:07