jmDNS ServiceListener在被删除后触发

时间:2016-05-30 07:36:19

标签: java android jmdns

我使用jmDNS在wifi网络上找到一些服务。 问题是有时在服务解决后,我删除了这个监听器,它再次使用serviceResolved()方法触发。 jmDNS 3.4.1

private static JmDNS jmDNS;
private static ServiceType currentType;
private static ServiceListener currentListener;

public static Observable<String> getXXXIp(final ServiceType type,
                                             final WifiManager wifiManager) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override public void call(final Subscriber<? super String> subscriber) {

            InetAddress inetAddress = WifiUtils.getDeviceIpAddress(wifiManager.getConnectionInfo());

            try {
                jmDNS = JmDNS.create(inetAddress);
                currentType = type;
                currentListener = new ServiceListener() {
                    @Override public void serviceAdded(ServiceEvent event) { ... }

                    @Override public void serviceRemoved(ServiceEvent event) { }

                    @Override public void serviceResolved(ServiceEvent event) { ... }
                };
                jmDNS.addServiceListener(type.getCode(), currentListener);

            } catch (IOException e) {
                LOGGER.error("Exception occurred while searching " + type.getCode(), e);
                subscriber.onError(e);
            }
        }
    }).doOnNext(new Action1<String>() {
        @Override public void call(String s) {
            finish();
        }
    }).doOnError(new Action1<Throwable>() {
        @Override public void call(Throwable throwable) {
            finish();
        }
    });
}

private static void finish() {
    if (jmDNS != null) {
        LOGGER.info("jmDNS -> close");
        try {
            jmDNS.removeServiceListener(currentType.getCode(), currentListener);
            jmDNS.close();
        } catch (IOException e) {
            LOGGER.error("Cannot close jmDNS ", e);
        }
        jmDNS = null;
        currentListener = null;
    }
}

这是一个有点复杂的服务检查逻辑,所以我把它剪掉了,但是主要的事情是在一瞬间onNext()被调用一次所以调用方法finish()。我检查了侦听器的哈希码,我在finish()中无效,当调用此侦听器onServiceResolved()后,我检查它的哈希码,它是相同的。到底是怎么回事?有什么想法吗?

0 个答案:

没有答案