android - Connecting to a WiFi P2P device without discovering peers

I want to establish a WiFi-Direct Connection with another device peered through NFC. My steps are as follows:

First, Device A gets its own WiFiP2P address and transmits it to Device B via NFC.

Then, Device B tries to establish a connection with Device A using the provided address.

As you can see I didn't involve discovering peers in the process. But when Device B is trying to connect, the result is always failed (reason 0, this should be ERROR).

I think this might be related to device visibility, but I don't know and can't find any code to make a device visible.

Here's my code:

 //NOTE: These code should be executed on Device B
 //Starting WiFi Direct Transmission
 //First we should establish a connection
 WifiP2pConfig config = new WifiP2pConfig();
 config.deviceAddress = remoteWifiP2pDevice; 
 //remoteWifiP2pDevice is the address of device A obtained from NFC
 config.wps.setup = WpsInfo.PBC;
 mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            //success logic
            Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
            if (!FILE_RECV)
            {
                new SendFilesTask().execute("");
            }
        }
        @Override
        public void onFailure(int reason) {
            //failure logic
            Toast.makeText(MainActivity.this, "failed" + reason, Toast.LENGTH_SHORT).show();
        }
    });

In OnCreate() I have

intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);         
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);

The WifiDirectBroadcastReceiver has code only related to getting Device A's address and can be considered empty.

So what's wrong with these and how can I fix it? Thanks in advance.

P.S. If I connect Device A and B manually, and run my code again, it returns success.

1 answer

  • answered 2017-07-21 14:46 Kavin Zhao

    I have discovered that delaying several seconds will make the connection succeed. I don't know the reason, but this can be used as a workaround.

    So after all is there a better solution to this? And why does the delay work?