我为我的 android 应用程序构建了对话框。它运行良好,但我遇到了一些与对话框相关的问题。
(1) 我想要连接互联网或 WiFi 时。自动对话框消失。
(2) 如果互联网连接丢失,应用程序正在运行。对话框再次自动出现。
if (!isConnected(Dashboard.this)) buildDialog(Dashboard.this).show();
else {
setContentView(R.layout.activity_dashboard);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or WiFi to access this. Press OK to Exit");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Dashboard.super.onBackPressed();
}
});
return builder;
}