如何在while循环中使用处理函数并等待事件?
问题描述:
我正在尝试使用处理程序来等待我的无线连接。这一段代码我使用:如何在while循环中使用处理函数并等待事件?
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连接。
答
您将需要使用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连接通知。但是我怎么知道它是否失败?这就是为什么我想要一个计时器。 –