Android Wi-Fi peer-to-peer (Android WiFi peer-to-peer network)

Source: Internet
Author: User

Tagged with: Android Wi-Fi peer network


Wi-Fi peer-to-peer (peer-to-peer network), which allows Android 4.0 with the appropriate hardware (API level 14) or later devices can communicate directly via WiFi without the need for other intermediate transit nodes (Android Wi-Fi peer-to-frame complies with Wi-Fi affiliate Wi-Fi Direct). Using these APIs, you can search for and connect to other devices that also support Wi-Fi peers, and then communicate with each other through a high-speed connection, and the effective distance of this connection is much longer than the effective distance of the Bluetooth connection. This is useful for applications that need to share data between users, such as multi-player games or photo-sharing applications.


The Android Wi-Fi peer API mainly consists of the following sections:

* Use the method defined by the Wifip2pmanager class to search, request, and connect to other peer devices.

* Monitor whether the Wifip2pmanager method call succeeded or failed listener (listener). When calling the Wifip2pmanager method, each method can receive a specified listener as a parameter.

* The intent of the specified event type identified and sent by the Wi-Fi peer framework, such as revoking a connection or discovering a new peer device.


Usually you need to use the API for these three main parts together. For example, you can provide a Wifip2pmanager.actionlistener listener object when calling the Discoverpeers () method, so you can get Actionlistener.onsuccess () and the Actionlistener.onfailure () method notification. If the Discoverpeers () method finds that the peer list is updated, it also sends intent broadcasts of the wifi_p2p_peers_change_action type.


1. API Overview


The Wifip2pmanager class provides methods for interacting with the Wi-Fi hardware on the device, such as searching for and connecting to peer devices. The following are the available actions:


Table one: Wi-Fi peer

Method Describe
Initialize () Register the application on the Wi-Fi framework. This method must be called before the other Wi-Fi peer method is called.
Connect () Starts a peer-to-peer connection with a device using the specified configuration.
Cancelconnect () Cancels the interaction of the peer-to-peer network group in progress.
Requestconnectinfo () Request a device connection information.
CreateGroup () Create a peer network group and use the current device as the owner of the group.
Removegroup () Removes the current peer-to-peer network group.
Requestgroupinof () Ask for peer Network group information.
Discoverpeers () Start searching for peer-to network (devices).
Requestpeers () Requests a peer network (device) that is currently discovered.


The Wifip2pmanager method allows you to pass a listener listener so that the Wi-Fi peer framework notifies you of the state of the method invoked by your activity. The Listener listener interface that can be used and the corresponding Wifip2pmanager method for invoking these listeners are as follows:


Table II: Wi-Fi peer listener

Listener interface Operations that can be used
Wifip2pmanager.actionlistener Connect (), Cancelconnect (), CreateGroup (), Removegroup (), Discoverpeers ()
Wifip2pmanager.channellistener Initialize ()
Wifip2pmanager.connectioninfolistener Requestconnectinfo ()
Wifip2pmanager.groupinfolistener Requestgroupinfo ()
Wifip2pmanager.peerlistlistener Requestpeers ()


The Wi-Fi peer API defines events that are broadcast when certain Wi-Fi peer events occur, such as when a new peer network (device) is discovered or a device's Wi-Fi status changes. Intent You can create and register a broadcast recipient in your application to handle these intent:


Table three: Wi-Fi peer Intents

Intent Describe
Wifi_p2p_connection_changed_action This broadcast is sent when the device's Wi-Fi connection status changes.
Wifi_p2p_peers_changed_action When you call the Discoverpeers () method you will receive this broadcast. If you are dealing with this intent in your application, you also need to call Requestpeers () to get a list of the most recent peer-network (devices).
Wifi_p2p_state_changed_action This broadcast is sent when the device's Wi-Fi peer is enabled or disabled. This broadcast is sent when the device's Wi-Fi peer is enabled or disabled.
Wifi_p2p_this_device_changed_action This broadcast is sent when the details of the device are modified, such as the name of the device.

2. Create a broadcast receiver for Wi-Fi peer Intent


The broadcast receiver (Broadcase receiver) allows you to receive intent that are broadcast by the Android system so that your application can respond to the time you are interested in. The basic steps to create a broadcast receiver to handle Wi-Fi peer intent are as follows:


2.1 Create a class that inherits Broadcasereceiver. In the construction of this class, you'd better pass Wifip2pmanager, Wifip2pmanager.channel, and the activity that registered the broadcast receiver as a parameter. This allows the broadcast receiver to send updates to the activity while also accessing the Wi-Fi hardware and communication channels when needed.

2.2 In the broadcast receiver, examine the intent you are interested in in the OnReceive () method. Perform some necessary operations based on the received intent. For example, if the broadcast sink receives a wifi_p2p_peers_change_action type of intent, you can call the Requestpeers () method to get the currently discovered peer network (device).


The following code shows how to create a typical broadcast sink. This broadcast receiver carries a Wifip2pmanager object and an activity-most parameter, and when the broadcast receiver receives a intent, it uses both objects to do the necessary things properly:

/** * A broadcast receiver that receives Wi-Fi peer Events */public class Wifidirectbroadcastreceiver extends Broadcastreceiver {private Wifip2pman    Ager Mmanager;    Private Channel Mchannel;    Private Mywifiactivity mactivity; Public Wifidirectbroadcastreceiver (Wifip2pmanager Manager, channel Channel, mywifiactivity activity) {s        Uper ();        This.mmanager = Manager;        This.mchannel = Channel;    This.mactivity = activity;        } @Override public void OnReceive (context context, Intent Intent) {String action = intent.getaction (); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals (ACTION)) {//check if Wi-Fi is enabled and notify the appropriate activity} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals (ACTION)) {///call Wifip2pmanager.requestpeers () to get the current List of peer networks (devices)} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals (ACTION)) {//respond to new connection or disconnect Connection} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equaLS (action)) {//respond to changes in WiFi status of this device}}} 


3. Create a Wi-Fi peer app


Creating a Wi-Fi peer application involves creating and registering a broadcast receiver for the application, searching the peer network (device), connecting a peer device, and transmitting data to a peer device. The following sections describe how to accomplish these operations.


3.1 Initial Setup


Before using the Wi-Fi peer-to API, you must verify that your application has access to the corresponding hardware and that the device supports the Wi-Fi peer-to protocol. If you support Wi-Fi peer, you can get a Wifip2pmanager instance, create and register your broadcast receiver, and start using Wi-Fi peer-to API.


3.1.1 Request permission to use the Wi-Fi hardware on your device in your Android manifest file and declare the correct minimum SDK version number for your application:

<USES-SDK android:minsdkversion= "/><uses-permission android:name=" android.permission.ACCESS_WIFI_ State "/><uses-permission android:name=" Android.permission.CHANGE_WIFI_STATE "/><uses-permission Android:name= "Android.permission.CHANGE_NETWORK_STATE"/><uses-permission android:name= " Android.permission.INTERNET "/><uses-permission android:name=" Android.permission.ACCESS_NETWORK_STATE "/ >


3.1.2 Check that Wi-Fi peer is supported and enabled. A good place to do this is in your broadcast receiver, when the broadcast receiver receives the wifi_p2p_state_changed_action . This informs your activity about the status of Wi-Fi peer and responds accordingly.

@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 peer enabled        } else {            //Wi-Fi peer not enabled        }    }    ...}


3.1.3 Gets an instance of Wifip2pmanager in your activity's OnCreate () method and registers your application with the Wi-Fi peer-to frame by calling the Initialize () method. This method returns a Wifip2pmanager.channel object that is used to connect your application to the Wi-Fi peer-to frame. You also need to use this Wifip2pmanager and Wifip2pmanager.channel object, as well as your activity reference to create an instance of your broadcast receiver. This allows your broadcast receivers to notify you of events of interest to your activity and update them. It also allows you to manipulate the Wi-Fi status of your device when you need it.

Wifip2pmanager Mmanager; Channel Mchannel; Broadcastreceiver mreceiver, ... @Overrideprotected void onCreate (Bundle savedinstancestate) {    ...    Mmanager = (Wifip2pmanager) getsystemservice (context.wifi_p2p_service);    Mchannel = Mmanager.initialize (this, getmainlooper (), null);    Mreceiver = new Wifidirectbroadcastreceiver (Mmanager, Mchannel, this);    ...}


3.1.4 Create a intent filter and add the same intent to your broadcast receiver to check:

Intentfilter mintentfilter, ... @Overrideprotected void onCreate (Bundle savedinstancestate) {    ...    Mintentfilter = new Intentfilter ();    Mintentfilter.addaction (wifip2pmanager.wifi_p2p_state_changed_action);    Mintentfilter.addaction (wifip2pmanager.wifi_p2p_peers_changed_action);    Mintentfilter.addaction (wifip2pmanager.wifi_p2p_connection_changed_action);    Mintentfilter.addaction (wifip2pmanager.wifi_p2p_this_device_changed_action);    ...}


3.1.5 Registers your broadcast receiver in the activity's Onresume () method and unregisters it in the OnPause () method:

/* Register the broadcast receiver with the intent value that needs to be matched */@Overrideprotected void Onresume () {    super.onresume ();    Registerreceiver (Mreceiver, mintentfilter);} /* Unregister the Broadcast receiver */@Overrideprotected void OnPause () {    super.onpause ();    Unregisterreceiver (mreceiver);}


When you have acquired the Wifip2pmanager.channel object and set up the broadcast receiver, your application can call the Wi-Fi peer-to-air method and receive Wi-Fi peer intent.

You can now implement your application and use the Wi-Fi peer-to feature by calling methods in Wifip2pmanager. The following sections describe how to perform common operations, such as searching and connecting peer devices.


3.2 Search peer network (device)


The search allows the peer to be connected, and can call the Discoverpeers () method to detect a peer network (device) that is allowed to be discovered in a nearby range. The execution of this method is asynchronous, and if you have created and passed an Wifip2pmanager.actionlistener object as a parameter, you can receive the result of the operation execution in the onsuccess () and OnFailure () methods in this object. where the Onsuccess () method only notifies you that the search program has been executed successfully, but does not provide any actual search to the peer device information;

Mmanager.discoverpeers (channel, New Wifip2pmanager.actionlistener () {    @Override public    void onsuccess () {        ...    }    @Override public    void onfailure (int reasoncode) {        ...    }});


If the search program executes successfully and detects a peer network and device, the system will send a wifi_p2p_peers_changed_action type of intent broadcast, which you can listen to in the broadcast receiver to get a list of peer-network devices. When your application receives a wifi_p2p_peers_changed_action type of intent, you can use the Requestpeers () method to request a list of peer network devices that have been discovered. The following code shows how to set up these steps:

Peerlistlistener Mypeerlistlistener;...if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals (ACTION)) {    // Request a peer device that can be used from WiFi peer manager. This is a method of calling asynchronously, and/    /The activity of the call will get the list result in the callback method of Peerlistlistener.onpeersavailable ().    if (Mmanager! = null) {        mmanager.requestpeers (Mchannel, Mypeerlistlistener);}    }


This requestpeers () method is also a method of asynchronous execution, when the peer list is available, it is defined in the Wifip2pmanager.peerlistlistener interface onpeersavailable () method to return the results to your activity. The Onpeersavailable () method provides a Wifip2pdevicelist object that you can use to find the peer device you want to connect to.


3.3 Connecting the peer device


After you find the peer device you want to connect from the list of available connected peers, you can call the Connect () method to link the device. The invocation of this method requires an Wifip2pconfig object that contains the device information that you want to connect. You can get the result of the connection success or failure through Wifip2pmanager.actionlistener. The following code shows how to connect a target device:

Get a peer device from wifip2pdevicelist wifip2pdevice devices; Wifip2pconfig config = new Wifip2pconfig (); config.deviceaddress = Device.deviceaddress;mmanager.connect (MChannel, Config, new ActionListener () {    @Override public    void onsuccess () {        //connection successful logical processing Operation    }    @Override Public    void OnFailure (int reason) {        //Connection failed logical processing Operation    }});

3.4 Transferring data


Once the connection is successful, you can transfer data between the devices via the socket. The basic steps for incoming data are as follows:


3.4.1 Create a seversocket. This socket waits for a client connection on a port and blocks until the connection request appears, so this method needs to be executed in the background thread.

3.4.2 Create a socket for the client. This client uses the IP address and port of the server ServerSocket to connect to the service-side device.

3.4.3 sends data from the client to the server. When the client socket is successfully connected to the socket on the server, you can send the data from the client to the server via byte stream.

The ServerSocket on the 3.4.4 server waits for the client to connect (via the Accept () method). This method will block until the client connects, so call this method in other threads. When connected, the service-side device is able to receive data sent by the client. Complete some operations on this data, such as saving as a file or showing it to the user.


The following example modifies the Wi-Fi peer Demo (which can be found in the Android SDK), which shows how to create a socket communication between the client and the server and send a JPEG image from the client to the server through a service. Complete code to view Wi-Fi peer Demo directly.

public static class Fileserverasynctask extends Asynctask {private context context;    Private TextView statustext;        Public Fileserverasynctask (context context, View statustext) {this.context = context;    This.statustext = (TextView) statustext; } @Override protected String doinbackground (Void ... params) {try {/** * * Creates a Serverso            Cket and waits for the client to connect. This method will block until a client connection is accepted */serversocket ServerSocket = new ServerSocket (8888);            Socket client = Serversocket.accept (); /** * If the code can be executed here, the previous client is connected and the data is transferred * Save the data stream from the client as a JPEG file */FINAL Fil E F = new File (environment.getexternalstoragedirectory () + "/" + context.getpackagename () + "/wifip2psh            ared-"+ system.currenttimemillis () +". jpg ");            File dirs = new file (F.getparent ());            if (!dirs.exists ()) dirs.mkdirs (); F.creAtenewfile ();            InputStream InputStream = Client.getinputstream ();            CopyFile (InputStream, New FileOutputStream (f));            Serversocket.close ();        return F.getabsolutepath ();            } catch (IOException e) {log.e (Wifidirectactivity.tag, E.getmessage ());        return null; }}/** * Initiates activity that handles JPEG pictures */@Override protected void OnPostExecute (String result) {if (            Result! = null) {Statustext.settext ("File copied-" + result);            Intent Intent = new Intent ();            Intent.setaction (Android.content.Intent.ACTION_VIEW);            Intent.setdataandtype (Uri.parse ("file://" + result), "image/*");        Context.startactivity (Intent); }    }}


On the client, connect the socket on the service side via a client socket and transfer the data. This example transmits a JPEG file on the file system of a client device.

Context context = This.getapplicationcontext (); String Host;int Port;int Len;    Socket socket = new socket (); byte buf[] = new Byte[1024];...try {/** * Create a client socket with server IP and port and connection timeout */    Socket.bind (NULL);    Socket.connect (New Inetsocketaddress (host, Port), 500); /** * Creates a byte stream from a JPEG file and transmits it to the output stream of the socket.     This data will be received on the service-side device.    */OutputStream OutputStream = Socket.getoutputstream ();    Contentresolver CR = Context.getcontentresolver ();    InputStream inputstream = null;    InputStream = Cr.openinputstream (Uri.parse ("path/to/picture.jpg"));    while (len = Inputstream.read (BUF))! =-1) {outputstream.write (buf, 0, Len);    } outputstream.close (); Inputstream.close ();} catch (FileNotFoundException e) {//catch logic} catch (IOException e) {//catch logic}/** * Close open so when data transfer is complete or an exception occurs Cket.            */finally {if (socket! = NULL) {if (socket.isconnected ()) {try {socket.close ()};     } catch (IOException e) {           Catch Logic}}} 


Original address: http://developer.android.com/guide/topics/connectivity/wifip2p.html



Android Wi-Fi peer-to-peer (Android WiFi peer-to-peer network)

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.