I am writing an Android application that needs to connect to different Wifi networks based on the user's selection. I need to retrieve the gateway IP address from the networkInfo. The Problem I am facing is that if I am connected to wifi network configuration A, and then want to switch to network configuration B, the wifi.getDhcpInfo(); returns to gateway IP address of network A. After several tries through the User interface workflow, it eventually returns the gateway IP of network B. Code snipet is below. Any ideas how to determine when the newly enabled network will return accurate Dhcp information so that I can get it reliably. Is there an ansynchronous event that I can catch for example, etc. Thanks.
WifiConfiguration config = wifiConfiguredNetworks.get(SSID);
enableNetworkResult = false;
enableNetworkResult = wifi.enableNetwork(config.networkId,true);
if (enableNetworkResult == true) {
this.networkInfo = wifi.getDhcpInfo(); // does not return proper IP info
this.DeviceIP = android.text.format.Formatter.formatIpAddress(networkInfo.gateway);
}
I have exactly same issue and able to fix it with workaround. Just need to create worker thread with checking wifiManager.getConnectionInfo().getIpAddress() == 0 Something like this:
final Handler h = new Handler();
final WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
new Thread(new Runnable() {
@Override
public void run() {
while (wifiManager.getConnectionInfo().getIpAddress() == 0) {
Log.d(TAG, "waiting for valid ip");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
h.post(new Runnable() {
@Override
public void run() {
// proceed here
}
});
}
}).start();
I also tried all possible listeners, receivers etc. Nothing helped. The only way to get valid dhcp info is to wait for not null ip address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With