Host is null in NsdServiceInfo of NsdManager.DiscoveryListener.onServiceFound

对着背影说爱祢 提交于 2019-12-05 07:52:53

I just ran across this same issue and managed to solve it with a little help from Google's page on network discovery.

http://developer.android.com/training/connect-devices-wirelessly/nsd.html

The problem is that the connection information isn't known when the service is discovered. You have to resolve it first before getHost() will work.

You already have the line:

    nsdManager.resolveService(service, resolveListener);

The resolveListener variable contains callbacks for success and failure. You want to use getHost() when the connection information has been successfully determined. Here's the resolve listener from 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
        }
    };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!