JmDNS
姚鹤龄
2023-12-01
1. 注册设备
public void publishService(BonjourServiceInfo svcInfo) {
synchronized (mJmdnsLock) {
ServiceInfo serviceInfo = ServiceInfo.create(svcInfo.getServiceType(),
svcInfo.getServiceName(),
svcInfo.getServicePort(),
0,
0,
svcInfo.getProperties());
if (!mSvcInfoList.containsKey(svcInfo.getServiceType())) {
mSvcInfoList.put(svcInfo.getServiceType(), serviceInfo);
try {
Log.v(TAG, String.format("registerService: %s (%s)",
svcInfo.getServiceType(),
svcInfo.getServiceName()));
mJmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
}
2. 取消注册
public void unpublishService(String svcType) {
synchronized (mJmdnsLock) {
ServiceInfo serviceInfo = mSvcInfoList.get(svcType);
if (serviceInfo != null) {
Log.v(TAG, String.format("unregisterService: %s", svcType));
mJmdns.unregisterService(serviceInfo);
mSvcInfoList.remove(svcType);
}
}
}
3. 查找设备
public void discoveryService(String serviceType) {
synchronized (mJmdnsLock) {
mSvcType.add(serviceType);
if (mStarted) {
Log.d(TAG, String.format("discoveryService: %s", serviceType));
mJmdns.addServiceListener(serviceType, this);
}
}
}
4.取消查找
public void undiscoveryService(String serviceType) {
synchronized (mJmdnsLock) {
mSvcType.remove(serviceType);
if (mStarted) {
Log.d(TAG, String.format("discoveryService: %s", serviceType));
mJmdns.removeServiceListener(serviceType, this);
}
}
}