我正在编写一个连接到网站并以 JSON 形式检索搜索结果的 Android 应用程序。此功能发生在 AsyncTask 中,它被设置为与 UI 分开的流。我需要处理连接中断/不存在/太潜在的情况。我需要处理这种情况,以便向用户显示一个 AlertDialog,让他们知道连接不好。我看到帖子建议为 URLConnection 设置超时参数,但我现在没有使用 URLConnection。
现在,当我有数据连接时,该功能完美地执行,但没有连接时则不然。当我运行模拟器并禁用我的 PC 的互联网连接时,运行该函数会显示“强制关闭”消息并产生 UnknownHostException。我遇到了这个异常,但我的应用程序仍然崩溃。
我还需要处理无法找到缩略图的情况,这会产生 FileNotFoundException。
请告诉我我应该怎么做。谢谢。
@Override
protected HashMap<String, String> doInBackground(Object... params) {
InputStream imageInput = null;
FileOutputStream imageOutput = null;
try {
URL url = new URL("http://www.samplewebsite.com/" + mProductID);
BufferedReader reader =
new BufferedReader(new InputStreamReader(url.openStream()));
String jsonOutput = "";
String temp = "";
while ((temp = reader.readLine()) != null) {
jsonOutput += temp;
}
JSONObject json = new JSONObject(jsonOutput);
// ... Do some JSON parsing and save values to HashMap
String filename = mProductID + "-thumbnail.jpg";
URL thumbnailURL = new URL("http://www.samplewebsite.com/img/" + mProductID + ".jpg");
imageInput = thumbnailURL.openConnection().getInputStream();
imageOutput = mContext.openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = imageInput.read(data)) != -1) {
imageOutput.write(data, 0, read);
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
try {
imageOutput.close();
imageInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return mProductInfoHashMap;
}