Android 如何在wifi direct中获取Wifip2pInfo对象
它给出了一个空指针异常。我想获得通过wifi直接连接的设备的IP地址。如何做到这一点,有人能解释吗?附件a查看。Android 如何在wifi direct中获取Wifip2pInfo对象,android,android-intent,nullpointerexception,action,wifi-direct,Android,Android Intent,Nullpointerexception,Action,Wifi Direct,它给出了一个空指针异常。我想获得通过wifi直接连接的设备的IP地址。如何做到这一点,有人能解释吗?附件a查看。 提前感谢。您可以使用以下代码段,当WiFiP2pInfo有连接时,它不是null,但当没有连接或连接丢失时,它将是null if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION .equals(action)) { if (manager == null) { re
提前感谢。您可以使用以下代码段,当WiFiP2pInfo有连接时,它不是null,但当没有连接或连接丢失时,它将是null
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中添加读取外部存储的权限。我已经更新了关于您问题的答案。请检查它,让我知道它是否为您工作。感谢Umang Kothari提供的信息,但那里的“活动”是什么?它显示了一些错误,表示符号无法解析,activity是您已从中注册此接收器的受尊重活动的对象,并且您希望返回该活动的连接信息。它在android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)处发出新错误Kothari“android.os.NetworkOnMainThreadException”位于com.example.hp1.myproject3.MainActivity$Myreceiver$2.onConnectionInfoAvailable(MainActivity.java:231)的java.net.InetAddress.getHostName(InetAddress.java:307)的java.net.InetAddress.getHostByAddrImpl(InetAddress.java:438)在android.net.wifi.p2p.WifiP2pManager$Channel$P2pHandler.handlemes,因为获取IP地址是网络操作,您必须在工作线程而不是UI线程中执行此类操作。使用asynctask机制获取IP地址它仍然在信息对象kothari上显示空指针异常。无论如何,非常感谢您的帮助