我正在尝试将NsdServiceInfo的mHost作为参数传递给NsdManager.discoveryListener.onServiceFound(),但它为null.
我有两个 Android设备,其中设备1是服务器,设备2是客户端.
我有两个 Android设备,其中设备1是服务器,设备2是客户端.
这是我在设备1中注册服务器的方式
public void registerService(int port,InetAddress myIp) { NsdServiceInfo serviceInfo = new NsdServiceInfo(); serviceInfo.setPort(port); serviceInfo.setServiceName(this.serviceName); serviceInfo.setServiceType(SERVICE_TYPE); serviceInfo.setHost(myIp); this.nsdManager.registerService( serviceInfo,NsdManager.PROTOCOL_DNS_SD,registrationListener); }
这就是我初始化discoveryListener的方法
public void initializediscoveryListener() { discoveryListener = new NsdManager.discoveryListener() { @Override public void onServiceFound(NsdServiceInfo service) { Log.d(TAG,"Service discovery success" + service); if (!service.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG,"UnkNown Service Type: " + service.getServiceType()); } else if (service.getHost() == myIp) { Log.d(TAG,"Same machine: " + service.getHost()); } else if (service.getServiceName().contains(serviceName)){ nsdManager.resolveService(service,resolveListener); } } ... } }
但是service.getHost()返回null.
有什么建议吗?
解决方法
我刚刚遇到了同样的问题,并在Google网页发现页面的帮助下设法解决了这个问题.
http://developer.android.com/training/connect-devices-wirelessly/nsd.html
问题是在发现服务时不知道连接信息.您必须先解决它,然后才能使用getHost().
你已经有了这条线:
nsdManager.resolveService(service,resolveListener);
resolveListener变量包含成功和失败的回调.您希望在成功确定连接信息后使用getHost().以下是Google的解决方案监听器:
public void initializeResolveListener() { resolveListener = new NsdManager.ResolveListener() { @Override public void onResolveFailed(NsdServiceInfo serviceInfo,int errorCode) { // Called when the resolve fails. Use the error code to debug. Log.e(TAG,"Resolve Failed" + errorCode); } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { Log.e(TAG,"Resolve Succeeded. " + serviceInfo); if (serviceInfo.getServiceName().equals(mServiceName)) { Log.d(TAG,"Same IP."); return; } service = serviceInfo; int port = service.getPort(); InetAddress host = service.getHost(); // getHost() will work Now } }; }