Android 中的 wifi.getDhcpInfo() 返回错误的 IP 网关
我正在编写一个Android应用程序,需要根据用户的选择连接到不同的Wifi网络。我需要从networkInfo 中检索网关IP 地址。我面临的问题是,如果我连接到wifi网络配置A,然后想切换到网络配置B,则 wifi.getDhcpInfo();返回网络 A 的网关 IP 地址。经过用户界面工作流程的多次尝试,它最终返回网络 B 的网关 IP。代码片段如下。任何想法如何确定新启用的网络何时返回准确的 Dhcp 信息,以便我可以可靠地获取它。是否有我可以捕获的异步事件,例如等等。谢谢。
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 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有完全相同的问题,并且能够通过解决方法解决它。只需要创建工作线程并检查 wifiManager.getConnectionInfo().getIpAddress() == 0
像这样的事情:
我还尝试了所有可能的监听器、接收器等。没有任何帮助。获取有效 dhcp 信息的唯一方法是等待非空 ip 地址。
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:
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.
尝试在监听 WIFI_STATE_CHANGED 事件时捕获 WifiManager.WIFI_STATE_ENABLED - 此状态将在所有连接过程完成后出现,因此在此阶段应正确设置网关 ip。
这应该转到您的
onResume
函数:this - 到
onPause
这是接收器本身
Try to catch WifiManager.WIFI_STATE_ENABLED while listening to WIFI_STATE_CHANGED event- this state will come after all connection procedures are finished, so gateway ip should be set properly at this stage.
this should go to your
onResume
function:this - to
onPause
and this is receiver itself