Using Wi-Fi Direct technology allows hardware-enabled devices to be connected directly without an intermediate access point. The API support for Wi-Fi Direct is available for Android 4.0 (API version 14) and later systems. Through the use of these APIs, developers can implement Wi-Fi direct-enabled devices to detect and connect to each other, so as to obtain a longer distance than Bluetooth data communication effect. This technology is undoubtedly valuable for applications such as multiplayer games, picture sharing, etc. that need to transfer data between users.
There are several important points to note about the use of the Wi-Fi Direct API function:
• Methods for probing (discover) peer devices (peers), initiating requests (request) to peer devices, and establishing a connection (connect) are defined in class Wifip2pmanager.
• By setting the Listener (Listener), you can learn the success of a method call in Wifip2pmanager. The listener is passed as a parameter to the called method.
• When a new peer device or link is found to be missing, the Wi-Fi Direct system (framework) is notified in an intentional (Intent) manner based on the different events detected.
In development, the use of the above three points is quite common. As a simple example, define a listener wifip2pmanager.actionlistener and call the function discoverpeers (), when the corresponding event occurs, it will be in actionlistener.onsuccess () and Actionlistener.onfailure () two methods are notified. When the Discoverpeers () method detects a change in the peer device list, it is possible to receive a wifi_p2p_peers_changed_action intent from the system broadcast (broadcast).
The basic steps for
To create a broadcast sink to handle Wi-Fi direct intent are as follows:
1, create a new class that inherits the Broadcastreceiver class. The parameters of the constructor are passed Wifip2pmanager,wifip2pmanager.channel, respectively, and activities that need to be registered in the broadcast receiver. This is one of the most common parameter-setting patterns that allow a broadcast receiver to cause an activity to be updated while using Wi-Fi hardware and communication channels when necessary.
2, in the OnReceive () function of the broadcast receiver, the corresponding action (actions) can be performed for a particular intention of interest. For example, when the broadcast receiver receives the intent wifi_p2p_peers_changed_action, it can call the Requestpeers () method to enumerate the currently detected peer devices.
To create a Wi-Fi direct app:
A full Wi-Fi direct application includes the ability to create and register a broadcast receiver, detect peer devices, connect peer devices, and transfer data between peer devices. Here is a detailed description of how to implement it.
Preparation: Before using the Wi-Fi Direct API, first make sure that the application has access to the hardware and that the device supports the Wi-Fi direct protocol. If these conditions are met, you can get a Wifip2pmanager instance, create and register a broadcast receiver, and finally use the Wi-Fi Direct API.
Add the following to the Android manifest file to allow the use of the hardware on the Wi-Fi device and declare that the application correctly supports the Minimum SDK version required to invoke the API.
<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"/>
Check Wi-Fi direct support and turned on. It is recommended to detect when the broadcast receiver receives the wifi_p2p_state_changed_action intention. The test results need to be notified and processed accordingly:
@Override
public 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 Direct is enabled
} else {
Wi-Fi Direct is not enabled
}
}
......
}
The
Obtains an instance of the Wifip2pmanager object in the active OnCreate () method, registering the current application with the Wi-Fi direct system through the object's Initialize () method. Once the registration is successful, it returns a Wifip2pmanager.channel that allows the application to interact with the Wi-Fi direct system. The Wifip2pmanager and Wifip2pmanager.channel objects and a reference to an activity are finally passed as parameters to the custom broadcast sink. In this way, the activity is able to respond to the notification of the broadcast receiver and make the appropriate updates. Of course, this also gives the program the ability to manipulate the Wi-Fi state of the device:
Wifip2pmanager mmanager;
Channel mchannel;
Broadcastreceiver mreceiver;
...
@Override
protected void OnCreate (Bundle savedinstancestate) {
...
Mmanager = (Wifip2pmanager) getsystemservice (context.wifi_p2p_service);
Mchannel = Mmanager.initialize (this, getmainlooper (), null);
mreceiver = new Wifidirectbroadcastreceiver (Mmanager, Mchannel, this);
...
}
The
Creates an intent filter (intent filter) that adds the kind of intent and consistency in the broadcast sink:
Intentfilter mintentfilter;
......
@Override
protected 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);
...
}
The
Registers the broadcast sink in the active Onresume () method and unregisters it in the active OnPause () method:
/Register the broadcast receiver with the intent values to be MATC Hed */
@Override
protected void Onresume () {
Super.onresume ();
registerreceiver (Mreceiver, mintentfilter);
}
/* Unregister the broadcast receiver */
@Override
protected void OnPause () {
super.onpause ();
Unregisterreceiver (mreceiver);
}
Once Wifip2pmanager.channel is successfully acquired and a broadcast receiver is created, the application has the ability to use Wi-Fi direct correlation functions and to receive Wi-Fi direct intent. Let the program also have the special power of Wi-Fi direct, even if you let go of the Wifip2pmanager method.
The
Probe peer device (discovering peers)
calls the Discoverpeers () function to detect peer devices within a valid distance. It is an asynchronous function, and the success of the call gives the notification in the onsuccess () and OnFailure () of the Wifip2pmanager.actionlistener listener created by the program. It is worth noting that the onsuccess () method only notifies the event that a peer device is successfully detected, and does not provide any specific information about the discovered peer device:
Manager.discoverpeers (channel, new Wifip2pmanager.actionlistener () {
@Override
public void onsuccess () {
...
}
@Override
public void OnFailure ( int reasoncode) {
...
}
});
When a peer device is successfully detected, the system broadcasts wifi_p2p_peers_changed_action intent. Once the program receives the intent, it can obtain a list of peer devices that have been detected by invoking the Requestpeers () method. The following code shows how to implement this process:
Peerlistlistener mypeerlistlistener;
...
if ( WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals (ACTION) {
/* Request Available peers from the WiFi peer manager. This was an asynchronous call and the calling activity are notified with a callback on peerlistlistener.onpeersavailable () &N Bsp */
if (manager! = null) {
Manager.requestpeers (channel, Mypeerlistlistener);
}
} the
Requestpeers () method is also an asynchronous function, when it prepares a list of peer devices, The Onpeersavailable () method that is defined in the listener Wifip2pmanager.peerlistlistener is notified. The list of peer devices that can be obtained in the Onpeersavailable () method is stored in wifip2pdevicelist form, and the device that you want to connect is selected by traversing this list.
The
Connect peer device (connecting to peers)
determines which device to connect, and also calls the Connect () method to establish a connection. One of the parameters of the method is the Wifip2pconfig object, which provides information about the device to which it is connected. The success of the connection needs to be notified through the listener Wifip2pmanager.actionlistener. The following code demonstrates how to establish a device connection:
//obtain a peer from the wifip2pdevicelist
Wifip2pdevice device;
Wifip2pconfig config = new Wifip2pconfig ();
Config.deviceaddress = device.deviceaddress;
Manager.connect (channel, config, new ActionListener () {
@Override
public void onsuccess () {
// Success logic
}
@Override
public void onfailure (int reason) {
// Failure logic
}
});
Transfer data (transferring)
Once the connection is successful, the data transfer is the logical thing. Here are the basic steps to send data through the socket:
1, create ServerSocket. It will be used to listen for a specific port, waiting for a client-initiated connection request. This operation needs to be implemented in a background thread.
2. Create a client socket. The client connects to the service device by serversocket the corresponding IP and port.
3. The client has data to the server. After the client socket is successfully connected to the service socket, data can be taken to the server in the form of a byte stream.
4, the server socket through the Accept () method waits for the arrival of the client data connection. This method is blocked until the client data is received. Therefore, it needs to be called in a separate thread. Once a data connection is established, the service device can receive data from the client. All you have to do is apply the appropriate action, such as saving the data to a file, or displaying it directly to the user interface, and so on.
The following code modifies the sample Wi-Fi Direct Demo that comes with the SDK. It demonstrates how to establish a pair of client-server connections and send JPEG pictures to the server by the client. For a complete demonstration project, simply compile and run the SDK sample Wi-Fi Direct demo.
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 {
/* Create a server socket and wait for client connections. This call blocks until a connection are accepted from a client */
ServerSocket serversocket = new ServerSocket (8888);
Socket client = Serversocket.accept ();
/*if This code is reached, a client have connected and transferred data Save the input stream from the client as a JPEG fil E * *
Final file F = new file (environment.getexternalstoragedirectory () + "/"
+ context.getpackagename () + "/wifip2pshared-"
+ 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;
}
}
Start activity that can handle the JPEG image
@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 to the server sockets with a client socket and transfer data. This example transfers a JPEG file on the client device ' s file system:
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 the host, port, and timeout information.*/
Socket.bind (NULL);
Socket.connect (New Inetsocketaddress (host, Port), 500);
/* Create A byte stream from a JPEG file and pipe it to the output stream of the socket. This data is being retrieved by the server 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
}
/* Clean up any open sockets when do transferring or if an exception occurred. */
finally {
if (socket! = NULL) {
if (socket.isconnected ()) {
try {
Socket.close ();
} catch (IOException e) {
Catch logic
}
}
}
}
Official Reference Link: http://developer.android.com/reference/android/net/wifi/p2p/WifiP2pManager.html
Reference Link: http://blog.csdn.net/yichigo/article/details/8472570
Code DOWNLOAD Link: http://download.csdn.net/detail/klcf0220/5894381
Http://www.apkbus.com/android-137269-1-1.html
Reprint: http://klcf0220.cnblogs.com/
WiFi Direct for Android network communication