【问题标题】:How to use handler in a while loop and wait for an event?如何在while循环中使用处理程序并等待事件?
【发布时间】:2016-10-02 23:10:57
【问题描述】:

我正在尝试使用处理程序来等待我的 wifi 连接。这是我正在使用的代码:

    final AlertDialog alertDialog2 = new AlertDialog.Builder(new android.view.ContextThemeWrapper(context, R.style.AlertDialogCustom)).create();
    alertDialog2.setTitle("Loading...");
    alertDialog2.setIcon(R.drawable.check);
    alertDialog2.show();
    Handler handler = new Handler();
    int count = 0;
    while (!isConnected() /*Check wifi connection*/) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                alertDialog2.dismiss();
                // do other thing
            }
        }, 200);
        count++;
        /*stop the loop after 20s*/
        if (count > 100) {
            break;
        }
    }

正如您在这段代码中看到的那样,我想在操作期间显示一个正在加载的 alertDialog,当它完成时我想停止它以通知用户他的 wifi 连接。

【问题讨论】:

    标签: android android-handler


    【解决方案1】:

    您需要使用 WIFI 广播接收器。

    首先您需要显示对话框,然后注册 wifi 广播接收器,它会告诉您 WIFI 状态何时更改以及何时收到您想要关闭对话框的状态。

    参考以下链接了解如何检测 WIFI 状态变化

    How to detect when WIFI Connection has been established in Android?

    final AlertDialog alertDialog2 = new AlertDialog.Builder(new android.view.ContextThemeWrapper(context, R.style.AlertDialogCustom)).create();
    alertDialog2.setTitle("Loading...");
    alertDialog2.setIcon(R.drawable.check);
    alertDialog2.show();
    
    private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
    
    @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equalsIgnoreCase("android.net.wifi.STATE_CHANGE")) {
                Log.d(TAG,"WIFI STATE CHANGED");
    alertDialog2. dismiss();
            }
        }
    };
    
    IntentFilter intent = new IntentFilter("");
    registerReceiver(myReceiver, intent);
    

    【讨论】:

    • 感谢您的回答,但问题是只有在连接 Wifi 时才会通知我。但是我怎么知道它是否失败了?这就是我想要一个计时器的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多