I'm developing an app with a built in feature to connect to a Wi-Fi access point. After a user has entered the password to the access point they want to connect, the code below is executed. My problem is that even after my android device successfully connects to an AP, after ~2 seconds, the if statement is run. Or sometimes it fails to connect, but the else statement runs. What am I doing wrong? Is there a simpler way to accomplish what I am trying to do?
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);