Android: 如何获取当前设备的WiFi-direct名称

10
在P2P环境中,我知道如何获取另一个设备的名称,但是如何获取自己设备的名称?(在设置下WiFi直连显示的那个)。
我已经检查过 WiFiManager、WiFiInfo 等,但没有成功。

你能编辑你的问题并展示代码吗? - Raptor
不确定要添加什么...我想做的就是访问设备的名称,类似于在蓝牙中调用BluetoothAdapter.getDefaultAdapter().getName() - Daiwik Daarun
WifiP2pDevice.deviceName?请参见此链接 - Raptor
你如何获取自己设备的WifiP2pDevice? - Daiwik Daarun
你找到解决方案了吗? - An-droid
很遗憾,我选择只存储一个“特定于应用程序”的Wi-Fi Direct密码,在托管Wi-Fi组时进行广播。 - Daiwik Daarun
4个回答

13
在您的设备上打开wifi后,它会发送一个WIFI_P2P_THIS_DEVICE_CHANGED_ACTION广播。您可以使用广播接收器捕获此广播,并获取一个WifiP2pDevice对象,代表您的设备。

打开设备上的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;
 }

1
当您注册WifiP2pBroadcastReceiver时,无论wifi是否已打开,您都将收到此调用。 - Jonathan
1
device is null, hence getting NullPointerException - Touhid

0

只需在您的广播接收器中,

 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); 
    }

0
一旦您获得了管理器,就可以使用WifiP2pManager.requestDeviceinfo()与DeviceInfoListener。
mManager.requestDeviceInfo(mChannel, wifiP2pDevice -> String deviceName = wifiP2pDevice.deviceName));

但它只能从API29及以上版本使用


0

尝试这段代码:

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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接