【发布时间】:2015-08-06 04:07:45
【问题描述】:
它给出了一个空指针异常。我想获取通过wifi直接连接的设备的IP地址。如何做到这一点谁能解释一下?附上Screen看看。 提前致谢。
【问题讨论】:
-
我已经更新了我对您问题的回答。请检查一下,让我知道它是否适合您。
标签: android android-intent nullpointerexception action wifi-direct
它给出了一个空指针异常。我想获取通过wifi直接连接的设备的IP地址。如何做到这一点谁能解释一下?附上Screen看看。 提前致谢。
【问题讨论】:
标签: android android-intent nullpointerexception action wifi-direct
你可以使用下面的代码sn-p,当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 中添加读取外部存储权限。
【讨论】: