在P2P环境中,我知道如何获取另一个设备的名称,但是如何获取自己设备的名称?(在设置下WiFi直连显示的那个)。
我已经检查过 WiFiManager、WiFiInfo 等,但没有成功。
我已经检查过 WiFiManager、WiFiInfo 等,但没有成功。
打开设备上的Wi-Fi后,它会发送名为WIFI_P2P_THIS_DEVICE_CHANGED_ACTION的广播。您可以使用广播接收器捕获此广播,并获取一个WifiP2pDevice对象,该对象表示您的设备。
@Override
public void onReceive(Context context, Intent intent) {
WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
String thisDeviceName = device.deviceName;
}
device
is null, hence getting NullPointerException
- Touhid只需在您的广播接收器中,
if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
WifiP2pDevice myDevice =(WifiP2pDevice)intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
Log.d("Wifi Direct: My Device",myDevice.devicename);
}
mManager.requestDeviceInfo(mChannel, wifiP2pDevice -> String deviceName = wifiP2pDevice.deviceName));
但它只能从API29及以上版本使用
尝试这段代码:
public static String getHostName(String defValue) {
try {
Method getString = Build.class.getDeclaredMethod("getString", String.class);
getString.setAccessible(true);
return getString.invoke(null, "net.hostname").toString();
} catch (Exception ex) {
return defValue;
}
}
BluetoothAdapter.getDefaultAdapter().getName()
。 - Daiwik DaarunWifiP2pDevice.deviceName
?请参见此链接。 - Raptor