Daiwik Daarun
Daiwik Daarun

Reputation: 3974

Android: How to get current device WiFi-direct name

In a P2P setting, I understand how to get another device's name, but how do I get my own device's name? (the one displayed in WiFi-direct under settings).

I have checked WiFiManager, WiFiInfo, and more with no success.

Upvotes: 10

Views: 7104

Answers (4)

Benjamin Kielinski
Benjamin Kielinski

Reputation: 19

Once you got the manager, you can use WifiP2pManager.requestDeviceinfo() with the DeviceInfoListener

mManager.requestDeviceInfo(mChannel, wifiP2pDevice -> String deviceName = wifiP2pDevice.deviceName));

But it's only available from API29

Upvotes: 0

SafalFrom2050
SafalFrom2050

Reputation: 727

Simply in your broadcast receiver,

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

Upvotes: 0

After you turn on wifi on your device, it is send a WIFI_P2P_THIS_DEVICE_CHANGED_ACTION broadcast. You can catch this with a broadcast receiver and you can get a WifiP2pDevice object, that is your device.

 @Override
 public void onReceive(Context context, Intent intent) {
     WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
     String thisDeviceName = device.deviceName;
 }

Upvotes: 13

samsad
samsad

Reputation: 1241

Try this code:

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

Upvotes: 0

Related Questions