When we use a conventional Wi-Fi network we need a controller device known as WAP (Wireless Access Point). In a scenario where just two devices want to be connected with each other there must WAP to provide support. To avoid this complexity, Wi-Fi Alliance introduced a certification for wireless devices known as Wi-Fi Direct which allows two devices connect directly.
This is a game-changing technology for Wi-Fi devices to connect directly, making it simple and convenient to do things like print, share, synch and display.
Wi-Fi Direct in Android:
Wi-Fi Direct allows Android 4.0 (API level 14) or later devices with the appropriate hardware to connect directly to each other via Wi-Fi without an intermediate access point.
API Overview:
- WifiP2pManager class provides all methods to discover , request and connect to peers.
- Each method in WifiP2pManager implements a specific listener which is passed as parameter to allow you to be notified of the success or failure of method calls,
- Intents that notify you of specific events detected by the Wi-Fi Direct framework, such as a dropped connection or a newly discovered peer.
Connecting via Wi-Fi Direct:
- Application Permissions :
- To use Wi-Fi Direct, we need to add the
CHANGE_WIFI_STATE
,ACCESS_WIFI_STATE
, andINTERNET
permissions to your manifest. Wi-Fi Direct doesn’t require an internet connection, but it does use standard Java sockets, which require theINTERNET
permission. - Broadcast Receiver and Peer-To-Peer manager :
- We have to listen particular broadcasts when we use Wi-Fi Directs. These Broadcasts tell us about certain event that occurred.
WIFI_P2P_STATE_CHANGED_ACTION
WIFI_P2P_PEERS_CHANGED_ACTION
WIFI_P2P_CONNECTION_CHANGED_ACTION
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
- At the end of the
onCreate()
method, get an instance of theWifiP2pManager
, and call itsinitialize()
method. This method returns aWifiP2pManager.Channel
object, which you’ll use later to connect your app to the Wi-Fi Direct Framework. - Initiate Peer Discovery :
- To search near by Peers, WifiP2pManager class has one method discoverPeers() method. There are two argument supposed to be passed in this method:
- The
WifiP2pManager.Channel
you received back when you initialized the peer-to-peerWifiP2pManager.
- An implementation of
WifiP2pManager.ActionListener
with methods the system invokes for successful and unsuccessful discovery. - Fetch list of Peers :
- Implement the
WifiP2pManager.PeerListListener
interface, which provides information about the peers that Wi-Fi Direct has detected. - Connect to Peer :
- In order to connect to a peer, create a new
WifiP2pConfig
object, and copy data into it from theWifiP2pDevice
representing the device you want to connect to. Then call theconnect()
method.