我想要显示消息" No Internet Connection"如果我的应用在用户访问时未连接到互联网。默认情况下,它显示"页面未找到...(网址)" 。但我想向用户显示一条消息"要检查互联网连接"如果在访问我的应用程序时设备未连接到Internet。谁能建议我怎么做?谢谢......
答案 0 :(得分:0)
创建一个名为ConnectionDetector的单独类来检测互联网的可用性
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Activity context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length;)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
else {
showAlertDialog(_context, "No Internet Connection",
"You don't have internet connection.");
return false;
}
}
return false;
}
public void showAlertDialog(Context context, String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
}
像这样称呼这个:
ConnectionDetector connectionDetector = new ConnectionDetector(this);
if (connectionDetector.isConnectingToInternet()) {
// do your stuff
}