如何在while循环中使用handler并等待事件?

时间:2016-10-02 23:10:57

标签: android android-handler

我试图使用处理程序来等待我的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连接。 / p>

1 个答案:

答案 0 :(得分:0)

您将需要使用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);