Check whether android wifip2p connection was succe

2019-02-24 13:32发布

问题:

I am connecting two android devices via Wifi Direct. I created a group using Wifip2pManager.createGroup on the first device.

Now, on the second device I call the Wifip2pManager.connect method. But the connect method is succesful, even if the first device declines the connection since it only checks for successful initialization. How do I check if the other device accepted the connection ?

回答1:

The class needs to implement ConnectionInfoListener. And in the function onConnectionInfoAvailable(final WifiP2pInfo info) you can check if a successful connection has been established or not. The info argument of type WifiP2pInfo contains the information about the connection. It contains a boolean called groupFormed which indicates if a p2p group has been successfully formed. You can also retrieve from it if the device is groupOwner and the IP of the groupOwner, etc.

@Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {

        // After the group negotiation, we check if this device 
        // is acting as group owner

        if (info.groupFormed && !info.isGroupOwner) {

            // Do whatever you want the group owner to do

        } else if (info.groupFormed) {
            // The device now act as the slave device, 
            // and the other connected device is group owner
    }

Google provides a very good demo app that uses WiFi Direct to send an image between 2 devices. Check its implementation and try to build on top of it. Link: http://developer.android.com/guide/topics/connectivity/wifip2p.html

Hope this helps. Let me know if you have any questions.