如何在wifi直接获取Wifip2pInfo对象

时间:2015-08-06 04:07:45

标签: android android-intent nullpointerexception action wifi-direct

它给出了一个空指针异常。我想得到一个通过wifi直接连接的设备的IP地址。如何做到这一点可以解释一个人吗?附上一个msaffitz来看看。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码段,当WiFiP2pInfo连接时,它不为空,但是当没有连接或连接丢失时,它将为空。

if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION
            .equals(action)) {

        if (manager == null) {
            return;
        }

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

        if (networkInfo.isConnected()) {
            manager.requestConnectionInfo(channel,
                    new ConnectionInfoListener() {

                        @Override
                        public void onConnectionInfoAvailable(
                                WifiP2pInfo info) {
                            if (info != null) {
                                activity.setConnectionInfo(info); // When connection is established with other device, We can find that info from wifiP2pInfo here.
                            }
                        }
                    }

            );
        } else {
            activity.resetData(); // When connection lost then we can reset data w.r.t that connection.
        }
    }

以下代码有助于查找客户和所有者的地址,

public static String getDestinationDeviceIpAddress(WifiP2pInfo wifiP2pInfo) {
    String destinationAddress;
    if (wifiP2pInfo.isGroupOwner) {
        destinationAddress = WifiDirectUtil.getIPFromMac();

    } else {
        destinationAddress = wifiP2pInfo.groupOwnerAddress.getHostAddress();
    }
    return destinationAddress;
}

    public static String getIPFromMac() {
    BufferedReader br = null;
    boolean isFirstLine = true;
    String ipAddress = null;
    try {

        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;

        while ((line = br.readLine()) != null) {
            if (isFirstLine) {
                isFirstLine = false;
                continue;
            }

            String[] splitted = line.split(" +");
            Log.d(TAG, "** length **" + splitted.length);
            if (splitted.length >= 4) {

                String device = splitted[5];
                Log.d(TAG, device);
                if (device.contains("p2p")) {
                    ipAddress = splitted[0];
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ipAddress;
}

在manifest.xml中添加权限读取外部存储空间