Skip to content Skip to sidebar Skip to footer

Android Wi-fi Direct: Onpeersavailable

I'm developping a simple application based on WiFi Direct for Android that has to connect two devices. To do so I need to call to the función onPeersAvailable(myPeerListListener),

Solution 1:

dtheo has answered and point to the nice Android tutorial about this topic. I will just make changes on the OP's code to show how to achieve the requested functions.

According to the official Android guide here, the wifip2p discovery api should be used in this way:

In your MainActivity class:

mManager.discoverPeers(mChannel, newWifiP2pManager.ActionListener() {
    publicvoidonSuccess() {
        TextDebug.setText("Ha habido éxito buscando Peers");
    }

    publicvoidonFailure(int reasonCode) {
        TextDebug.setText("Algo ha salido mal buscando Peers");
    }
});

// ############# DELETE THE FOLLOWING LINE #############
onPeersAvailable(myPeerListListener); // <<<<<<< DELETE THIS LINE

And in your BroadcastReceiver class, do the following instead:

@OverridepublicvoidonReceive(Context context, Intent intent) {
    ...    
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        ...
    } elseif (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        if (manager != null) {
            manager.requestPeers(channel, newWifiP2pManager.PeerListListener() {
            @OverridepublicvoidonPeersAvailable(WifiP2pDeviceList peers) {
                Log.d(TAG,String.format("PeerListListener: %d peers available, updating device list", peers.getDeviceList().size()));

                // DO WHATEVER YOU WANT HERE// YOU CAN GET ACCESS TO ALL THE DEVICES YOU FOUND FROM peers OBJECT

            }
        });
        }
    } elseif (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Respond to new connection or disconnections
    } elseif (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        // Respond to this device's wifi state changing
    }
}

Solution 2:

dtheo has answered the question.

I would just like to add a small side-note: For Wi-Fi Direct, both devices needs to be scanning at the same time to discover each other. There is also a scanning time-out which means that discoverability could be lost after some time.

Solution 3:

You should implement the onPeersAvailable method inside the PeerListListener.

Please see http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html for more information.

Post a Comment for "Android Wi-fi Direct: Onpeersavailable"