NsdManager  |  API reference  |  Android Developers

The Network Service Discovery Manager class provides the API to discover services on a network. As an example, if device A and device B are connected over a Wi-Fi network, a game registered on device A can be discovered by a game on device B. Another example use case is an application discovering printers on the network.

The API currently supports DNS based service discovery and discovery is currently limited to a local network over Multicast DNS. DNS service discovery is described at http://files.dns-sd.org/draft-cheshire-dnsext-dns-sd.txt

The API is asynchronous, and responses to requests from an application are on listener callbacks on a separate internal thread.

There are three main operations the API supports - registration, discovery and resolution.

Once the peer application discovers the "Example" http service, and either needs to read the attributes of the service or wants to receive data from the "Example" application, it can initiate a resolve with resolveService(NsdServiceInfo, ResolveListener) to resolve the attributes, host, and port details. A successful resolve is notified on ResolveListener.onServiceResolved and a failure is notified on ResolveListener.onResolveFailed. Applications can reserve for a service type at http://www.iana.org/form/ports-service. Existing services can be found at http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml

Nested classes

interface NsdManager.DiscoveryListener

Interface for callback invocation for service discovery 

interface NsdManager.RegistrationListener

Interface for callback invocation for service registration 

interface NsdManager.ResolveListener

Callback for use with NsdManager.resolveService to resolve the service info and use with NsdManager.stopServiceResolution to stop resolution. 

interface NsdManager.ServiceInfoCallback

Callback to listen to service info updates. 

Constants

String ACTION_NSD_STATE_CHANGED

Broadcast intent action to indicate whether network service discovery is enabled or disabled.

String EXTRA_NSD_STATE

The lookup key for an int that indicates whether network service discovery is enabled or disabled.

int FAILURE_ALREADY_ACTIVE

Indicates that the operation failed because it is already active.

int FAILURE_BAD_PARAMETERS

Indicates that the service has failed to resolve because of bad parameters.

int FAILURE_INTERNAL_ERROR

Failures are passed with RegistrationListener.onRegistrationFailed, RegistrationListener.onUnregistrationFailed, DiscoveryListener.onStartDiscoveryFailed, DiscoveryListener.onStopDiscoveryFailed or ResolveListener.onResolveFailed.

int FAILURE_MAX_LIMIT

Indicates that the operation failed because the maximum outstanding requests from the applications have reached.

int FAILURE_OPERATION_NOT_RUNNING

Indicates that the stop operation failed because it is not running.

int FAILURE_PERMISSION_DENIED

Indicates that the operation failed because the caller did not have the required permissions.

int NSD_STATE_DISABLED

Network service discovery is disabled

int NSD_STATE_ENABLED

Network service discovery is enabled

int PROTOCOL_DNS_SD

Dns based service discovery protocol

int SERVICE_PERMISSION_DENIED

Indicates the caller is not allowed to register service info callbacks or resolve a service.

int SERVICE_PERMISSION_GRANTED

Indicates the caller can register service info callbacks or resolve a service.

Public methods

void checkPermissionForService(String serviceName, String serviceType, Executor executor, IntConsumer resultReceiver)

Check whether the caller can register service info callbacks or resolve a service.

void discoverServices(String serviceType, int protocolType, NetworkRequest networkRequest, Executor executor, NsdManager.DiscoveryListener listener)

Initiate service discovery to browse for instances of a service type.

void discoverServices(DiscoveryRequest discoveryRequest, Executor executor, NsdManager.DiscoveryListener listener)

Initiates service discovery to browse for instances of a service type.

void discoverServices(String serviceType, int protocolType, NsdManager.DiscoveryListener listener)

Initiate service discovery to browse for instances of a service type.

void discoverServices(String serviceType, int protocolType, Network network, Executor executor, NsdManager.DiscoveryListener listener)

Initiate service discovery to browse for instances of a service type.

void registerService(NsdServiceInfo serviceInfo, int protocolType, NsdManager.RegistrationListener listener)

Register a service to be discovered by other services.

void registerService(AdvertisingRequest advertisingRequest, Executor executor, NsdManager.RegistrationListener listener)

Register a service to be discovered by other services.

void registerService(NsdServiceInfo serviceInfo, int protocolType, Executor executor, NsdManager.RegistrationListener listener)

Register a service to be discovered by other services.

void registerServiceInfoCallback(NsdServiceInfo serviceInfo, Executor executor, NsdManager.ServiceInfoCallback listener)

Register a callback to listen for updates to a service.

void registerServiceInfoCallback(DiscoveryRequest discoveryRequest, Executor executor, NsdManager.ServiceInfoCallback listener)

Register a callback to discover and track updates of services.

void resolveService(NsdServiceInfo serviceInfo, Executor executor, NsdManager.ResolveListener listener)

This method was deprecated in API level 34. the returned ServiceInfo may get stale at any time after resolution, including immediately after the callback is called, and may not contain some service information that could be delivered later, like additional host addresses. Prefer using registerServiceInfoCallback(DiscoveryRequest, Executor, ServiceInfoCallback), which will keep the application up-to-date with the state of the service.

void resolveService(NsdServiceInfo serviceInfo, NsdManager.ResolveListener listener)

This method was deprecated in API level 34. the returned ServiceInfo may get stale at any time after resolution, including immediately after the callback is called, and may not contain some service information that could be delivered later, like additional host addresses. Prefer using registerServiceInfoCallback(DiscoveryRequest, Executor, ServiceInfoCallback), which will keep the application up-to-date with the state of the service.

void stopServiceDiscovery(NsdManager.DiscoveryListener listener)

Stop service discovery initiated with discoverServices(DiscoveryRequest, Executor, DiscoveryListener).

void stopServiceResolution(NsdManager.ResolveListener listener)

Stop service resolution initiated with resolveService(NsdServiceInfo, ResolveListener).

void unregisterService(NsdManager.RegistrationListener listener)

Unregister a service registered through registerService(AdvertisingRequest, Executor, RegistrationListener).

void unregisterServiceInfoCallback(NsdManager.ServiceInfoCallback listener)

Unregister a callback registered with registerServiceInfoCallback(DiscoveryRequest, Executor, ServiceInfoCallback).

Inherited methods

From class java.lang.Object

Object clone()

Creates and returns a copy of this object.

boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

final Class<?> getClass()

Returns the runtime class of this Object.

int hashCode()

Returns a hash code value for the object.

final void notify()

Wakes up a single thread that is waiting on this object's monitor.

final void notifyAll()

Wakes up all threads that are waiting on this object's monitor.

String toString()

Returns a string representation of the object.

final void wait(long timeoutMillis, int nanos)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait(long timeoutMillis)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait()

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

Constants

ACTION_NSD_STATE_CHANGED

public static final String ACTION_NSD_STATE_CHANGED

Broadcast intent action to indicate whether network service discovery is enabled or disabled. An extra EXTRA_NSD_STATE provides the state information as int.

Constant Value: "android.net.nsd.STATE_CHANGED"

FAILURE_ALREADY_ACTIVE

public static final int FAILURE_ALREADY_ACTIVE

Indicates that the operation failed because it is already active.

Constant Value: 3 (0x00000003)

FAILURE_MAX_LIMIT

public static final int FAILURE_MAX_LIMIT

Indicates that the operation failed because the maximum outstanding requests from the applications have reached.

Constant Value: 4 (0x00000004)

FAILURE_OPERATION_NOT_RUNNING

public static final int FAILURE_OPERATION_NOT_RUNNING

Indicates that the stop operation failed because it is not running. This failure is passed with ResolveListener.onStopResolutionFailed.

Constant Value: 5 (0x00000005)

NSD_STATE_DISABLED

public static final int NSD_STATE_DISABLED

Network service discovery is disabled

Constant Value: 1 (0x00000001)

NSD_STATE_ENABLED

public static final int NSD_STATE_ENABLED

Network service discovery is enabled

Constant Value: 2 (0x00000002)

PROTOCOL_DNS_SD

public static final int PROTOCOL_DNS_SD

Dns based service discovery protocol

Constant Value: 1 (0x00000001)

Public methods

checkPermissionForService

public void checkPermissionForService (String serviceName, 
                String serviceType, 
                Executor executor, 
                IntConsumer resultReceiver)

Check whether the caller can register service info callbacks or resolve a service.

Starting from target SDK Build.VERSION_CODES.CINNAMON_BUN, unless apps have the Manifest.permission.ACCESS_LOCAL_NETWORK permission, they can only register service info callbacks or resolve services that were selected in a UI picker, as per DiscoveryRequest.FLAG_SHOW_PICKER.

The system will remember whether a user has selected a service in the past, but access may be revoked for storage reasons or by the user. This method allows checking whether access to the service was granted in the picker and not revoked.

The resultReceiver will be called using the provided Executor with either SERVICE_PERMISSION_GRANTED or SERVICE_PERMISSION_DENIED.

Parameters
serviceName String: Instance name of the service.
This value cannot be null.
serviceType String: Type of the service, e.g. _ipp._tcp.
This value cannot be null.
executor Executor: The Executor on which to invoke the receiver.
This value cannot be null.
resultReceiver IntConsumer: The IntConsumer to receive the permission check result code; will be either SERVICE_PERMISSION_GRANTED or SERVICE_PERMISSION_DENIED.
This value cannot be null.

discoverServices

public void discoverServices (String serviceType, 
                int protocolType, 
                NetworkRequest networkRequest, 
                Executor executor, 
                NsdManager.DiscoveryListener listener)

Initiate service discovery to browse for instances of a service type. Service discovery consumes network bandwidth and will continue until the application calls stopServiceDiscovery(DiscoveryListener).

The function call immediately returns after sending a request to start service discovery to the framework. The application is notified of a success to initiate discovery through the callback DiscoveryListener.onDiscoveryStarted or a failure through DiscoveryListener.onStartDiscoveryFailed.

Upon successful start, application is notified when a service is found with DiscoveryListener.onServiceFound or when a service is lost with DiscoveryListener.onServiceLost.

Upon failure to start, service discovery is not active and application does not need to invoke stopServiceDiscovery(DiscoveryListener)

The application should call stopServiceDiscovery(DiscoveryListener) when discovery of this service type is no longer required, and/or whenever the application is paused or stopped.

During discovery, new networks may connect or existing networks may disconnect - for example if wifi is reconnected. When a service was found on a network that disconnects, DiscoveryListener.onServiceLost will be called. If a new network connects that matches the NetworkRequest, DiscoveryListener.onServiceFound will be called for services found on that network. Applications that do not want to track networks themselves are encouraged to use this method instead of other overloads of discoverServices, as they will receive proper notifications when a service becomes available or unavailable due to network changes.
Requires Manifest.permission.ACCESS_NETWORK_STATE

Parameters
serviceType String: The service type being discovered. Examples include "_http._tcp" for http services or "_ipp._tcp" for printers.
This value cannot be null.
protocolType int: The service discovery protocol
networkRequest NetworkRequest: Request specifying networks that should be considered when discovering.
This value cannot be null.
executor Executor: Executor to run listener callbacks with.
This value cannot be null.
listener NsdManager.DiscoveryListener: The listener notifies of a successful discovery and is used to stop discovery on this serviceType through a call on stopServiceDiscovery(DiscoveryListener).
This value cannot be null.

discoverServices

public void discoverServices (String serviceType, 
                int protocolType, 
                Network network, 
                Executor executor, 
                NsdManager.DiscoveryListener listener)

Initiate service discovery to browse for instances of a service type. Service discovery consumes network bandwidth and will continue until the application calls stopServiceDiscovery(DiscoveryListener).

The function call immediately returns after sending a request to start service discovery to the framework. The application is notified of a success to initiate discovery through the callback DiscoveryListener.onDiscoveryStarted or a failure through DiscoveryListener.onStartDiscoveryFailed.

Upon successful start, application is notified when a service is found with DiscoveryListener.onServiceFound or when a service is lost with DiscoveryListener.onServiceLost.

Upon failure to start, service discovery is not active and application does not need to invoke stopServiceDiscovery(DiscoveryListener)

The application should call stopServiceDiscovery(DiscoveryListener) when discovery of this service type is no longer required, and/or whenever the application is paused or stopped.

Parameters
serviceType String: The service type being discovered. Examples include "_http._tcp" for http services or "_ipp._tcp" for printers.
This value cannot be null.
protocolType int: The service discovery protocol
network Network: Network to discover services on, or null to discover on all available networks
executor Executor: Executor to run listener callbacks with.
This value cannot be null.
listener NsdManager.DiscoveryListener: The listener notifies of a successful discovery and is used to stop discovery on this serviceType through a call on stopServiceDiscovery(DiscoveryListener).
This value cannot be null.

registerService

public void registerService (NsdServiceInfo serviceInfo, 
                int protocolType, 
                Executor executor, 
                NsdManager.RegistrationListener listener)

Register a service to be discovered by other services.

The function call immediately returns after sending a request to register service to the framework. The application is notified of a successful registration through the callback RegistrationListener.onServiceRegistered or a failure through RegistrationListener.onRegistrationFailed.

The application should call unregisterService(RegistrationListener) when the service registration is no longer required, and/or whenever the application is stopped.

Parameters
serviceInfo NsdServiceInfo: The service being registered.
This value cannot be null.
protocolType int: The service discovery protocol
executor Executor: Executor to run listener callbacks with.
This value cannot be null.
listener NsdManager.RegistrationListener: The listener notifies of a successful registration and is used to unregister this service through a call on unregisterService(RegistrationListener). Cannot be null.

registerServiceInfoCallback

public void registerServiceInfoCallback (NsdServiceInfo serviceInfo, 
                Executor executor, 
                NsdManager.ServiceInfoCallback listener)

Register a callback to listen for updates to a service. An application can listen to a service to continuously monitor availability of given service. The callback methods will be called on the passed executor. And service updates are sent with continuous calls to ServiceInfoCallback.onServiceUpdated. This is different from resolveService(NsdServiceInfo, ResolveListener) which provides one shot service information.

This API listens to updates for one service at a time. Applications need to cancel the registration before registering the same callback instance again. Upon failure to register a callback for example if it's a duplicated registration, the application is notified through ServiceInfoCallback.onServiceInfoCallbackRegistrationFailed with FAILURE_BAD_PARAMETERS.

Parameters
serviceInfo NsdServiceInfo: the service to receive updates for.
This value cannot be null.
executor Executor: Executor to run callbacks with.
This value cannot be null.
listener NsdManager.ServiceInfoCallback: to receive callback upon service update.
This value cannot be null.

registerServiceInfoCallback

public void registerServiceInfoCallback (DiscoveryRequest discoveryRequest, 
                Executor executor, 
                NsdManager.ServiceInfoCallback listener)

Register a callback to discover and track updates of services.

This method combines discoverServices(DiscoveryRequest,Executor,DiscoveryListener) and registerServiceInfoCallback(NsdServiceInfo,Executor,ServiceInfoCallback) by finding services as per the provided DiscoveryRequest, and continuously monitoring availability and properties of the discovered services.

This API may cause more network traffic than using discoverServices(DiscoveryRequest,Executor,DiscoveryListener) and only calling registerServiceInfoCallback(NsdServiceInfo,Executor,ServiceInfoCallback) for select services, because it automatically queries all service information for all discovered services. However most mDNS advertisers reply with their full service information in one discovery reply, in which case there is no additional traffic, and this API saves the cost of registering multiple listeners for discovering and resolving services.

Applications need to cancel the registration before registering the same callback instance again. Upon failure to register a callback, the application is notified through ServiceInfoCallback.onServiceInfoCallbackRegistrationFailed.

Parameters
discoveryRequest DiscoveryRequest: the DiscoveryRequest object which specifies the discovery parameters such as service type, subtype and network.
This value cannot be null.
executor Executor: Executor to run listener callbacks with.
This value cannot be null.
listener NsdManager.ServiceInfoCallback: The listener to be notified of found, updated or lost services.
This value cannot be null.

resolveService

public void resolveService (NsdServiceInfo serviceInfo, 
                Executor executor, 
                NsdManager.ResolveListener listener)

This method was deprecated in API level 34.
the returned ServiceInfo may get stale at any time after resolution, including immediately after the callback is called, and may not contain some service information that could be delivered later, like additional host addresses. Prefer using registerServiceInfoCallback(DiscoveryRequest, Executor, ServiceInfoCallback), which will keep the application up-to-date with the state of the service.

Resolve a discovered service. An application can resolve a service right before establishing a connection to fetch the IP and port details on which to setup the connection.

Parameters
serviceInfo NsdServiceInfo: service to be resolved.
This value cannot be null.
executor Executor: Executor to run listener callbacks with.
This value cannot be null.
listener NsdManager.ResolveListener: to receive callback upon success or failure.
This value cannot be null.

resolveService

public void resolveService (NsdServiceInfo serviceInfo, 
                NsdManager.ResolveListener listener)

This method was deprecated in API level 34.
the returned ServiceInfo may get stale at any time after resolution, including immediately after the callback is called, and may not contain some service information that could be delivered later, like additional host addresses. Prefer using registerServiceInfoCallback(DiscoveryRequest, Executor, ServiceInfoCallback), which will keep the application up-to-date with the state of the service.

Resolve a discovered service. An application can resolve a service right before establishing a connection to fetch the IP and port details on which to setup the connection.

Parameters
serviceInfo NsdServiceInfo: service to be resolved
listener NsdManager.ResolveListener: to receive callback upon success or failure. Cannot be null. Cannot be in use for an active service resolution.

stopServiceDiscovery

public void stopServiceDiscovery (NsdManager.DiscoveryListener listener)

Stop service discovery initiated with discoverServices(DiscoveryRequest, Executor, DiscoveryListener). An active service discovery is notified to the application with DiscoveryListener.onDiscoveryStarted and it stays active until the application invokes a stop service discovery. A successful stop is notified to with a call to DiscoveryListener.onDiscoveryStopped.

Upon failure to stop service discovery, application is notified through DiscoveryListener.onStopDiscoveryFailed.

If the listener is not already registered, for apps running on devices with T SDK extension < 22, this will throw with IllegalArgumentException.

Parameters
listener NsdManager.DiscoveryListener: This should be the listener object that was passed to discoverServices(DiscoveryRequest, Executor, DiscoveryListener). It identifies the discovery that should be stopped and notifies of a successful or unsuccessful stop. In API versions 20 and above, the listener object may be used for another service discovery once the callback has been called. In API versions <= 19, there is no entirely reliable way to know when a listener may be re-used, and a new listener should be created for each service discovery request.