What is Android?
Android, the widely popular operating system, is the beating heart behind millions of smartphones and tablets globally. Developed by Google, Android is an open-source platform that powers a diverse range of devices, offering users an intuitive and customizable experience. With its user-friendly interface, Android provides easy access to a plethora of applications through the Google Play Store, catering to every need imaginable. From social media and gaming to productivity and entertainment, Android seamlessly integrates into our daily lives, ensuring that the world is at our fingertips. Whether you're a tech enthusiast or a casual user, Android's versatility and accessibility make it a cornerstone of modern mobile technology.
Android NSDManager Example: Service Discovery and Advertisement
In this example, we'll go through how to use NSDManager (Network Service Discovery) in Android to discover and advertise services over a local network. This can be useful for apps that need to find devices offering services like file sharing, multiplayer games, or connecting to IoT devices.
Setting Up the Environment
To use NSDManager in your Android app, first ensure that your app has the necessary permissions in the AndroidManifest.xml file. The permissions required for Network Service Discovery are as follows:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
These permissions will allow your app to access Wi-Fi and network state to perform network service discovery.
1. Service Discovery Example
In this example, we'll create a DiscoveryListener that listens for services being advertised on the network.
Step 1: Initialize NSDManager
The first thing you need to do is initialize the NSDManager. This is the object that handles network service discovery.
NsdManager nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
Step 2: Set Up the DiscoveryListener
Next, create a DiscoveryListener to handle events when services are found or when discovery starts and stops.
NsdManager.DiscoveryListener discoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onServiceFound(NsdServiceInfo service) {
// Called when a service is found on the local network
Log.d("NSD", "Service found: " + service.getServiceName() + " (" + service.getServiceType() + ")");
// You can resolve the service if you need to connect to it (e.g., get port and host)
resolveService(service);
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e("NSD", "Discovery failed to start: Error Code " + errorCode);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e("NSD", "Stop discovery failed: Error Code " + errorCode);
}
@Override
public void onDiscoveryStarted(String serviceType) {
Log.d("NSD", "Discovery started for service type: " + serviceType);
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.d("NSD", "Discovery stopped for service type: " + serviceType);
}
};
Step 3: Start Service Discovery
To begin the discovery process, call discoverServices() with the service type and protocol. For example, let's discover HTTP services on the local network:
String serviceType = "_http._tcp."; // The service type you want to discover
int protocol = NsdManager.PROTOCOL_DNS_SD; // The DNS-SD protocol to use
// Start discovering services of type "_http._tcp."
nsdManager.discoverServices(serviceType, protocol, discoveryListener);
2. Service Advertisement Example
In this example, we'll advertise a service that other devices can discover. For instance, if you're running a simple HTTP server on your device, you might want to advertise this service to other devices.
Step 1: Create the Service Information
The NsdServiceInfo class is used to define the service you want to advertise. You need to set a service name, service type, and port.
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName("MyService");
serviceInfo.setServiceType("_http._tcp.");
serviceInfo.setPort(12345); // This is the port your service will be running on
Step 2: Set Up the RegistrationListener
The RegistrationListener is used to handle the outcome of the service registration process.
NsdManager.RegistrationListener registrationListener = new NsdManager.RegistrationListener() {
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
Log.d("NSD", "Service registered: " + serviceInfo.getServiceName());
}
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e("NSD", "Service registration failed: Error Code " + errorCode);
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
Log.d("NSD", "Service unregistered: " + serviceInfo.getServiceName());
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e("NSD", "Service unregistration failed: Error Code " + errorCode);
}
};
Step 3: Register the Service
Now, you can register the service on the local network.
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener);
This will make your service available to other devices that are scanning for it.
3. Resolving Services
When a service is discovered, you may want to resolve it to get more information, such as the IP address and port number, to connect to it.
Step 1: Resolve the Service
To resolve a service, you call the resolveService() method on the NsdManager. Here's an example of how to resolve a discovered service:
private void resolveService(NsdServiceInfo serviceInfo) {
nsdManager.resolveService(serviceInfo, new NsdManager.ResolveListener() {
@Override
public void onServiceResolved(NsdServiceInfo resolvedServiceInfo) {
Log.d("NSD", "Service resolved: " + resolvedServiceInfo.getHost() + ":" + resolvedServiceInfo.getPort());
// Now you can connect to the service using the resolved IP address and port
}
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e("NSD", "Resolve failed: Error Code " + errorCode);
}
});
}
The onServiceResolved() callback provides the host and port of the service, which you can then use to connect to the service.
4. Stopping Discovery
Once you're done with the discovery process, it’s important to stop it. You can do this by calling the stopServiceDiscovery() method.
nsdManager.stopServiceDiscovery(discoveryListener);
This stops the discovery process and frees up resources.
Complete Code Example
Here's how everything ties together in a simple Android Activity:
public class MainActivity extends AppCompatActivity {
private NsdManager nsdManager;
private NsdManager.DiscoveryListener discoveryListener;
private NsdManager.RegistrationListener registrationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
// Discovery Listener
discoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onServiceFound(NsdServiceInfo service) {
Log.d("NSD", "Service found: " + service.getServiceName());
resolveService(service);
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e("NSD", "Discovery failed to start: Error Code " + errorCode);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e("NSD", "Stop discovery failed: Error Code " + errorCode);
}
@Override
public void onDiscoveryStarted(String serviceType) {
Log.d("NSD", "Discovery started for service type: " + serviceType);
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.d("NSD", "Discovery stopped for service type: " + serviceType);
}
};
// Registration Listener
registrationListener = new NsdManager.RegistrationListener() {
@Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
Log.d("NSD", "Service registered: " + serviceInfo.getServiceName());
}
@Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e("NSD", "Service registration failed: Error Code " + errorCode);
}
@Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
Log.d("NSD", "Service unregistered: " + serviceInfo.getServiceName());
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e("NSD", "Service unregistration failed: Error Code " + errorCode);
}
};
// Start service discovery
nsdManager.discoverServices("_http._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener);
// Register a service
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName("MyService");
serviceInfo.setServiceType("_http._tcp.");
serviceInfo.setPort(12345);
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
nsdManager.stopServiceDiscovery(discoveryListener);
}
}
Conclusion
This is a simple example of using NSDManager to discover and advertise services on the local network in Android. Whether you're creating a file sharing app, a multiplayer game, or an IoT device manager, NSDManager provides a straightforward way for Android devices to find and interact with each other over a local Wi-Fi network.
0 Comments