WiFi P2P in Android

Source: Internet
Author: User

WiFi P2P in Android

WiFi P2P in Android allows devices in a certain range to directly connect to IOT platform through Wifi instead of through hot spots or the Internet.

Need to use WiFi P2PAndroid API Level> = 14And do not forget to add the following five permissions to the Manifest file:

● Android. permission. ACCESS_WIFI_STATE

● Android. permission. CHANGE_WIFI_STATE

● Android. permission. ACCESS_NETWORK_STATE

● Android. permission. CHANGE_NETWORK_STATE

● Android. permission. INTERNET (WiFi P2P does not need to connect to the INTERNET, but this permission is required because Java Socket is used)

 

Wi-Fi P2P operations rely almost on WifiP2pManager, so if your program needs to use the WiFi P2P function, you can set a global variable wifiP2pManager, and then in onCreate () obtain the WifiP2pManager object in the life function:

 

wifiP2pManager = (WifiP2pManager) getApplicationContext().getSystemService(Context.WIFI_P2P_SERVICE);

WifiP2pManager has the following methods to facilitate P2P operations:

 

 

Method Function
initialize() You must call this method before using the Wi-Fi P2P function to register our applications through the WiFi P2P framework.
connect() Perform P2P connection with the specified device (WifiP2pDevice object) based on the configuration (WifiP2pConfig object)
cancelConnect() Disable a P2P connection
requestConnectInfo() Obtains the connection information of a device.
createGroup() Create a P2P team with the current device as the team leader
removeGroup() Remove the Current P2P Group
requestGroupInfo() Obtain P2P group information
discoverPeers() Initialize the peers discovery operation
requestPeers() Obtain the current peers list (discovered by discoverPeers)
Each time WifiP2pManager performs a P2P operation, different listeners can be used to detect the feedback of these operations. The types of these listeners are as follows:

 

 

Listener Associated Behavior
WifiP2pManager.ActionListener connect(),cancelConnect(),createGroup(),removeGroup()AnddiscoverPeers()
WifiP2pManager.ChannelListener initialize()
WifiP2pManager.ConnectionInfoListener requestConnectInfo()
WifiP2pManager.GroupInfoListener requestGroupInfo()
WifiP2pManager.PeerListListener requestPeers()

 

Next, we will explain how to use WiFi P2P.

 

 

I. Preparations

In the preparation phase, we need to allow our applications to accept P2P signals, which requires an intent broadcast receiver. To create a broadcast receiver that meets our requirements, we need to prepare the following three elements:

(1) An intent broadcast receiver is used to accept intent broadcasts.

(2) Obtain a Channel object through the initialize () initialization operation of WifiP2pManager for future communication with the WiFi P2P framework.

(3) package the BroadcastReceiver class to implement a receiver.

 

The intent filter is created using the following method:

 

// Set intent filter intentFilter = new IntentFilter (); // a global intentFilter object intentFilter. addAction (WifiP2pManager. WIFI_P2P_STATE_CHANGED_ACTION); // whether intentFilter is available for Wi-Fi P2P. addAction (WifiP2pManager. WIFI_P2P_PEERS_CHANGED_ACTION); // intentFilter is changed in the peers list. addAction (WifiP2pManager. WIFI_P2P_CONNECTION_CHANGED_ACTION); // intentFilter varies with the Wi-Fi P2P connection. addAction (WifiP2pManager. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); // the P2P device information of WiFi changes (for example, the device name is changed)

 


Channel acquisition method:

 

Channel = wifiP2pManager. initialize (getApplicationContext (), getMainLooper (), null); // channel is a global Channel object.

 

To create an intent broadcast receiver, you must inherit the BroadcastReceiver class. The following is an example:

 

Class MyBroadcastReceiver extends BroadcastReceiver {// when using WiFi P2P, the self-defined BroadcastReceiver constructor must include the following three elements: private WifiP2pManager wifiP2pManager; private Channel channel Channel; private Activity activity; public MyBroadcastReceiver (WifiP2pManager wifiP2pManager, Channel channel, Activity) {this. wifiP2pManager = wifiP2pManager; this. channel = channel; this. activity = activity;} // onReceiver processes the corresponding intent @ Overridepublic void onReceive (Context context, Intent intent) {String action = intent. getAction (); if (WifiP2pManager. WIFI_P2P_STATE_CHANGED_ACTION.equals (action) {int state = intent. getIntExtra (WifiP2pManager. EXTRA_WIFI_STATE,-1); if (state = WifiP2pManager. WIFI_P2P_STATE_ENABLED) {// WiFi P2P available} else {// WiFi P2P unavailable} else if (WifiP2pManager. WIFI_P2P_PEERS_CHANGED_ACTION.equals (action) {} else if (WifiP2pManager. WIFI_P2P_CONNECTION_CHANGED_ACTION.equals (action) {} else if (WifiP2pManager. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals (action )){}}}

 

 

After definition, You Can instantiate an intent broadcast receiver object as needed:

 

broadcastReceiver = new MyBroadcastReceiver(wifiP2pManager, channel, this);

 

After the three elements are met, register our receiver with the application so that it can start to work:

 

registerReceiver(broadcastReceiver, intentFilter);


 

 

Ii. Start peers discovery

 

Public void discoverPeers (View view) {peerlistener = new WifiP2pManager. peerlistener () {@ Overridepublic void onPeersAvailable (WifiP2pDeviceList peerList) {peers. clear (); // peers is a global ArrayList object used to save the peers information found. addAll (peerList. getDeviceList (); // if you have a control to display the peers information, you can update it here.}; wifiP2pManager. discoverPeers (channel, new WifiP2pManager. actionListener () {@ Overridepublic void onSuccess ( ) {Toast. makeText (getApplicationContext (), "discover peers! ", Toast. LENGTH_SHORT) ;}@ Overridepublic void onFailure (int arg0) {}}); // discoverPeers is executed asynchronously and will be returned immediately after the call, but the discovery process is ongoing, // you will be notified when a device is found}


 

After a device is found, WifiP2pManager. WIFI_P2P_PEERS_CHANGED_ACTION intent broadcast is triggered. You can add the intent to the BroadcastReceiver class you previously wrapped:

 

else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {if (wifiP2pManager != null) {wifiP2pManager.requestPeers(channel, peerListListener);}}

 


 

3. Establish a connection with peers

 

Public void connect () {final WifiP2pDevice device = (WifiP2pDevice) peers. get (0); // obtain the first detected device WifiP2pConfig config = new WifiP2pConfig (); config from the peers list. deviceAddress = device. deviceAddress; config. wps. setup = WpsInfo. PBC; wifiP2pManager. connect (channel, config, new WifiP2pManager. actionListener () {@ Overridepublic void onSuccess () {// connection successful Toast. makeText (getApplicationContext (), "and device" + device. deviceName + "connection successful", Toast. LENGTH_LONG ). show () ;}@ Overridepublic void onFailure (int arg0) {// connection failure Toast. makeText (getApplicationContext (), "and device" + device. deviceName + "connection failed", Toast. LENGTH_LONG ). show ();}});}

 

 

Whenever the P2P connection status changes, WifiP2pManager. WIFI_P2P_CONNECTION_CHANGED_ACTION intent broadcast is triggered. You can add the intent to the BroadcastReceiver class you previously wrapped:

 

Else if (WifiP2pManager. WIFI_P2P_CONNECTION_CHANGED_ACTION.equals (action) {if (wifiP2pManager = null) return; NetworkInfo networkInfo = (NetworkInfo) intent. getParcelableExtra (WifiP2pManager. EXTRA_NETWORK_INFO); if (networkInfo. isConnected () {// We are connected with the other device, request // connection // info to find group owner IPwifiP2pManager. requestConnectionInfo (channel, new WifiP2pManager. ConnectionInfoListener () {@ Overridepublic void onConnectionInfoAvailable (WifiP2pInfo info) {// you can view the network information after the change. // obtain the changed address information through the passed WifiP2pInfo parameter. InetAddress groupOwnerAddress = info. groupOwnerAddress; // determine the group leader if (info. groupFormed & info. isGroupOwner) {// the P2P team lead task is executed here. // Usually create a service thread to listen to client requests} else if (info. groupFormed) {// execute the tasks of common team members here. // a client is usually created to send a request to the server of the group leader }}});}}


 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.