WiFi Direct device connection with other Android devices

扶醉桌前 提交于 2019-12-01 13:39:09

It is possible. Code taken from a talk I gave at Droidcon UK 2013.

You need to call the createGroup(WifiP2pManager.Channel c, WifiP2pManager.ActionListener listener) method of the WifiP2pManager class. This will create a Wi-Fi Direct group that supports legacy Wi-Fi connections.

Prior to the call, you need to register a broadcast receiver similar to this:

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals
            (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)){
            wifiP2pManager.requestGroupInfo(channel,
                new WifiP2pManager.GroupInfoListener() {
                @Override
                public void onGroupInfoAvailable(WifiP2pGroup group) {
                    if(group != null){
                        // clients require these
                        String ssid = group.getNetworkName(),
                        String passphrase = group.getPassphrase() 
                    }
                }
            });
        }
    }
};

The other devices can then use Wi-Fi to connect to the Wi-Fi Direct device, once they have the ssid and passphrase.

Stephen's answer is great, but I found it's better to get the group info at

WIFI_P2P_CONNECTION_CHANGED_ACTION

...

if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
    WifiP2pInfo wifiP2pInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO);
    if (networkInfo.isConnected() && wifiP2pInfo.groupFormed) {
            if (wifiP2pInfo.isGroupOwner) {
                wifiP2pManager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
                    @Override
                    public void onGroupInfoAvailable(final WifiP2pGroup wifiP2pGroup) {
                        if (wifiP2pGroup != null) {
                            // clients require these
                            String ssid = wifiP2pGroup.getNetworkName();
                            String passphrase = wifiP2pGroup.getPassphrase();
                            ...
                        }
                    }
                }
            }
        }
    }
}
...

Because this can make sure the access point is created and current device is the group owner (GO).

It is possible according to the WiFi Direct documentation, as mentiond here.

If I re-phrase the documentation,

Create a p2p group with the current device as the group owner.This essentially creates an access point that can accept connections from legacy clients as well as other p2p devices

but the guides are for a pretty narrow scope. you'll have to do a bit of research to find out how to implement!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!