Android unknownhostexception

时间:2010-08-23 19:17:44

标签: android connection

我有以下代码,如果没有连接到互联网命中捕获但崩溃应用程序与主题中的错误。是否有一种优雅的方式来检测连接是否正常或只是忽略它?

 try {

        GeoPoint center = myMapView.getMapCenter();
        double minLat = (double) (center.getLatitudeE6() - (myMapView
                .getLatitudeSpan() / 2)) / 1E6;
        double maxLat = (double) (center.getLatitudeE6() + (myMapView
                .getLatitudeSpan() / 2)) / 1E6;
        double minLng = (double) (center.getLongitudeE6() - (myMapView
                .getLongitudeSpan() / 2)) / 1E6;
        double maxLng = (double) (center.getLongitudeE6() + (myMapView
                .getLongitudeSpan() / 2)) / 1E6;

        /* Create a URL we want to load some xml-data from. */
        URL url = new URL(
                "http://www.test.com/feed.asp?maxlat="
                        + Double.toString(maxLat) + "&maxlon="
                        + Double.toString(maxLng) + "&minlat="
                        + Double.toString(minLat) + "&minlon="
                        + Double.toString(minLng));

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();
        /* Create a new ContentHandler and apply it to the XML-Reader */
        XMLHandler myXMLHandler = new XMLHandler();
        xr.setContentHandler(myXMLHandler);

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(url.openStream()));
        /* Parsing has finished. */

        /* Our ExampleHandler now provides the parsed data to us. */
        /*
         * ParsedExampleDataSet parsedExampleDataSet =
         * myExampleHandler.getParsedData();
         */
        ArrayList<Ship> shipArray = myXMLHandler.getShipArray();
        ArrayList<pfOverlayItem> overArray = myXMLHandler.getOverlayArray();
        mainOverlayArray = overArray;
        pfOverlayItem tempOver = null;

        Drawable marker = null;
        for (int i = 0; i < mainOverlayArray.size(); i++) {
            tempOver = mainOverlayArray.get(i);
            // tempOver.setMarker(getIcon(tempOver.getshipTypeInt()));
            tempOver.setMarker(getPlaneIcon(tempOver.getcourse()));
        }

        sites = new SitesOverlay();

    } catch (Exception e) {
        /* Display any Error to the GUI. */
        Log.e("Error", "Problem processing XML", e);
    }

3 个答案:

答案 0 :(得分:2)

从URL流中解析XML似乎是一个可怕的想法。为什么不完全获取流,然后解析它?


 public static String doGet(String url)throws ClientProtocolException, IOException{
  HttpGet getRequest = new HttpGet(url);
  HttpClient client = new DefaultHttpClient();
  HttpResponse response = client.execute(getRequest);

  return responseToString(response);


private static String responseToString(HttpResponse httpResponse)
 throws IllegalStateException, IOException{
  StringBuilder response = new StringBuilder();
  String aLine = new String();

  //InputStream to String conversion
  InputStream is = httpResponse.getEntity().getContent();
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));

  while( (aLine = reader.readLine()) != null){
   response.append(aLine);
  }
  reader.close();

  return response.toString();
 }


string serverInterestURI = 'www.test.com/whatever.php?something=what&other=lolwut'
String response = ServerHttpRequest.doGet(serverInterestURI);


SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = null;
        XMLReader xr = null;
        MatchedUsersParser myXmlHandler = null;
  try {
   sp = spf.newSAXParser();
   // Get the XMLReader of the SAXParser we created.
         xr = sp.getXMLReader();
         // Create a new ContentHandler and apply it to the XML-Reader
         myXmlHandler = new MatchedUsersParser();
         xr.setContentHandler(myXmlHandler);
         // Parse the xml-data from the server response.
         xr.parse(new InputSource(new StringReader(response)));
         // Parsing has finished.
  } catch (ParserConfigurationException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (SAXException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }

答案 1 :(得分:1)

我用它来检查互联网

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return true;
    }
    return true;
}

答案 2 :(得分:0)

正如公制152所述,新用户很容易错过在清单中添加正确的权限!

在这种情况下,添加<uses-permission android:name="android.permission.INTERNET" />为我带来了魔力!