android.net.nsd.NsdManager Java Examples

The following examples show how to use android.net.nsd.NsdManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CastMediaRouteProvider.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) {
    if (android.os.Build.VERSION.SDK_INT < 16) {
        return;
    }

    if (request != null && request.isValid() && request.isActiveScan()) {
        if (request.getSelector() != null) {
            for (String category : request.getSelector().getControlCategories()) {
                if (CastMediaControlIntent.isCategoryForCast(category)) {
                    this.customCategories.add(category);
                }
            }
        }
        if (this.state == State.NOT_DISCOVERING) {
            mNsdManager.discoverServices("_googlecast._tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
            this.state = State.DISCOVERY_REQUESTED;
        }
    } else {
        if (this.state == State.DISCOVERING) {
            mNsdManager.stopServiceDiscovery(mDiscoveryListener);
            this.state = State.DISCOVERY_STOP_REQUESTED;
        }
    }
}
 
Example #2
Source File: YokeActivity.java    From yoke-android with MIT License 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, this);

    handler = new Handler();
    handler.post(new Runnable() {

        @Override
        public void run() {
            update();

            if (handler != null)
                handler.postDelayed(this, 20);
        }
    });

}
 
Example #3
Source File: MainActivity.java    From Rucky with GNU General Public License v3.0 6 votes vote down vote up
private void initPiResolveListener() {
    piResolveListener = new NsdManager.ResolveListener() {
        @Override
        public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
            piSocketConnected = false;
            piConnected = false;
        }

        @Override
        public void onServiceResolved(NsdServiceInfo serviceInfo) {
            mServiceInfo = serviceInfo;
            piIp = mServiceInfo.getHost().getHostAddress();
            piSocketConnected = false;
            piConnected = true;
        }
    };
}
 
Example #4
Source File: NsdHelper.java    From snapdroid with GNU General Public License v3.0 6 votes vote down vote up
private void initializeResolveListener() {
    mResolveListener = new NsdManager.ResolveListener() {
        @Override
        public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
            Log.d(TAG, "Resolve failed");
        }

        @Override
        public void onServiceResolved(NsdServiceInfo serviceInfo) {
            NsdServiceInfo info = serviceInfo;
            // sometimes it returns an IPv6 address...
            if (!info.getHost().getCanonicalHostName().contains(":"))
                listener.onResolved(NsdHelper.this, serviceInfo);
        }
    };
}
 
Example #5
Source File: NsdService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void expungeAllRequests() {
    int globalId, clientId, i;
    // TODO: to keep handler responsive, do not clean all requests for that client at once.
    for (i = 0; i < mClientIds.size(); i++) {
        clientId = mClientIds.keyAt(i);
        globalId = mClientIds.valueAt(i);
        mIdToClientInfoMap.remove(globalId);
        if (DBG) Slog.d(TAG, "Terminating client-ID " + clientId +
                " global-ID " + globalId + " type " + mClientRequests.get(clientId));
        switch (mClientRequests.get(clientId)) {
            case NsdManager.DISCOVER_SERVICES:
                stopServiceDiscovery(globalId);
                break;
            case NsdManager.RESOLVE_SERVICE:
                stopResolveService(globalId);
                break;
            case NsdManager.REGISTER_SERVICE:
                unregisterService(globalId);
                break;
            default:
                break;
        }
    }
    mClientIds.clear();
    mClientRequests.clear();
}
 
Example #6
Source File: NSDDiscoveryTools.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void doDiscovery(Context context) {
    synchronized (nsdToolsLock) {
        if (mNsdManager == null) {
            if(!connectNsdManager(context)) {
                return;
            }
        }

        if (state == NsdState.Init || state == NsdState.Idle) {
            initializeDiscoveryListener();
            state = NsdState.Discovery;
            mNsdManager.discoverServices(SERVICE_TYPE,
                    NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
        }
    }
}
 
Example #7
Source File: ShareActivity.java    From nitroshare-android with MIT License 5 votes vote down vote up
void start() {
    mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
    mNsdManager.discoverServices(Device.SERVICE_TYPE,
            NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);

    mThisDeviceName = new Settings(getContext()).getString(Settings.Key.DEVICE_NAME);
}
 
Example #8
Source File: NsdHelper.java    From NsdHelper with Apache License 2.0 5 votes vote down vote up
/**
 * Start discovering services.
 *
 * @param serviceType Service type, eg. "_http._tcp.". Typical names can be obtain from {@link com.rafakob.nsdhelper.NsdType}
 * @param serviceName When service is discovered it will check if it's name contains this text. It is NOT case sensitive.
 */
public void startDiscovery(String serviceType, String serviceName) {
    if (!mDiscoveryStarted) {
        mDiscoveryStarted = true;
        mDiscoveryTimer.start();
        mDiscoveryServiceType = serviceType;
        mDiscoveryServiceName = serviceName;
        mDiscoveryListener = new NsdListenerDiscovery(this);
        mNsdManager.discoverServices(mDiscoveryServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
    }
}
 
Example #9
Source File: MirrorService.java    From mirror with GNU General Public License v3.0 5 votes vote down vote up
private void onWifiConnected() {
    if (mIsWifiConnected) {
        return;
    }
    mIsWifiConnected = true;
    mIsWifiDisconnected = false;

    closeDiscoveryListenerSafety();
    RxBus.getInstance().post(new WifiConnectedEvent());

    mNsdManager = (NsdManager) getSystemService(NSD_SERVICE);
    mDiscoveryListener = buildDiscoveryListener();
    mNsdManager.discoverServices(SERVICE_TYPE, PROTOCOL_TYPE, mDiscoveryListener);
}
 
Example #10
Source File: ThetaDeviceDetectionFromLAN.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void onServiceFound(final NsdServiceInfo serviceInfo) {
    mLogger.info("onServiceFound: serviceInfo=" + serviceInfo);
    if (serviceInfo != null) {
        NsdManager nsdManager = mNsdManager;
        if (nsdManager != null) {
            nsdManager.resolveService(serviceInfo, mResolveListener);
        }
    }
}
 
Example #11
Source File: ThetaDeviceDetectionFromLAN.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public synchronized void start(final Context context) {
    if (mIsStarted) {
        return;
    }
    mIsStarted = true;
    mNsdManager = (NsdManager) context.getApplicationContext().getSystemService(Context.NSD_SERVICE);
    if (mNsdManager != null) {
        mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mNsdDiscoveryListener);
    }
}
 
Example #12
Source File: DiscoverResolver.java    From tinydnssd with MIT License 5 votes vote down vote up
public synchronized void start() {
    if (mStarted) {
        throw new IllegalStateException();
    }
    if (!mTransitioning) {
        discoverServices(mServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
        mTransitioning = true;
    }
    mStarted = true;
}
 
Example #13
Source File: DiscoverResolver.java    From tinydnssd with MIT License 5 votes vote down vote up
@Override
public void onDiscoveryStopped(String serviceType) {
    Log.d(TAG, "onDiscoveryStopped() serviceType = [" + serviceType + "]");
    if (mStarted) {
        discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, this);
    } else {
        mTransitioning = false;
    }
}
 
Example #14
Source File: ServerDiscovery.java    From habpanelviewer with GNU General Public License v3.0 5 votes vote down vote up
public synchronized void discover(final DiscoveryListener l) {
    if (mDiscoveryListener != null || mNsdManager == null) {
        return;
    }

    Log.v(TAG, "starting discovery...");
    mUrls.clear();

    ArrayList<String> types = new ArrayList<>();
    types.add("_openhab-server._tcp");
    types.add("_openhab-server-ssl._tcp");

    try {
        for (String serviceType : types) {
            try {
                Log.v(TAG, "starting discovery for " + serviceType + "...");
                mDiscoveryListener = new NsdDiscoveryListener(l);
                mNsdManager.discoverServices(
                        serviceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);

                Log.v(TAG, "waiting for results...");
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                Log.e(TAG, "Interrupted while waiting for discovery", e);
            } finally {
                Log.v(TAG, "stopping discovery for " + serviceType + "...");
                stopDiscovery();
            }
        }
    } finally {
        stopDiscovery();
    }

    Log.v(TAG, "discovery finished.");
}
 
Example #15
Source File: DiscoverResolverTest.java    From tinydnssd with MIT License 5 votes vote down vote up
public void testStartStop() {
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    verify(mDiscoverResolver, never()).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
    stopDiscoveryOnMainThread();
    verify(mDiscoverResolver).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
}
 
Example #16
Source File: NsdHelper.java    From NsdHelper with Apache License 2.0 5 votes vote down vote up
/**
 * Register new service with given serivce name, type and port.
 *
 * @param desiredServiceName Desired service name. If the name already exists in network it will be change to something like 'AppChat (1)'.
 * @param serviceType        Service type.
 * @param port               Service port.
 */
public void registerService(String desiredServiceName, String serviceType, int port) {
    if (port == 0) return;

    mRegisteredServiceInfo = new NsdServiceInfo();
    mRegisteredServiceInfo.setServiceName(desiredServiceName);
    mRegisteredServiceInfo.setServiceType(serviceType);
    mRegisteredServiceInfo.setPort(port);

    mRegistrationListener = new NsdListenerRegistration(this);
    mNsdManager.registerService(mRegisteredServiceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
 
Example #17
Source File: NsdHelper.java    From NsdHelper with Apache License 2.0 5 votes vote down vote up
/**
 * @param nsdManager  Android {@link NsdManager}.
 * @param nsdListener Service discovery listener.
 */
public NsdHelper(NsdManager nsdManager, NsdListener nsdListener) {
    this.mNsdManager = nsdManager;
    this.mNsdListener = nsdListener;
    this.mDiscoveryTimer = new DiscoveryTimer(this, mDiscoveryTimeout);
    this.mResolveQueue = new ResolveQueue(this);
}
 
Example #18
Source File: MainActivity.java    From Rucky with GNU General Public License v3.0 5 votes vote down vote up
private void initPiDiscoveryListener() {
    piDiscoveryListener = new NsdManager.DiscoveryListener() {
        @Override
        public void onStartDiscoveryFailed(String serviceType, int errorCode) {
            mNsdManager.stopServiceDiscovery(this);
        }

        @Override
        public void onStopDiscoveryFailed(String serviceType, int errorCode) {
            mNsdManager.stopServiceDiscovery(this);
        }

        @Override
        public void onDiscoveryStarted(String serviceType) {
        }

        @Override
        public void onDiscoveryStopped(String serviceType) {
        }

        @Override
        public void onServiceFound(NsdServiceInfo serviceInfo) {
            String name = serviceInfo.getServiceName();
            String type = serviceInfo.getServiceType();
            if (type.equals(SERVICE_TYPE) && name.contains("Rucky")) {
                mNsdManager.resolveService(serviceInfo, piResolveListener);
            }
        }

        @Override
        public void onServiceLost(NsdServiceInfo serviceInfo) {
        }
    };
}
 
Example #19
Source File: NsdHelper.java    From NsdHelper with Apache License 2.0 5 votes vote down vote up
/**
 * @param context     Context is only needed to create {@link NsdManager} instance.
 * @param nsdListener Service discovery listener.
 */
public NsdHelper(Context context, NsdListener nsdListener) {
    this.mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
    this.mNsdListener = nsdListener;
    this.mDiscoveryTimer = new DiscoveryTimer(this, mDiscoveryTimeout);
    this.mResolveQueue = new ResolveQueue(this);
}
 
Example #20
Source File: DiscoverResolverTest.java    From tinydnssd with MIT License 5 votes vote down vote up
public void testDebounceStartStop() {
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    stopDiscoveryOnMainThread();
    verify(mDiscoverResolver, never()).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    verify(mDiscoverResolver).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
}
 
Example #21
Source File: DiscoverResolverTest.java    From tinydnssd with MIT License 5 votes vote down vote up
public void testDebounceStartStopStart() {
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    stopDiscoveryOnMainThread();
    startDiscoveryOnMainThread();
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    verify(mDiscoverResolver, times(1)).discoverServices(anyString(), anyInt(), any(NsdManager.DiscoveryListener.class));
    verify(mDiscoverResolver, never()).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
}
 
Example #22
Source File: NsdHelper.java    From snapdroid with GNU General Public License v3.0 5 votes vote down vote up
public void startListening(String serviceType, String serviceName, NsdHelperListener listener) {
        stopListening();
        this.listener = listener;
        this.serviceName = serviceName;
        this.serviceType = serviceType;
        initializeResolveListener();
        initializeDiscoveryListener();
        mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
        mNsdManager.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
//        mNsdManager.discoverServices("_snapcast-jsonrpc._tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
    }
 
Example #23
Source File: DiscoverResolverTest.java    From tinydnssd with MIT License 5 votes vote down vote up
public void testDebounceStartStopStartStop() {
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    stopDiscoveryOnMainThread();
    startDiscoveryOnMainThread();
    stopDiscoveryOnMainThread();
    verify(mDiscoverResolver, never()).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    verify(mDiscoverResolver).stopServiceDiscovery(any(NsdManager.DiscoveryListener.class));
}
 
Example #24
Source File: NsdService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onEvent(int code, String raw, String[] cooked) {
    // TODO: NDC translates a message to a callback, we could enhance NDC to
    // directly interact with a state machine through messages
    NativeEvent event = new NativeEvent(code, raw, cooked);
    mNsdStateMachine.sendMessage(NsdManager.NATIVE_DAEMON_EVENT, event);
    return true;
}
 
Example #25
Source File: NsdService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void sendNsdStateChangeBroadcast(boolean isEnabled) {
    final Intent intent = new Intent(NsdManager.ACTION_NSD_STATE_CHANGED);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
    int nsdState = isEnabled ? NsdManager.NSD_STATE_ENABLED : NsdManager.NSD_STATE_DISABLED;
    intent.putExtra(NsdManager.EXTRA_NSD_STATE, nsdState);
    mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
}
 
Example #26
Source File: DiscoverResolverTest.java    From tinydnssd with MIT License 5 votes vote down vote up
public void testStartAgainWhileNsdIsStopping() {
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    stopDiscoveryOnMainThread();
    verify(mDiscoverResolver).stopServiceDiscovery(eq(mDiscoveryListener));
    // we call start() again before onDiscoveryStopped() => must restart discovery automatically
    startDiscoveryOnMainThread();
    verify(mDiscoverResolver, times(1)).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStopped(SERVICE_TYPE);
    verify(mDiscoverResolver, times(2)).discoverServices(eq(SERVICE_TYPE), eq(NsdManager.PROTOCOL_DNS_SD), any(NsdManager.DiscoveryListener.class));
    mDiscoveryListener.onDiscoveryStarted(SERVICE_TYPE);
    stopDiscoveryOnMainThread();
    verify(mDiscoverResolver, times(2)).stopServiceDiscovery(eq(mDiscoveryListener));
}
 
Example #27
Source File: NsdService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean processMessage(Message msg) {
    switch (msg.what) {
        case NsdManager.ENABLE:
            transitionTo(mEnabledState);
            break;
        default:
            return NOT_HANDLED;
    }
    return HANDLED;
}
 
Example #28
Source File: DiscoverResolver.java    From tinydnssd with MIT License 4 votes vote down vote up
protected void stopServiceDiscovery(NsdManager.DiscoveryListener listener) {
    ((NsdManager) mContext.getSystemService(Context.NSD_SERVICE)).stopServiceDiscovery(listener);
}
 
Example #29
Source File: DiscoverResolver.java    From tinydnssd with MIT License 4 votes vote down vote up
protected void discoverServices(String serviceType, int protocol, NsdManager.DiscoveryListener listener) {
    ((NsdManager) mContext.getSystemService(Context.NSD_SERVICE)).discoverServices(serviceType, protocol, listener);
}
 
Example #30
Source File: MonitorActivity.java    From protect-baby-monitor with GNU General Public License v3.0 4 votes vote down vote up
private void registerService(final int port)
{
    final NsdServiceInfo serviceInfo  = new NsdServiceInfo();
    serviceInfo.setServiceName("ProtectBabyMonitor");
    serviceInfo.setServiceType("_babymonitor._tcp.");
    serviceInfo.setPort(port);

    _registrationListener = new NsdManager.RegistrationListener()
    {
        @Override
        public void onServiceRegistered(NsdServiceInfo nsdServiceInfo) {
            // Save the service name.  Android may have changed it in order to
            // resolve a conflict, so update the name you initially requested
            // with the name Android actually used.
            final String serviceName = nsdServiceInfo.getServiceName();

            Log.i(TAG, "Service name: " + serviceName);

            MonitorActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run()
                {
                    final TextView statusText = (TextView) findViewById(R.id.textStatus);
                    statusText.setText(R.string.waitingForParent);

                    final TextView serviceText = (TextView) findViewById(R.id.textService);
                    serviceText.setText(serviceName);

                    final TextView portText = (TextView) findViewById(R.id.port);
                    portText.setText(Integer.toString(port));
                }
            });
        }

        @Override
        public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode)
        {
            // Registration failed!  Put debugging code here to determine why.
            Log.e(TAG, "Registration failed: " + errorCode);
        }

        @Override
        public void onServiceUnregistered(NsdServiceInfo arg0)
        {
            // Service has been unregistered.  This only happens when you call
            // NsdManager.unregisterService() and pass in this listener.

            Log.i(TAG, "Unregistering service");
        }

        @Override
        public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode)
        {
            // Unregistration failed.  Put debugging code here to determine why.

            Log.e(TAG, "Unregistration failed: " + errorCode);
        }
    };

    _nsdManager.registerService(
            serviceInfo, NsdManager.PROTOCOL_DNS_SD, _registrationListener);
}