这不是一个重复的问题,我现在如何检查是否有互联网连接,我不知道的是如何在循环时弹出对话框并重试,直到互联网连接恢复
如果没有互联网连接,我正在尝试弹出"警报"对话框,然后等待用户点击"重试"当他按下按钮时,检查互联网连接,如果没有互联网连接,则再次弹出此警报对话框。
当我用if语句做这件事时,它效果很好——当没有互联网时弹出对话框,当点击"重试"时检查连接但是,当我尝试将其放入while循环中时,循环不会等待/向用户显示对话框。
做这件事的正确方法是什么?为什么现在不起作用?
while (netInfo == null || !netInfo.isConnected()) {
new AlertDialog.Builder(this)
.setTitle("title")
.setMessage("message")
.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
System.out.println("cm: "+cm+ " netinfo: "+ netInfo);
}
})
.show();
}
在actvity中onCreate()时尝试此代码调用getDATA()方法,它可能有助于
private void getDATA() {
boolean isProcess;
try {
isProcess = Utils.isNetworkConnected(class.this) || Utils.hasActiveInternetConnection(); //method to check internet connection
} catch (Exception e) {
isProcess = false;
e.printStackTrace();
}
if (isProcess) {
try {
AlertDialog.Builder builder =
new AlertDialog.Builder(class.this, R.style.AppCompatAlertDialogStyle);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("Internet not available?");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getDATA();
}
});
builder.setCancelable(false);
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Crouton.makeText(class.this, MessageConstant.MsgWiFi, Style.ALERT).show();
}
}