我正在开发一款内置功能的应用,可连接到Wi-Fi接入点。用户输入密码到他们想要连接的接入点后,执行以下代码。 我的问题是,即使我的android设备成功连接到AP后,约2秒后,运行if语句。或者有时它无法连接,但else语句运行。我究竟做错了什么?有没有更简单的方法来完成我想要做的事情?
final WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (wifiMgr.isWifiEnabled()) {
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
if (wifiInfo.getNetworkId() == -1) {
Log.v("rht", "Problems connecting. Try again.");
Toast.makeText(NetworkScanner.this, "Problems connecting. Try again.", Toast.LENGTH_LONG).show();
}
else {
Log.v("rht", "Successfully Connected.");
}
}
}
}, 4000);
答案 0 :(得分:1)
你可以这样做..
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 200ms
}
}, 200);
此解决方案仅适用于UI线程。否则在普通线程上,你需要实现looper,这不是最好的版本..
了解更多信息you can visit this link
答案 1 :(得分:0)
这是init Handler对象
Handler mHandler = new Handler();
mHandler.posttoDealy(run,1000*10) // 10 Sec
调用为您的任务运行线程
Runnable run = new Runnable() {
@Override
public void run() {
//this will run after ten Sec
//mHandler.posttoDealy(run,1000*10) // 10 Sec for again and again loop
}
})
删除处理程序
mHandler.removeCallback(run)
答案 2 :(得分:0)
使用Supplicant状态确实具有魅力。出于某种原因" wifiInfo.getNetworkId()== -1"给了我不可预知的结果。最终我发现了一种不同的方法来检查我的Android设备是否连接到网络。 非常感谢Donal Rafferty和Armand。他们都为this SO question
做出了贡献 final WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (wifiMgr.isWifiEnabled()) {
SupplicantState supState;
supState = wifiInfo.getSupplicantState();
if(supState != SupplicantState.COMPLETED) {
Log.v("rht", "Problems connecting. Try again.");
}
else {
Log.v("rht", "Successfully Connected.");
}
}
}
}, 4000);