0

I know similar questions are asked but the answers didn't work for me. I tried this answer but it throws null pointer exception. I also saw this answer but WifiP2pManager does not have any property or method that returns device name.

Can anyone please help?

I basically want to show user their device name and let them change it if they want to set custom name.

Thanks.

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122

1 Answers1

0

If you're still looking for the answer, here's how:

  1. Identify own device name

This becomes available upon receiving the WIFI_P2P_THIS_DEVICE_CHANGED_ACTION intent in your broadcast receiver. Simply use the deviceName member variable like so:

@Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();

  if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {

    WifiP2pDevice self = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);

    // Now self.deviceName gives you own device name

  } else if(WifiP2pManager.WIFI_P2P...) {
  ...


2. Change own device name

There's no method to change the device name using the WifiP2pManager as per the develper docs, and although a public setDeviceName() method exists in the source code, you can't call it on your object (probably to keep devs from calling it on an object representing a nearby peer device). What worked for me was to obtain a Method object representing said method and invoking it on my WifiP2pManager instance:

private WifiP2pManager manager;
private WifiP2pManager.Channel channel;

...

public void changeDeviceName(String deviceNewName) {
  try {
    Method method = manager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);

    method.invoke(manager, channel, deviceNewName, new WifiP2pManager.ActionListener() {

      @Override
      public void onSuccess() {
        Toast.makeText(MainActivity.this, "Name successfully changed", Toast.LENGTH_LONG).show();
      }

      @Override
      public void onFailure(int reason) {
        Toast.makeText(MainActivity.this, "Request failed: " + reason, Toast.LENGTH_SHORT).show();
        Log.d(TAG, "Name change failed: " + reason);
      }
    });

  } catch (Exception e) {
    e.printStackTrace();
  }
}

Alternatively, users can rename their device manually from the advanced WiFi settings (Preferences > Advanced > WiFi Direct > Configure Device),

EDIT: Starting with Pie, use of non-SDK interfaces (essentially classes, variables or methods marked with @hide, which you access using reflection) is being restricted and will eventually be disallowed. The above method is currently greylisted (which means support for reflecting it might be removed in the future). Read up more here: https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces