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

Source: Internet
Author: User


Wi-Fi peer-to-peer (peer-to peers), which agrees with the corresponding hardware of the Android 4.0 (API level 14) or a higher version of the device can directly communicate via WiFi without the need for other intermediate transit nodes (Android Wi-Fi peer framework complies with the Wi-Fi affiliate Wi-Fi direct authentication logo). Use these APIs. You can search for and connect to other Wi-Fi-enabled devices, and then communicate with each other through a quick 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 includes 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 is able to 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 of these three main parts together.

Like what. You can provide the Wifip2pmanager.actionlistener listener object when calling the Discoverpeers () method. This way you will be notified of the actionlistener.onsuccess () and Actionlistener.onfailure () methods. Suppose the Discoverpeers () method finds that the peer list is updated, and the same wifi_p2p_peers_change_action type of intent broadcast is sent.


1. API Overview


The Wifip2pmanager class provides a way to interact with the Wi-Fi hardware on the device. such as searching and connecting peer devices. The following are the available actions:


Table one: Wi-Fi peer

Method Descriptive narrative
Initialize () Register your app on the Wi-Fi framework. This method must be called before other Wi-Fi peer methods are called.
Connect () Use the specified configuration to start a peer-to-peer connection with a single device.

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 the search 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 can inform the State of the method that your activity invokes. The Listener listener interface that you can use and the Wifip2pmanager method that corresponds to calling 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 the intent to broadcast when certain Wi-Fi peer events occur. For example, a new peer network (device) or an event that changes the Wi-Fi status of a device is found. You can create and register a broadcast recipient in your application to handle these intent:


Table three: Wi-Fi peer Intents

Intent Descriptive narrative
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. Assuming that you are working with this intent in your application, you will 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 changed, such as the name of the device.


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


The broadcast receiver (Broadcase receiver) agrees that you receive the intent that the Android system broadcasts, so your application can respond to the time you are interested in. The basic process of creating a broadcast receiver to handle Wi-Fi peer intent such as the following:


2.1 Create a class that inherits Broadcasereceiver.

In the constructor method of this class. You'd better be Wifip2pmanager, Wifip2pmanager.channel. There is also a note that the activity of this broadcast receiver is passed in as a number of references. This enables the broadcast receiver to send updates to the activity at the same time, and to access the Wi-Fi hardware and communication channels when needed.

2.2 In the broadcast receiver. Check the intent you are interested in in the OnReceive () method. Some necessary operations are completed based on the received intent. For example, assuming that the broadcast receiver receives a wifi_p2p_peers_change_action type of intent, you can call the Requestpeers () method to obtain the currently discovered peer-to network (device).


The following code shows how to create a typical broadcast receiver.

This broadcast receiver carries a Wifip2pmanager object and an activity that is the most important, and when the broadcast receiver receives a intent. Use these two objects to properly complete the required actions:

/** * 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 whether Wi-Fi is enabled. and notify the appropriate activity} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals (ACTION)) {//Call Wifip2pman            Ager.requestpeers () to get the current peer network (device) list} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals (ACTION)) { Respond to a new connection or disconnect} 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 casting a broadcast receiver for the application. Search the peer network (device), connect a peer device, and transfer data to a peer device.

The following chapters describe how these operations are completed.


3.1 Initial Setup


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


3.1.1 Requests permission to use the Wi-Fi hardware on the device in the Android manifest file. and declare the correct minimum SDK version 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 can be 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 state of the 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 is enabled        } else {            //Wi-Fi peer is not enabled        }    }< c10/> ...}


3.1.3 Gets an instance of Wifip2pmanager in your activity's OnCreate () method and uses the call Initialize () method to register your application with the Wi-Fi peer-to frame. This method returns a Wifip2pmanager.channel object that is used to connect your application to the Wi-Fi peer-to frame. You 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 receiver to notify you of events that are of interest to your activity and update them.

The same 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 for inspection:

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 Register your broadcast receiver in the activity's Onresume () method and log off in the OnPause () method:

/* Use the intent value required to match the broadcast receiver */@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 will be able to call the Wi-Fi peer method and receive Wi-Fi peer intent.

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


3.2 Search peer network (device)


The search agrees to be connected to the peer device and is able to call the Discoverpeers () method to detect a peer network (device) that agrees to be discovered in a nearby range.

The process of running this method is asynchronous, assuming that you have created and passed a Wifip2pmanager.actionlistener object as a parameter. You can receive the result of the operation running in the onsuccess () and OnFailure () methods in this object. The Onsuccess () method only notifies you that the search program has run successfully. But will 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) {        ...    }});


Assuming the search program runs successfully and detects a peer-to network and device, the system will send a wifi_p2p_peers_changed_action -type Intent broadcast that you can listen to in a broadcast receiver to get a list of peer-to network devices. When your application receives the 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 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.    //The activity of the call will be given a list result in the callback method of Peerlistlistener.onpeersavailable ().

if (Mmanager! = null) { mmanager.requestpeers (Mchannel, Mypeerlistlistener);} }


This requestpeers () method is the same method that runs asynchronously. When the list of peer devices is available, it returns the results to your activity in the onpeersavailable () method defined by the Wifip2pmanager.peerlistlistener interface. 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 have found the peer device that you want to connect from the list of connected peers that you acquired. You will be able to call the Connect () method to link the device.

The invocation of this method requires a Wifip2pconfig object that includes the device information that you want to connect.

You can get the results of successful or unsuccessful connections through Wifip2pmanager.actionlistener. The following code shows how to connect the 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 Data transfer


Once the connection is established, you will be able to transfer data between devices via the socket.

The basic process for passing data is as follows:


3.4.1 Create a seversocket. The socket will wait for the client connection on a port and will block until the connection request appears. So this method needs to run in a background thread.

3.4.2 Create a client socket.

This client uses the IP address of the server ServerSocket and port 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 is blocked until the client is connected, so this method is called in other threads. After the connection. The service-side device will receive the data sent by the client. Complete some operations on these data, such as saving as a file or displaying it to the user.


The following example changes to the Wi-Fi peer-to Demo (found in the Android SDK), which shows how to create a socket communication between the client and the server. A JPEG image is sent 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 wait for the client to connect. This method is blocked until a client connection is accepted */serversocket ServerSocket = new ServerSocket (8888);            Socket client = Serversocket.accept (); /** * Assume that the code can be run here, stating that the previous client has been connected and data transfer * Save the stream from the client as a JPEG file */fin Al file F = new file (environment.getexternalstoragedirectory () + "/" + context.getpackagename () + "/wif            ip2pshared-"+ 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 can handle 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 server and transfer data via a client socket.

This sample 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 Clientsocket using server-side IP and port and connection time-outs */    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 is transferred 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)

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.