I'm trying out the official android NSDchat example to communicate between two android phones connecting to the same wifi network. After importing the project into eclipse, I changed only the target sdk to api level 22 instead of 16. I tried the app on various devices like samsung device with api 18,htc device with api 21, asus device with api 21 etc. and it works on some of them and doesnt work on others ,also it gives different errors on different devices. I got a null pointer exception while running the code and when I restarted the device ,the error went away. Also Is it that the demo app does not support higher api levels or is there any change that should be made in that code before running it ?
If you downloaded the NsdChat sample project from the Android Developers site (i.e. NsdChat.zip
or something along those lines), that project code is likely out of date.
Try using the latest code on the master branch instead... you can copy and paste it into your sample project from here.
Yes it works, but it's not straightforward. To connect both devices you need to do the following in this order:
- Click Register on device 1
- Click Register on device 2
- Wait 5 seconds and click Discover on device 1
- Wait 5 more seconds and click Connect on device 1
Then you can start sending messages normally.
Mainly, you need to make sure that both devices register the service. This is because the way this toy example handles the onServiceFound()
callback. It considers that if the service has exactly the same name it is using for registering it (i.e. NsdChat
), then it means that is the local instance of it. Hence, when you register a second device with the same service name, NSD is assigning it a different name (NsdChat(1)
), which is considered as a valid remote service to connect to.
The toy example is really just a starting point, which I think is good for learning the basics of NSD, but not really usable as it is.
This works for me:
@Override
public void onServiceFound(NsdServiceInfo service) {
if(mServiceName.length()==7)mServiceName=mServiceName.substring(0,mServiceName.length()-1);
Toast.makeText(mContext,"msg "+mServiceName, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Service discovery success" + service);
if (!service.getServiceType().equals(SERVICE_TYPE)) {
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same machine: " + mServiceName);
} else if (service.getServiceName().contains(mServiceName)){
mNsdManager.resolveService(service, mResolveListener);
}
}
mServiceName="NsdChat" has 7 characters. In this way you changes the name of the second machine on service found
© 2022 - 2024 — McMap. All rights reserved.