我的代码获取 RSS 提要并解析它。代码工作正常,但在某些函数中速度很慢(请参阅代码中的时间)。有什么建议吗?
URLConnection connection = feedUrl_.openConnection();
InputStream inputStream = connection.getInputStream(); // 15 sec
Reader reader = new InputStreamReader(inputStream, "UTF-8");
InputSource inputSource = new InputSource(reader);
doc = builder.parse(inputSource); // 60 sec
最佳答案
兄弟,试试用XMLPullParser解析数据吧,解析数据不会花太多时间,6-7秒。这是代码。试试这个:
onCreate()
{
try
{
URL url = null;
url = new URL("http://feeds.abcnews.com/abcnews/worldnewsheadlines");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); // extract the
// headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); // extract the link of
// article
}
} else if (eventType == XmlPullParser.END_TAG
&& xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
}
eventType = xpp.next(); // move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
我希望这个例子能帮到你。 :)
关于android - AVD 解析速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279387/