抓住连接失败?

时间:2011-12-31 11:27:59

标签: android

我正在使用SAXParserFactory和XML阅读器从API获取。但有时当互联网连接断开时,它会卡住并且应用程序崩溃。

我对异常处理的概念并不是那么好。我希望停止该操作,并希望在连接失败时显示自定义消息。

2 个答案:

答案 0 :(得分:1)

您可以执行类似

的操作
try {
   ... do the IO and SAX parsing
} catch (Exception e) {
  Toast.makeToast(context, "Failure: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}

话虽如此:在Android 3及更高版本中,您的网络IO需要处于后台任务(当您在UI线程中执行网络IO时,系统将终止您的应用程序),因此您需要将io置于background,根据定义,无法访问UI。

这里的模式(伪代码)可以提供帮助:

class MyAsyncTask extends AsyncTask {

  String doInBackground() {

     try { 
         ... do IO / parsing
     }
     catch (Exception e) {
         return e.getMessage();
     }
     return "ok";
  }

  onPostExecute(String in) {
    Toast.makeToas(... in ... );
  }
}

答案 1 :(得分:0)

以下是一个示例代码,详细说明了如何在Android中执行网络通信:

try {
url = new URL(ForumURL);
URLConnection connection = url.openConnection();
//Set connection time out to 10 secs
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setConnectTimeout(10*1000);

int responseCode = httpConnection.getResponseCode();    
if(responseCode == HttpURLConnection.HTTP_OK)
 {
    InputStream in = httpConnection.getInputStream();

    DocumentBuilderFactory dbf;
    dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document dom = db.parse(in);
 } //You can put an else condition here, if you want to process any error situations.

} catch (Exception e) { 
    //Your exception handler code here.
    return;
  }//catch (Exception e)    

谨慎一点。在Android中执行网络通信时,make是使用单独的线程进行的,而不是来自主UI线程。原因是,如果您在慢速网络上执行网络操作,Android操作系统将使用ANR终止您的应用程序。

相关问题