Wi-Fi Direct
Android now supports Wi-Fi Direct for peer-to-peer (P2P) connections between Android-powered devices and other device types without a hotspot or Internet connection. The Android framework provides a set of Wi-Fi P2P APIs that allow you to discover and connect to other devices when each device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer than a Bluetooth connection.
A new package, android.net.wifi.p2p, contains all the APIs for performing peer-to-peer connections with Wi-Fi. The primary class you need to work with is WifiP2pManager, which you can acquire by calling getSystemService(WIFI_P2P_SERVICE). The WifiP2pManager includes APIs that allow you to:
- Initialize your application for P2P connections by calling initialize()
- Discover nearby devices by calling discoverPeers()
- Start a P2P connection by calling connect()
- And more
Several other interfaces and classes are necessary as well, such as:
- The WifiP2pManager.ActionListener interface allows you to receive callbacks when an operation such as discovering peers or connecting to them succeeds or fails.
- WifiP2pManager.PeerListListener interface allows you to receive information about discovered peers. The callback provides a WifiP2pDeviceList, from which you can retrieve a WifiP2pDevice object for each device within range and get information such as the device name, address, device type, the WPS configurations the device supports, and more.
- The WifiP2pManager.GroupInfoListener interface allows you to receive information about a P2P group. The callback provides a WifiP2pGroup object, which provides group information such as the owner, the network name, and passphrase.
- WifiP2pManager.ConnectionInfoListener interface allows you to receive information about the current connection. The callback provides a WifiP2pInfo object, which has information such as whether a group has been formed and who is the group owner.
In order to use the Wi-Fi P2P APIs, your app must request the following user permissions:
- ACCESS_WIFI_STATE
- CHANGE_WIFI_STATE
- INTERNET (although your app doesn’t technically connect to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet permission).
The Android system also broadcasts several different actions during certain Wi-Fi P2P events:
- WIFI_P2P_CONNECTION_CHANGED_ACTION: The P2P connection state has changed. This carries EXTRA_WIFI_P2P_INFO with a WifiP2pInfo object and EXTRA_NETWORK_INFO with a NetworkInfo object.
- WIFI_P2P_STATE_CHANGED_ACTION: The P2P state has changed between enabled and disabled. It carries EXTRA_WIFI_STATE with either WIFI_P2P_STATE_DISABLED or WIFI_P2P_STATE_ENABLED
- WIFI_P2P_PEERS_CHANGED_ACTION: The list of peer devices has changed.
- WIFI_P2P_THIS_DEVICE_CHANGED_ACTION: The details for this device have changed.