Using Wi-Fi Direct for Service Discovery Direct use of Wi-Fi Service Discovery

Source: Internet
Author: User

Using Network Service Discovery, showed you how to discover services that are connected to a local network. however, using Wi-Fi Direct & trad; Service Discovery allows you to discover the services of nearby devices directly, without being connected to a network. you can also advertise the services running on your device. these capabilities help you communicate between apps, even when no local network or hotspot is available.

While this set of APIs is similar in purpose to the Network Service Discovery APIs outlined in a previous lesson, implementing them in code is very different. this lesson shows you how to discover services available from other devices, using Wi-Fi Direct™. The lesson assumes that you're already familiar with the Wi-Fi Direct API.

Set Up the Manifest
In order to use Wi-Fi Direct, add the CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, and INTERNET permissions to your manifest. even though Wi-Fi Direct doesn't require an Internet connection, it uses standard Java sockets, and using these in Android requires the requested permissions.

<Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "com. example. android. nsdchat"
...

<Uses-permission
Android: required = "true"
Android: name = "android. permission. ACCESS_WIFI_STATE"/>
<Uses-permission
Android: required = "true"
Android: name = "android. permission. CHANGE_WIFI_STATE"/>
<Uses-permission
Android: required = "true"
Android: name = "android. permission. INTERNET"/>
...
Add a Local Service
If you're providing a local service, you need to register it for service discovery. Once your local service is registered, the framework automatically responds to service discovery requests from peers.

To create a local service:

Create a WifiP2pServiceInfo object.
Populate it with information about your service.
Call addLocalService () to register the local service for service discovery.
Private void startRegistration (){
// Create a string map containing information about your service.
Map

Record = new HashMap

();
Record. put ("listenport", String. valueOf (SERVER_PORT ));
Record. put ("buddyname", "John Doe" + (int) (Math. random () * 1000 ));
Record. put ("available", "visible ");

// Service information. Pass it an instance name, service type
// _ Protocol. _ transportlayer, and the map containing
// Information other devices will want once they connect to this one.
WifiP2pDnsSdServiceInfo serviceInfo =
WifiP2pDnsSdServiceInfo. newInstance ("_ test", "_ presence. _ tcp", record );

// Add the local service, sending the service info, network channel,
// And listener that will be used to indicate success or failure
// The request.
MManager. addLocalService (channel, serviceInfo, new ActionListener (){
@ Override
Public void onSuccess (){
// Command successful! Code isn't necessarily needed here,
// Unless you want to update the UI or add logging statements.
}

@ Override
Public void onFailure (int arg0 ){
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
}
});
}


Discover Nearby Services
Android uses callback methods to your y your application of available services, so the first thing to do is set those up. create aWifiP2pManager. dnsSdTxtRecordListener to listen for incoming records. this record can optionally be broadcast by other devices. when one comes in, copy the device address and any other relevant information you want into a data structure external to the current method, so you can access it later. the following example assumes that the record contains a "buddyname" field, populated with the user's identity.

Final HashMap <String, String> buddies = new HashMap <String, String> ();
...
Private void discoverService (){
DnsSdTxtRecordListener txtListener = new DnsSdTxtRecordListener (){
@ Override
/* Callback uplodes:
* FullDomain: full domain name: e. g "printer. _ ipp. _ tcp. local ."
* Record: TXT record dta as a map of key/value pairs.
* Device: The device running the advertised service.
*/

Public void onDnsSdTxtRecordAvailable (
String fullDomain, Map

Record, WifiP2pDevice device ){
Log. d (TAG, "DnsSdTxtRecord available-" + record. toString ());
Buddies. put (device. deviceAddress, record. get ("buddyname "));
}
};
...
}

To get the service information, create a WifiP2pManager. dnsSdServiceResponseListener. this parameter es the actual description and connection information. the previous code snippet implemented aMap object to pair a device address with the buddy name. the service response listener uses this to link the DNS record with the corresponding service information. once both listeners are implemented, add them to theWifiP2pManager using the setDnsSdResponseListeners () method.

Private void discoverService (){
...

DnsSdServiceResponseListener servListener = new DnsSdServiceResponseListener (){
@ Override
Public void onDnsSdServiceAvailable (String instanceName, String registrationType,
WifiP2pDevice resourceType ){

// Update the device name with the human-friendly version from
// The DnsTxtRecord, assuming one arrived.
ResourceType. deviceName = buddies
. ContainsKey (resourceType. deviceAddress )? Buddies
. Get (resourceType. deviceAddress): resourceType. deviceName;

// Add to the custom adapter defined specifically for showing
// Wifi devices.
WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager ()
. FindFragmentById (R. id. frag_peerlist );
WiFiDevicesAdapter adapter = (WiFiDevicesAdapter) fragment
. GetListAdapter ());

Adapter. add (resourceType );
Adapter. notifyDataSetChanged ();
Log. d (TAG, "onBonjourServiceAvailable" + instanceName );
}
};

MManager. setDnsSdResponseListeners (channel, servListener, txtListener );
...
}
Now create a service request and call addServiceRequest (). This method also takes a listener to report success or failure.

ServiceRequest = WifiP2pDnsSdServiceRequest. newInstance ();
MManager. addServiceRequest (channel,
ServiceRequest,
New ActionListener (){
@ Override
Public void onSuccess (){
// Success!
}

@ Override
Public void onFailure (int code ){
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
}
});
Finally, make the call to discoverServices ().

MManager. discoverServices (channel, new ActionListener (){

@ Override
Public void onSuccess (){
// Success!
}

@ Override
Public void onFailure (int code ){
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
If (code = WifiP2pManager. P2P_UNSUPPORTED ){
Log. d (TAG, "P2P isn' t supported on this device .");
Else if (...)
...
}
});
If all goes well, hooray, you're done! If you encounter problems, remember that the asynchronous callyou 've made take anWifiP2pManager. actionListener as an argument, and this provides you with callbacks indicating success or failure. to diagnose problems, put debugging code inonFailure (). the error code provided by the method hints at the problem. here are the possible error values and what they mean

P2P_UNSUPPORTED
Wi-Fi Direct isn' t supported on the device running the app.
BUSY
The system is to busy to process the request.
ERROR
The operation failed due to an internal error.

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.