Using Wi-Fi P2P for Service Discovery

This lesson teaches you to

The first lesson in this class, Using Network Service
Discovery, showed you
how to discover services that are connected to a local network. However, using
Wi-Fi Peer-to-Peer (P2P) 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 P2P. The lesson assumes that you're already familiar with the
Wi-Fi P2P API.

Set Up the Manifest

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

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.

Discover Nearby Services

Android uses callback methods to notify your application of available services, so
the first thing to do is set those up. Create a WifiP2pManager.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.

To get the service information, create a WifiP2pManager.DnsSdServiceResponseListener. This
receives the actual description and connection information. The previous code
snippet implemented a Map 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 the WifiP2pManager using the setDnsSdResponseListeners() method.

If all goes well, hooray, you're done! If you encounter problems, remember
that the asynchronous calls you've made take an
WifiP2pManager.ActionListener as an argument, and
this provides you with callbacks indicating success or failure. To diagnose
problems, put debugging code in onFailure(). The error code
provided by the method hints at the problem. Here are the possible error values
and what they mean