Android WifiInfo.getIpAddress在Android 6的Nexus 5X上返回0 Android

时间:2016-10-18 03:41:34

标签: java android networking ip wifi

这是我正在做的事情:

我注册了这样的BroadcastReceiver:

mConnectionChangeReceiver = new ConnectionChangeReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mContext.registerReceiver(mConnectionChangeReceiver, filter, null, handler);

然后我会自动尝试连接到特定的WiFi。像这样:

if (!mWifiManager.isWifiEnabled()) {
    mWifiManager.setWifiEnabled(true);
}
mWifiManager.enableNetwork(mCurrentNetworkId, true);

我按预期收到广播接收器事件。在onReceive()内,我检查了SSID和SuplicantState。问题是当我试图获取手机IP地址时。如果手机上启用了蜂窝网络,则WifiInfo.getIpAddress会返回0,但如果已禁用,则会发挥作用。

请注意,如果在两种情况下(有/没有蜂窝网络)设备已连接到SSID,这将有效。为此,必须关闭wifi或在运行代码之前必须将手机连接到另一个wifi。

以下是代码:

public void onReceive(Context context, Intent intent) {        
    WifiInfo wifiInfo = mWifiManager.getConnectionInfo();

    //..... Here's the code that compares SSID

    if (isConnectedToSSID() && (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {    
        mIpAddress = NetworkHelper.getIpAddress(wifiInfo);   
    }
}

public static String getIpAddress(WifiInfo pWifiInfo) {
    int ipAddress = pWifiInfo.getIpAddress();
    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
    String ipAddressString = null;
    try {
        ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
        ex.printStackTrace();
    }
    return ipAddressString;
}

为什么会发生这种情况?

0 个答案:

没有答案