我在 Async 任务中运行一个函数以从我的服务器上的 url 获取提要,它可以工作,但是当没有 Internet 连接时,它会通过给出错误消息来停止我的应用程序。
我不知道如何处理这个,反正这里是我的代码
获取提要的功能
public void getContent(){
// Initializing instance variables
headlines = new ArrayList<String>();
links = new ArrayList<String>();
server_images = new ArrayList<String>();
try {
URL url = new URL("http://www.uglobal.org/androidServer/courses_list.xml");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
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 (xpp.getName().equalsIgnoreCase("image")) {
if (insideItem)
server_images.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 (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
比我在异步任务中运行这个函数
异步任务
private class PostTask extends AsyncTask<String, Integer, String>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(ListViewImagesActivity.this, "Loading","Getting Feed ", true);
}
protected String doInBackground(String... arg0) {
getContent();
return null;
}
}
现在,如果我有 Internet 连接,它可以正常工作,但是当我失去连接时,它会杀死我的应用程序并显示错误“应用程序无响应”
为什么我不想依赖连接管理器
Connectivity Manager 只是寻找 Internet 连接,如果我在代理后面运行并且我需要登录到我的代理服务器才能访问 Internet,该怎么办?
有什么办法至少可以防止我的应用程序被杀死。