rss reader方法不支持uses-sdk

时间:2013-11-18 13:26:59

标签: android rss

我使用此方法获取rss项目

public static ArrayList<RssItem> getRssItems(String feedUrl) {

    ArrayList<RssItem> rssItems = new ArrayList<RssItem>();

    try {
        URL url = new URL(feedUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();

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

            Document document = db.parse(is);
            Element element = document.getDocumentElement();

            NodeList nodeList = element.getElementsByTagName("item");

            if (nodeList.getLength() > 0) {
                for (int i = 0; i < nodeList.getLength(); i++) {

                    Element entry = (Element) nodeList.item(i);

                    Element _titleE = (Element) entry.getElementsByTagName(
                            "title").item(0);
                    Element _descriptionE = (Element) entry
                            .getElementsByTagName("description").item(0);
                    Element _pubDateE = (Element) entry
                            .getElementsByTagName("pubDate").item(0);
                    Element _linkE = (Element) entry.getElementsByTagName(
                            "link").item(0);

                    String _title = _titleE.getFirstChild().getNodeValue();
                    String _description = _descriptionE.getFirstChild()
                            .getNodeValue();
                    Date _pubDate = new Date(_pubDateE.getFirstChild()
                            .getNodeValue());
                    String _link = _linkE.getFirstChild().getNodeValue();

                    RssItem rssItem = new RssItem(_title, _description,
                            _pubDate, _link);

                    rssItems.add(rssItem);
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rssItems;
}

但是当我在manifest中设置uses-sdk时,在此字符串之后 if(conn.getResponseCode()== HttpURLConnection.HTTP_OK) 执行继续阻止捕获。当我从清单中删除uses-sdk时一切正常。我需要做什么才能使用-sdk但它有效?

1 个答案:

答案 0 :(得分:0)

这个问题并不能很好地描述问题,但是做出有根据的猜测,你得到NetworkOnMainThreadException

如果未在清单中指定targetSdkVersion,则默认为1并启用所有向后兼容功能,包括允许在UI线程上进行网络操作。当您指定目标SDK版本&gt; = 11且实际在API级别11或更高级别上运行时,您将获得NetworkOnMainThreadException

修复是使用例如后台线程对后台线程进行网络操作。 AsyncTask

规范参考:How to fix android.os.NetworkOnMainThreadException?