我在android和java中有这个代码。当他的Internet连接出现问题或网站无法访问时,我想向用户显示一个对话框。我尝试将我的代码放入try-catch
块,但是当Internet连接出现问题时我的应用程序已关闭。我想向用户显示一条消息,而不是关闭应用程序。
HttpPost ht = new HttpPost("http://yahoo.com");
HttpClient hc = new DefaultHttpClient();
HttpResponse hr = null;
try {
hr = hc.execute(ht);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String htmlTemp = "";
try {
HttpEntity he = hr.getEntity();
htmlTemp = new String(EntityUtils.toString(he));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
您可以尝试将UnknownHostException
添加到catch中,也可以在调用request之前使用此方法:
public static boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
答案 1 :(得分:0)
您是否在清单文件中声明了此使用权限?
<uses-permission android:name="android.permission.INTERNET" />