How to get wifi direct devices name from WifiP2pDe

2020-07-22 18:34发布

问题:

I want to get the wi-fi direct name when I execute request peers, here is my code:

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

    Log.d(tag, "success discover the peers ");

    if (mManager != null) {
        mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {

            @Override
            public void onPeersAvailable(WifiP2pDeviceList peers) {
                // TODO Auto-generated method stub

                if (peers != null) {
                    if (device.deviceName.equals("ABC")) {
                        Log.d(tag, "found device!!! ");

                        Toast.makeText(getApplicationContext(), "FOUND!!", Toast.LENGTH_SHORT).show();

                    }
                }
            }
        });
    } else {
        Log.d(tag, "mMaganger == null");
    }
}

I want to get the deviceName from the list of peers so that I can found that one named "ABC". Any idea?

回答1:

If you want others device name:

wifiP2pManager.requestPeers(wifiChannel, new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {

            for (WifiP2pDevice device : wifiP2pDeviceList.getDeviceList())
            {
                if (device.deviceName.equals("ABC")) Log.d(tag, "found device!!! ");
                // device.deviceName
            }
        }
    });

If you want your device name get it in the receiver:

if (action.equals(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION))
{
    WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
    // device.deviceName
}

If you want to change device name:

try {
    Method method = wifiP2pManager.getClass().getMethod("setDeviceName",
        WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);

    method.invoke(wifiP2pManager, wifiChannel, "New Device Name", new WifiP2pManager.ActionListener() {
        public void onSuccess() {}

        public void onFailure(int reason) {}
    });
} catch (Exception e)   {}


回答2:

You have the object for WifiP2pDeviceList(peers)

Call the method getDeviceList() on peers which returns a collection(list) of P2p devices Collection<WifiP2pDevice>

Then iterate through the collection element which is a WifiP2pDevice and it would contain the deviceName property which is what you need exactly.

Refer this training from android developers

Hope you are able to get it