【问题标题】:Pop Alert Dialog while no internet and try again - Android [duplicate]没有互联网时弹出警报对话框,然后重试 - Android [重复]
【发布时间】:2016-03-29 17:26:21
【问题描述】:

这不是一个重复的问题,我现在如何检查是否有互联网连接,我不知道的是如何在 while 循环中弹出对话框并重试直到互联网连接恢复

如果没有互联网连接,我正在尝试弹出警报对话框, 然后等待用户点击“再试一次” 当他点击按钮时,检查互联网连接,如果没有互联网连接,则再次弹出此警报对话框。

当我使用 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();
}

【问题讨论】:

标签: android android-alertdialog internet-connection


【解决方案1】:

在活动中的 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();
        }
    }

【讨论】:

  • 你能解释一下为什么我的while循环不起作用吗?
  • 调试您的代码或发布完整代码。
  • 这是完整的代码。如果没有互联网连接,它唯一的 while 循环会弹出对话框
  • 如果有帮助,请使用此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
相关资源
最近更新 更多